SET NOCOUNT ON




IF NOT EXISTS (SELECT * FROM [D9Master]..sysobjects WHERE id = OBJECT_ID(N'[D9Master]..[AccessAddress]') AND type in (N'U'))
BEGIN
CREATE TABLE [D9Master].[DBO].AccessAddress(
	ID INT IDENTITY (1,1) PRIMARY KEY ,      /*ID  主键*/
	LinkPath VARCHAR(100),   
	ServerKey VARCHAR(50) NOT NULL,  
 );
 END



IF NOT EXISTS (SELECT * FROM [D9Master]..sysobjects WHERE id = OBJECT_ID(N'[D9Master]..[Customer]') AND type in (N'U'))
BEGIN
CREATE TABLE [D9Master].[DBO].Customer 
(
    CustomerID int  NOT NULL ,          
    ServerID int,	   
	CompanyName varchar(256),
    Contacts varchar(100),
    TEL varchar(100), 
    DbName varchar(256),
    ZTName varchar(256),			  
    UserNum int,				
    CreatDate datetime,				  
    ExpiringDate datetime, 			
    Area varchar(256),				  
    Industry varchar(256),			  
	Comment varchar(256),			
    IsDelete int DEFAULT 0,		
    AppID 	 varchar(256), 
    Customerkey [varchar](200)        
)
END

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='DBConStr' AND b.Name='Customer'
)
BEGIN
	ALTER TABLE [D9Master]..[Customer] 
		ADD DBConStr VARCHAR(500) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='DBType' AND b.Name='Customer'
)
BEGIN
	ALTER TABLE [D9Master]..[Customer] 
		ADD DBType INT NOT NULL DEFAULT(1)
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='ServerKey' AND b.Name='Customer'
)
BEGIN
	ALTER TABLE [D9Master]..[Customer] 
		ADD ServerKey VARCHAR(50) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='LinsenceKey' AND b.Name='Customer'
)
BEGIN
	ALTER TABLE [D9Master]..[Customer] 
		ADD LinsenceKey VARCHAR(200) NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='PublicKey' AND b.Name='Customer'
)
BEGIN
	ALTER TABLE [D9Master]..[Customer] 
		ADD PublicKey VARCHAR(20) NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='DbInfoID' AND b.Name='Customer'
)
BEGIN
	ALTER TABLE [D9Master]..[Customer] 
		ADD DbInfoID INT 
END
GO

--IF NOT EXISTS (SELECT a.Name FROM [D9Master].[DBO].syscolumns a	INNER JOIN [D9Master].[DBO].sysobjects	b ON a.object_id = b.object_id WHERE b.Name='Customer' AND a.Name='DBConStr')
--	ALTER TABLE [D9Master].dbo.Customer ADD DBConStr VARCHAR(500) NOT NULL default ('') 
--IF NOT EXISTS (SELECT a.Name FROM [D9Master].[DBO].syscolumns a	INNER JOIN [D9Master].[DBO].sysobjects	b ON a.object_id = b.object_id WHERE b.Name='Customer' AND a.Name='DBType')
--	ALTER TABLE [D9Master].dbo.Customer ADD DBType INT NOT NULL default (1) 
--IF NOT EXISTS (SELECT a.Name FROM [D9Master].[DBO].sys.columns a	INNER JOIN [D9Master].[DBO].sysobjects	b ON a.object_id = b.object_id WHERE b.Name='Customer' AND a.Name='ServerKey')
--	ALTER TABLE [D9Master].dbo.Customer ADD ServerKey VARCHAR(50)  
--IF NOT EXISTS (SELECT a.Name FROM [D9Master].[DBO].syscolumns a	INNER JOIN [D9Master].[DBO].sysobjects	b ON a.object_id = b.object_id WHERE b.Name='Customer' AND a.Name='LinsenceKey')
--	ALTER TABLE [D9Master].dbo.Customer ADD LinsenceKey VARCHAR(2000) 
--IF NOT EXISTS (SELECT a.Name FROM [D9Master].[DBO].syscolumns a	INNER JOIN [D9Master].[DBO].sysobjects	b ON a.object_id = b.object_id WHERE b.Name='Customer' AND a.Name='PublicKey')
--	ALTER TABLE [D9Master].dbo.Customer ADD PublicKey VARCHAR(200)  
--IF NOT EXISTS (SELECT a.Name FROM [D9Master].[DBO].syscolumns a	INNER JOIN [D9Master].[DBO].sysobjects	b ON a.object_id = b.object_id WHERE b.Name='Customer' AND a.Name='DbInfoID')
--	ALTER TABLE [D9Master].dbo.Customer ADD DbInfoID INT  



-- D9AccountList

IF NOT EXISTS (SELECT * FROM [D9Master]..sysobjects WHERE id = OBJECT_ID(N'[D9Master]..[D9AccountList]') AND type in (N'U'))
BEGIN
	CREATE TABLE  [D9Master].[DBO].D9AccountList
	(
			AId              INT IDENTITY (1,1) PRIMARY KEY ,		--D9账套列表
			UserCode         VARCHAR(100),							--账套编号
			FullName         VARCHAR(100),							--账套名称
			DbName           VARCHAR(100),							--数据库名称
			DogNumber        VARCHAR(100),							--狗号
			RegistionCode    VARCHAR(200),							--注册码 以狗号为密匙加密
			RegDate			 DATETIME,								--注册日期
			ExpiringDate     DATETIME,								--到期日期
			EnExpiringDate   VARCHAR(2000),							--加密后的到期日期
			RyDays           INT,									--更新周期
			EnRyDays		 VARCHAR(2000) NOT NULL DEFAULT('') ,	--加密验证天数
			RyDate           DATETIME,								--最后一次更新日期
			EnRyDate         VARCHAR(2000),							--加密后的最后一次更新日期 以狗号为密匙加密
			OffLineFlag      INT DEFAULT(0),						--离线标识
			EnOffLineFlag    VARCHAR(200) DEFAULT(''),				--加密后的离线标识 以狗号为密匙加密
			Deleted          INT,									--是否删除
			UserNumber       INT,									--用户数
			EnUserNumber     VARCHAR(2000),							--加密后的用户数
			VersionNo        VARCHAR(2000),							--版本号
			IsSysEdit        BIT NOT NULL DEFAULT(0),				--是否同步
			RegisterName	 VARCHAR(400),							--注册客户名称
			LimitDays		 INT DEFAULT(0)	,						--免注册时长
			regFlag			 INT NOT NULL DEFAULT(0),				--注册标志
			ztVersion		 INT,									--V3:1 A8:2 V1:3 T3:4 T6:5 T9:6 D9:7
			DogServerDate	 DATETIME,								--软狗服务器日期
			AccountNumber	 INT DEFAULT(1),						--授权账套数
			EnFinDate		 VARCHAR(2000) DEFAULT(''),				--加密后的D9产品终的到期日期		
			islimitlogin	 INT DEFAULT(0),						--并发登录限制
			lastLoginTime	 DATETIME DEFAULT(NULL),				--最后登录时间
			lastLoginUser	 VARCHAR(100) DEFAULT(''),				--最后登录用户名
			dogLog			NTEXT DEFAULT(''),						--狗日志
			showVerificationCode	INT NOT NULL DEFAULT(1),		--是否显示验证码
			d9phonecode		VARCHAR(50) NOT NULL DEFAULT(REPLACE(NEWID(),'-','')),		--物联通手机版使用
			remark			VARCHAR(1000) NULL DEFAULT('')			--备注
	);
END


IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='remark' AND b.Name='D9AccountList'
)
BEGIN
	ALTER TABLE [D9Master]..[D9AccountList] 
		ADD remark VARCHAR(1000) NULL DEFAULT('')
END
GO
UPDATE [D9Master]..[D9AccountList] SET remark = '' WHERE remark IS NULL
GO



IF NOT EXISTS (SELECT * FROM [D9Master]..sysobjects WHERE id = OBJECT_ID(N'[D9Master]..[D9DBInfo]') AND type in (N'U'))
BEGIN
CREATE TABLE [D9Master].[DBO].D9DBInfo 
(
    ID INT IDENTITY (1,1) PRIMARY KEY ,      /*ID  主键*/
    APPID  VARCHAR(32) ,          /* 操作员ID*/
    ConfigName VARCHAR(100),        /*配置名称*/
    ServerNode VARCHAR(100),        /*服务器节点*/
    AccessKey VARCHAR(100),         /*阿里云rds的AccessKey*/
    DBType int,                     /*数据库类型  0 代表rds  1代表自建DB*/
    DBPath  varchar(100),           /*自建db存储地址/rds实例ID*/
    LinkPath varchar(256),          /*连接地址*/
    Point varchar(50),              /*端口号*/
    UserName  varchar(50),          /*数据库用户名*/
    [PASSWORD] varchar(100)         /*数据库密码*/
)
END

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='AccessKeySecret' AND b.Name='D9DBInfo'
)
BEGIN
	ALTER TABLE [D9Master]..[D9DBInfo] 
		ADD AccessKeySecret VARCHAR(500) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='ServerKey' AND b.Name='D9DBInfo'
)
BEGIN
	ALTER TABLE [D9Master]..[D9DBInfo] 
		ADD ServerKey VARCHAR(50) NOT NULL DEFAULT('')
END
GO

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='BakPath' AND b.Name='D9DBInfo'
)
BEGIN
	ALTER TABLE [D9Master]..[D9DBInfo] 
		ADD BakPath VARCHAR(5100) NOT NULL DEFAULT('')
END
GO

--IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='D9DBInfo' AND a.Name='AccessKeySecret')
--	ALTER TABLE dbo.D9DBInfo ADD AccessKeySecret VARCHAR(500) NOT NULL default ('') 
--IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='D9DBInfo' AND a.Name='ServerKey')
--	ALTER TABLE dbo.D9DBInfo ADD ServerKey VARCHAR(50)  
--IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='D9DBInfo' AND a.Name='BakPath')
--	ALTER TABLE dbo.D9DBInfo ADD BakPath varchar(100)


GO	



IF NOT EXISTS (SELECT * FROM [D9Master]..sysobjects WHERE id = OBJECT_ID(N'[D9Master]..[MasterUser]') AND type in (N'U'))
BEGIN
CREATE TABLE [D9Master].[DBO].MasterUser 
(
    ID INT IDENTITY (1,1) PRIMARY KEY  /*ID  主键*/
    ,UserName  VARCHAR(32)  NOT NULL DEFAULT('')           /* 操作员ID*/
    ,[PASSWORD] varchar(50)   NOT NULL DEFAULT('')         /*操作员密码*/
    ,loginCount INT NOT NULL DEFAULT(0)
    ,APPID  VARCHAR(32)
    ,ServerKey VARCHAR(50) NOT NULL 
)
END
IF NOT EXISTS(SELECT TOP 1 1 FROM [D9Master].[DBO].MasterUser WHERE UserName = 'master')
BEGIN
	INSERT INTO [D9Master].[DBO].masteruser(username,[password],logincount,APPID,ServerKey) values('master','',0,'0','')
END
GO
IF EXISTS(SELECT TOP 1 1 FROM [D9Master].[DBO].MasterUser WHERE UserName = 'master')
BEGIN
	UPDATE [D9Master].[DBO].MasterUser  SET UserName = 'master' WHERE UserName = 'master'
END
GO



IF NOT EXISTS (SELECT * FROM [D9Master]..sysobjects WHERE id = OBJECT_ID(N'[D9Master]..[ServersRegist]') AND type in (N'U'))
BEGIN
	CREATE TABLE [D9Master].[DBO].ServersRegist 
	(
		ServerID int  NOT NULL,                                     
		DoMainName [varchar](200) NOT NULL DEFAULT '',             
		AppID   [varchar](32) NOT NULL ,                          /*代理标识*/
		ServerKey [varchar](50),                                  /*服务器标识 */ 
		Lasttime  datetime,                                        /*最后验证时间*/
		encrykey  [varchar] (2000),                                   /*密钥*/
		linsencekey [varchar] (2000),
		[version]    [varchar] (200)
		,Token		 VARCHAR(50) /*Token过期时间*/
	)

END

IF NOT EXISTS(
	SELECT a.Name,b.name 
	FROM D9Master..syscolumns a
		INNER JOIN D9Master..sysobjects b ON a.ID=b.ID
	WHERE a.Name='Token' AND b.Name='ServersRegist'
)
BEGIN
	ALTER TABLE [D9Master]..[ServersRegist] 
		ADD Token VARCHAR(50) NOT NULL DEFAULT('')
END
GO


--IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='ServersRegist' AND a.Name='Token')
--	ALTER TABLE ServersRegist ADD Token VARCHAR(50)  default ('') 

 /*
 --IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='ServersRegist' AND a.Name='RefreshCode')
	--ALTER TABLE ServersRegist ADD RefreshCode VARCHAR(50)  default ('') 

 
 
 --IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='ServersRegist' AND a.Name='ExpTime')
	--ALTER TABLE ServersRegist ADD ExpTime datetime

 
 
 
 --IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='ServersRegist' AND a.Name='RefreshTime')
	--ALTER TABLE ServersRegist ADD RefreshTime datetime   
 */
 
GO 



IF EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'TVP_BD_Goods_Price_Type' AND ss.name = N'dbo')
BEGIN
	IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UP_BD_Insert_BD_Goods]') AND TYPE in (N'P', N'PC'))
		DROP PROC UP_BD_Insert_BD_Goods;
		
	DROP TYPE TVP_BD_Goods_Price_Type;
END
GO

/*
	作者：谢吉康
	日期：2020-2-8
	描述：商品基本信息单位价格信息
*/
CREATE TYPE TVP_BD_Goods_Price_Type AS TABLE
(
	Unit				VARCHAR(100),		--单位名称
	Convfactor			NUMERIC(24,10),		--换算率
	BarCode				VARCHAR(100),		--条形码
	Price1				NUMERIC(24,10),		--预设价1
	Price2				NUMERIC(24,10),		--预设价2
	Price3				NUMERIC(24,10),		--预设价3
	Price4				NUMERIC(24,10),		--预设价4
	Price5				NUMERIC(24,10)		--预设价5
)
GO




/*====================== TABLETYPE: [TVP_Paging_Param] ======================*/
IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OT_Paging]') AND type in (N'P', N'PC')) 
DROP PROCEDURE [UP_OT_Paging]  
IF  EXISTS (SELECT 1 FROM sys.types WHERE is_table_type=1 AND name = N'TVP_Paging_Param') 
DROP TYPE [TVP_Paging_Param]
BEGIN 
CREATE TYPE [TVP_Paging_Param] AS TABLE
(
    [ParaName] [varchar](1000) NOT NULL DEFAULT '',
	[DataType] [varchar](1000) NOT NULL DEFAULT '',
	[ParaValue] [varchar](max) NOT NULL DEFAULT ''
)
END 



/*====================== TABLETYPE: [TVP_Type] ======================*/
IF  EXISTS (SELECT 1 FROM sys.types WHERE is_table_type=1 AND name = N'TVP_Type') 
DROP TYPE [TVP_Type]
BEGIN 
CREATE TYPE [TVP_Type] AS TABLE
(
    [TypeID] [INT] NOT NULL DEFAULT 0,
	[ChildTypeID] [INT] NOT NULL DEFAULT 0
)
END 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_ARAP]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_ARAP]
(
    [ARAPID] [BIGINT] IDENTITY(1,1) NOT NULL,
    [BTypeID] [int] NOT NULL,
    [QcAR] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QcAR] DEFAULT (0),
    [QcAP] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QcAP] DEFAULT (0),
    [QcBR] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QcBR] DEFAULT (0),
    [QcBP] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QcBP] DEFAULT (0),
    [ARPaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_ARPaidTotal] DEFAULT (0),
    [APPaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_APPaidTotal] DEFAULT (0),
    [QmAR] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QmAR] DEFAULT (0),
    [QmAP] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QmAP] DEFAULT (0),
    [QmBR] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QmBR] DEFAULT (0),
    [QmBP] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_ARAP_QmBP] DEFAULT (0),
    CONSTRAINT [PK_BD_ARAP] PRIMARY KEY NONCLUSTERED ([ARAPID])
)
END

IF NOT  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_ARAP]') AND name = N'IXC_BD_ARAP_BTypeID') 
	CREATE UNIQUE CLUSTERED  INDEX IXC_BD_ARAP_BTypeID on BD_ARAP ([BTypeID]) WITH (FILLFACTOR = 90);

 




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Area]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Area]
(
    [AreaID] [int] IDENTITY(1,1) NOT NULL,
    [AreaNO] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_AreaNO] DEFAULT '',
    [AreaName] [varchar](100) NOT NULL,
    [AreaAbbName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_AreaAbbName] DEFAULT '',
    [Spell] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_Spell] DEFAULT '',
    [Path] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_Path] DEFAULT '',
    [ParID] [int] NOT NULL CONSTRAINT [DF_BD_Area_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_BD_Area_Lvl] DEFAULT (0),
    [SonNum] [int] NOT NULL CONSTRAINT [DF_BD_Area_SonNum] DEFAULT (0),
    [AreaType] [bit] NOT NULL CONSTRAINT [DF_BD_Area_AreaType] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Area_Stt] DEFAULT (1),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_BD_Area] PRIMARY KEY CLUSTERED ([AreaID])
)
SET IDENTITY_INSERT [BD_Area] ON
    INSERT INTO [BD_Area] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1,'ALL','全部区域','','','',0,0,0,0,1,NULL);
SET IDENTITY_INSERT [BD_Area] OFF
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area]') AND name = N'IX_BD_Area_AreaIDAreaName') 
	CREATE  INDEX IX_BD_Area_AreaIDAreaName on BD_Area ([AreaID],[AreaName]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area]') AND name = N'IX_BD_Area_ParID') 
	CREATE  INDEX IX_BD_Area_ParID on BD_Area ([ParID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area]') AND name = N'IX_BD_Area_AreaNO') 
	CREATE  INDEX IX_BD_Area_AreaNO on BD_Area ([AreaNO]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area]') AND name = N'IX_BD_Area_AreaName') 
	CREATE  INDEX IX_BD_Area_AreaName on BD_Area ([AreaName]) WITH (FILLFACTOR = 90);




/*====================== TABLE: [BD_Area_Sys] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Area_Sys]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Area_Sys]
(
    [AreaID] [int] IDENTITY(1,1) NOT NULL,
    [AreaNO] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_Sys_AreaNO] DEFAULT '',
    [AreaName] [varchar](100) NOT NULL,
    [AreaAbbName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_Sys_AreaAbbName] DEFAULT '',
    [Spell] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_Sys_Spell] DEFAULT '',
    [Path] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Area_Sys_Path] DEFAULT '',
    [ParID] [int] NOT NULL CONSTRAINT [DF_BD_Area_Sys_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_BD_Area_Sys_Lvl] DEFAULT (0),
    [SonNum] [int] NOT NULL CONSTRAINT [DF_BD_Area_Sys_SonNum] DEFAULT (0),
    [AreaType] [bit] NOT NULL CONSTRAINT [DF_BD_Area_Sys_AreaType] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Area_Sys_Stt] DEFAULT (1),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_BD_Area_Sys] PRIMARY KEY CLUSTERED ([AreaID])
)
SET IDENTITY_INSERT [BD_Area_Sys] ON
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1,'ALL','全部区域','','','',0,0,34,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2,'110000','北京市','','','00001',1,1,2,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3,'120000','天津市','','','00002',1,1,2,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (4,'130000','河北省','','','00003',1,1,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (5,'140000','山西省','','','00004',1,1,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (6,'150000','内蒙古自治区','','','00005',1,1,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (7,'210000','辽宁省','','','00006',1,1,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (8,'220000','吉林省','','','00007',1,1,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (9,'230000','黑龙江省','','','00008',1,1,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (10,'310000','上海市','','','00009',1,1,2,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (11,'320000','江苏省','','','00010',1,1,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (12,'330000','浙江省','','','00011',1,1,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (13,'340000','安徽省','','','00012',1,1,16,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (14,'350000','福建省','','','00013',1,1,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (15,'360000','江西省','','','00014',1,1,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (16,'370000','山东省','','','00015',1,1,17,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (17,'410000','河南省','','','00016',1,1,18,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (18,'420000','湖北省','','','00017',1,1,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (19,'430000','湖南省','','','00018',1,1,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (20,'440000','广东省','','','00019',1,1,21,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (21,'450000','广西壮族自治区','','','00020',1,1,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (22,'460000','海南省','','','00021',1,1,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (23,'500000','重庆市','','','00022',1,1,2,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (24,'510000','四川省','','','00023',1,1,21,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (25,'520000','贵州省','','','00024',1,1,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (26,'530000','云南省','','','00025',1,1,16,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (27,'540000','西藏自治区','','','00026',1,1,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (28,'610000','陕西省','','','00027',1,1,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (29,'620000','甘肃省','','','00028',1,1,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (30,'630000','青海省','','','00029',1,1,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (31,'640000','宁夏回族自治区','','','00030',1,1,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (32,'650000','新疆维吾尔自治区','','','00031',1,1,15,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (33,'710000','台湾省','','','00032',1,1,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (34,'810000','香港特别行政区','','','00033',1,1,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (35,'820000','澳门特别行政区','','','00034',1,1,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (36,'110100','北京市辖区','','','0000100001',2,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (37,'110200','县','','','0000100002',2,2,2,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (38,'120100','天津市辖区','','','0000200001',3,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (39,'120200','县','','','0000200002',3,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (40,'130100','石家庄市','','','0000300001',4,2,24,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (41,'130200','唐山市','','','0000300002',4,2,15,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (42,'130300','秦皇岛市','','','0000300003',4,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (43,'130400','邯郸市','','','0000300004',4,2,20,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (44,'130500','邢台市','','','0000300005',4,2,20,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (45,'130600','保定市','','','0000300006',4,2,26,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (46,'130700','张家口市','','','0000300007',4,2,18,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (47,'130800','承德市','','','0000300008',4,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (48,'130900','沧州市','','','0000300009',4,2,17,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (49,'131000','廊坊市','','','0000300010',4,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (50,'131100','衡水市','','','0000300011',4,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (51,'140100','太原市','','','0000400001',5,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (52,'140200','大同市','','','0000400002',5,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (53,'140300','阳泉市','','','0000400003',5,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (54,'140400','长治市','','','0000400004',5,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (55,'140500','晋城市','','','0000400005',5,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (56,'140600','朔州市','','','0000400006',5,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (57,'140700','晋中市','','','0000400007',5,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (58,'140800','运城市','','','0000400008',5,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (59,'140900','忻州市','','','0000400009',5,2,15,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (60,'141000','临汾市','','','0000400010',5,2,18,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (61,'141100','吕梁市','','','0000400011',5,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (62,'150100','呼和浩特市','','','0000500001',6,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (63,'150200','包头市','','','0000500002',6,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (64,'150300','乌海市','','','0000500003',6,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (65,'150400','赤峰市','','','0000500004',6,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (66,'150500','通辽市','','','0000500005',6,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (67,'150600','鄂尔多斯市','','','0000500006',6,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (68,'150700','呼伦贝尔市','','','0000500007',6,2,15,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (69,'150800','巴彦淖尔市','','','0000500008',6,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (70,'150900','乌兰察布市','','','0000500009',6,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (71,'152200','兴安盟','','','0000500010',6,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (72,'152500','锡林郭勒盟','','','0000500011',6,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (73,'152900','阿拉善盟','','','0000500012',6,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (74,'210100','沈阳市','','','0000600001',7,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (75,'210200','大连市','','','0000600002',7,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (76,'210300','鞍山市','','','0000600003',7,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (77,'210400','抚顺市','','','0000600004',7,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (78,'210500','本溪市','','','0000600005',7,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (79,'210600','丹东市','','','0000600006',7,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (80,'210700','锦州市','','','0000600007',7,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (81,'210800','营口市','','','0000600008',7,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (82,'210900','阜新市','','','0000600009',7,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (83,'211000','辽阳市','','','0000600010',7,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (84,'211100','盘锦市','','','0000600011',7,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (85,'211200','铁岭市','','','0000600012',7,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (86,'211300','朝阳市','','','0000600013',7,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (87,'211400','葫芦岛市','','','0000600014',7,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (88,'220100','长春市','','','0000700001',8,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (89,'220200','吉林市','','','0000700002',8,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (90,'220300','四平市','','','0000700003',8,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (91,'220400','辽源市','','','0000700004',8,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (92,'220500','通化市','','','0000700005',8,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (93,'220600','白山市','','','0000700006',8,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (94,'220700','松原市','','','0000700007',8,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (95,'220800','白城市','','','0000700008',8,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (96,'222400','延边朝鲜族自治州','','','0000700009',8,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (97,'230100','哈尔滨市','','','0000800001',9,2,19,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (98,'230200','齐齐哈尔市','','','0000800002',9,2,17,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (99,'230300','鸡西市','','','0000800003',9,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (100,'230400','鹤岗市','','','0000800004',9,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (101,'230500','双鸭山市','','','0000800005',9,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (102,'230600','大庆市','','','0000800006',9,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (103,'230700','伊春市','','','0000800007',9,2,18,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (104,'230800','佳木斯市','','','0000800008',9,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (105,'230900','七台河市','','','0000800009',9,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (106,'231000','牡丹江市','','','0000800010',9,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (107,'231100','黑河市','','','0000800011',9,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (108,'231200','绥化市','','','0000800012',9,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (109,'232700','大兴安岭地区','','','0000800013',9,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (110,'310100','上海市辖区','','','0000900001',10,2,16,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (111,'310200','县','','','0000900002',10,2,1,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (112,'320100','南京市','','','0001000001',11,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (113,'320200','无锡市','','','0001000002',11,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (114,'320300','徐州市','','','0001000003',11,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (115,'320400','常州市','','','0001000004',11,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (116,'320500','苏州市','','','0001000005',11,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (117,'320600','南通市','','','0001000006',11,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (118,'320700','连云港市','','','0001000007',11,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (119,'320800','淮安市','','','0001000008',11,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (120,'320900','盐城市','','','0001000009',11,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (121,'321000','扬州市','','','0001000010',11,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (122,'321100','镇江市','','','0001000011',11,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (123,'321200','泰州市','','','0001000012',11,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (124,'321300','宿迁市','','','0001000013',11,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (125,'330100','杭州市','','','0001100001',12,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (126,'330200','宁波市','','','0001100002',12,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (127,'330300','温州市','','','0001100003',12,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (128,'330400','嘉兴市','','','0001100004',12,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (129,'330500','湖州市','','','0001100005',12,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (130,'330600','绍兴市','','','0001100006',12,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (131,'330700','金华市','','','0001100007',12,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (132,'330800','衢州市','','','0001100008',12,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (133,'330900','舟山市','','','0001100009',12,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (134,'331000','台州市','','','0001100010',12,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (135,'331100','丽水市','','','0001100011',12,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (136,'340100','合肥市','','','0001200001',13,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (137,'340200','芜湖市','','','0001200002',13,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (138,'340300','蚌埠市','','','0001200003',13,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (139,'340400','淮南市','','','0001200004',13,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (140,'340500','马鞍山市','','','0001200005',13,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (141,'340600','淮北市','','','0001200006',13,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (142,'340700','铜陵市','','','0001200007',13,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (143,'340800','安庆市','','','0001200008',13,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (144,'341000','黄山市','','','0001200009',13,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (145,'341100','滁州市','','','0001200010',13,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (146,'341200','阜阳市','','','0001200011',13,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (147,'341300','宿州市','','','0001200012',13,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (148,'341500','六安市','','','0001200013',13,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (149,'341600','亳州市','','','0001200014',13,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (150,'341700','池州市','','','0001200015',13,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (151,'341800','宣城市','','','0001200016',13,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (152,'350100','福州市','','','0001300001',14,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (153,'350200','厦门市','','','0001300002',14,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (154,'350300','莆田市','','','0001300003',14,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (155,'350400','三明市','','','0001300004',14,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (156,'350500','泉州市','','','0001300005',14,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (157,'350600','漳州市','','','0001300006',14,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (158,'350700','南平市','','','0001300007',14,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (159,'350800','龙岩市','','','0001300008',14,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (160,'350900','宁德市','','','0001300009',14,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (161,'360100','南昌市','','','0001400001',15,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (162,'360200','景德镇市','','','0001400002',15,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (163,'360300','萍乡市','','','0001400003',15,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (164,'360400','九江市','','','0001400004',15,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (165,'360500','新余市','','','0001400005',15,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (166,'360600','鹰潭市','','','0001400006',15,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (167,'360700','赣州市','','','0001400007',15,2,19,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (168,'360800','吉安市','','','0001400008',15,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (169,'360900','宜春市','','','0001400009',15,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (170,'361000','抚州市','','','0001400010',15,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (171,'361100','上饶市','','','0001400011',15,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (172,'370100','济南市','','','0001500001',16,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (173,'370200','青岛市','','','0001500002',16,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (174,'370300','淄博市','','','0001500003',16,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (175,'370400','枣庄市','','','0001500004',16,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (176,'370500','东营市','','','0001500005',16,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (177,'370600','烟台市','','','0001500006',16,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (178,'370700','潍坊市','','','0001500007',16,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (179,'370800','济宁市','','','0001500008',16,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (180,'370900','泰安市','','','0001500009',16,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (181,'371000','威海市','','','0001500010',16,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (182,'371100','日照市','','','0001500011',16,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (183,'371200','莱芜市','','','0001500012',16,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (184,'371300','临沂市','','','0001500013',16,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (185,'371400','德州市','','','0001500014',16,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (186,'371500','聊城市','','','0001500015',16,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (187,'371600','滨州市','','','0001500016',16,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (188,'371700','菏泽市','','','0001500017',16,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (189,'410100','郑州市','','','0001600001',17,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (190,'410200','开封市','','','0001600002',17,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (191,'410300','洛阳市','','','0001600003',17,2,16,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (192,'410400','平顶山市','','','0001600004',17,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (193,'410500','安阳市','','','0001600005',17,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (194,'410600','鹤壁市','','','0001600006',17,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (195,'410700','新乡市','','','0001600007',17,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (196,'410800','焦作市','','','0001600008',17,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (197,'410900','濮阳市','','','0001600009',17,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (198,'411000','许昌市','','','0001600010',17,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (199,'411100','漯河市','','','0001600011',17,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (200,'411200','三门峡市','','','0001600012',17,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (201,'411300','南阳市','','','0001600013',17,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (202,'411400','商丘市','','','0001600014',17,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (203,'411500','信阳市','','','0001600015',17,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (204,'411600','周口市','','','0001600016',17,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (205,'411700','驻马店市','','','0001600017',17,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (206,'419000','省直辖县级行政区划','','','0001600018',17,2,1,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (207,'420100','武汉市','','','0001700001',18,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (208,'420200','黄石市','','','0001700002',18,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (209,'420300','十堰市','','','0001700003',18,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (210,'420500','宜昌市','','','0001700004',18,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (211,'420600','襄阳市','','','0001700005',18,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (212,'420700','鄂州市','','','0001700006',18,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (213,'420800','荆门市','','','0001700007',18,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (214,'420900','孝感市','','','0001700008',18,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (215,'421000','荆州市','','','0001700009',18,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (216,'421100','黄冈市','','','0001700010',18,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (217,'421200','咸宁市','','','0001700011',18,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (218,'421300','随州市','','','0001700012',18,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (219,'422800','恩施土家族苗族自治州','','','0001700013',18,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (220,'429000','省直辖县级行政区划','','','0001700014',18,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (221,'430100','长沙市','','','0001800001',19,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (222,'430200','株洲市','','','0001800002',19,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (223,'430300','湘潭市','','','0001800003',19,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (224,'430400','衡阳市','','','0001800004',19,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (225,'430500','邵阳市','','','0001800005',19,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (226,'430600','岳阳市','','','0001800006',19,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (227,'430700','常德市','','','0001800007',19,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (228,'430800','张家界市','','','0001800008',19,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (229,'430900','益阳市','','','0001800009',19,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (230,'431000','郴州市','','','0001800010',19,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (231,'431100','永州市','','','0001800011',19,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (232,'431200','怀化市','','','0001800012',19,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (233,'431300','娄底市','','','0001800013',19,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (234,'433100','湘西土家族苗族自治州','','','0001800014',19,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (235,'440100','广州市','','','0001900001',20,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (236,'440200','韶关市','','','0001900002',20,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (237,'440300','深圳市','','','0001900003',20,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (238,'440400','珠海市','','','0001900004',20,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (239,'440500','汕头市','','','0001900005',20,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (240,'440600','佛山市','','','0001900006',20,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (241,'440700','江门市','','','0001900007',20,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (242,'440800','湛江市','','','0001900008',20,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (243,'440900','茂名市','','','0001900009',20,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (244,'441200','肇庆市','','','0001900010',20,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (245,'441300','惠州市','','','0001900011',20,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (246,'441400','梅州市','','','0001900012',20,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (247,'441500','汕尾市','','','0001900013',20,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (248,'441600','河源市','','','0001900014',20,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (249,'441700','阳江市','','','0001900015',20,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (250,'441800','清远市','','','0001900016',20,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (251,'441900','东莞市','','','0001900017',20,2,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (252,'442000','中山市','','','0001900018',20,2,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (253,'445100','潮州市','','','0001900019',20,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (254,'445200','揭阳市','','','0001900020',20,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (255,'445300','云浮市','','','0001900021',20,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (256,'450100','南宁市','','','0002000001',21,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (257,'450200','柳州市','','','0002000002',21,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (258,'450300','桂林市','','','0002000003',21,2,18,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (259,'450400','梧州市','','','0002000004',21,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (260,'450500','北海市','','','0002000005',21,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (261,'450600','防城港市','','','0002000006',21,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (262,'450700','钦州市','','','0002000007',21,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (263,'450800','贵港市','','','0002000008',21,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (264,'450900','玉林市','','','0002000009',21,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (265,'451000','百色市','','','0002000010',21,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (266,'451100','贺州市','','','0002000011',21,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (267,'451200','河池市','','','0002000012',21,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (268,'451300','来宾市','','','0002000013',21,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (269,'451400','崇左市','','','0002000014',21,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (270,'460100','海口市','','','0002100001',22,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (271,'460200','三亚市','','','0002100002',22,2,1,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (272,'460300','三沙市','','','0002100003',22,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (273,'469000','省直辖县级行政区划','','','0002100004',22,2,16,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (274,'500100','重庆市辖区','','','0002200001',23,2,19,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (275,'500200','县','','','0002200002',23,2,19,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (276,'510100','成都市','','','0002300001',24,2,20,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (277,'510300','自贡市','','','0002300002',24,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (278,'510400','攀枝花市','','','0002300003',24,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (279,'510500','泸州市','','','0002300004',24,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (280,'510600','德阳市','','','0002300005',24,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (281,'510700','绵阳市','','','0002300006',24,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (282,'510800','广元市','','','0002300007',24,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (283,'510900','遂宁市','','','0002300008',24,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (284,'511000','内江市','','','0002300009',24,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (285,'511100','乐山市','','','0002300010',24,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (286,'511300','南充市','','','0002300011',24,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (287,'511400','眉山市','','','0002300012',24,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (288,'511500','宜宾市','','','0002300013',24,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (289,'511600','广安市','','','0002300014',24,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (290,'511700','达州市','','','0002300015',24,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (291,'511800','雅安市','','','0002300016',24,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (292,'511900','巴中市','','','0002300017',24,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (293,'512000','资阳市','','','0002300018',24,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (294,'513200','阿坝藏族羌族自治州','','','0002300019',24,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (295,'513300','甘孜藏族自治州','','','0002300020',24,2,18,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (296,'513400','凉山彝族自治州','','','0002300021',24,2,17,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (297,'520100','贵阳市','','','0002400001',25,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (298,'520200','六盘水市','','','0002400002',25,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (299,'520300','遵义市','','','0002400003',25,2,15,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (300,'520400','安顺市','','','0002400004',25,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (301,'520500','毕节市','','','0002400005',25,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (302,'520600','铜仁市','','','0002400006',25,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (303,'522300','黔西南布依族苗族自治州','','','0002400007',25,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (304,'522600','黔东南苗族侗族自治州','','','0002400008',25,2,16,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (305,'522700','黔南布依族苗族自治州','','','0002400009',25,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (306,'530100','昆明市','','','0002500001',26,2,15,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (307,'530300','曲靖市','','','0002500002',26,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (308,'530400','玉溪市','','','0002500003',26,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (309,'530500','保山市','','','0002500004',26,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (310,'530600','昭通市','','','0002500005',26,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (311,'530700','丽江市','','','0002500006',26,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (312,'530800','普洱市','','','0002500007',26,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (313,'530900','临沧市','','','0002500008',26,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (314,'532300','楚雄彝族自治州','','','0002500009',26,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (315,'532500','红河哈尼族彝族自治州','','','0002500010',26,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (316,'532600','文山壮族苗族自治州','','','0002500011',26,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (317,'532800','西双版纳傣族自治州','','','0002500012',26,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (318,'532900','大理白族自治州','','','0002500013',26,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (319,'533100','德宏傣族景颇族自治州','','','0002500014',26,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (320,'533300','怒江傈僳族自治州','','','0002500015',26,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (321,'533400','迪庆藏族自治州','','','0002500016',26,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (322,'540100','拉萨市','','','0002600001',27,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (323,'542100','昌都地区','','','0002600002',27,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (324,'542200','山南地区','','','0002600003',27,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (325,'542300','日喀则地区','','','0002600004',27,2,18,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (326,'542400','那曲地区','','','0002600005',27,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (327,'542500','阿里地区','','','0002600006',27,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (328,'542600','林芝地区','','','0002600007',27,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (329,'610100','西安市','','','0002700001',28,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (330,'610200','铜川市','','','0002700002',28,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (331,'610300','宝鸡市','','','0002700003',28,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (332,'610400','咸阳市','','','0002700004',28,2,15,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (333,'610500','渭南市','','','0002700005',28,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (334,'610600','延安市','','','0002700006',28,2,14,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (335,'610700','汉中市','','','0002700007',28,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (336,'610800','榆林市','','','0002700008',28,2,13,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (337,'610900','安康市','','','0002700009',28,2,11,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (338,'611000','商洛市','','','0002700010',28,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (339,'620100','兰州市','','','0002800001',29,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (340,'620200','嘉峪关市','','','0002800002',29,2,1,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (341,'620300','金昌市','','','0002800003',29,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (342,'620400','白银市','','','0002800004',29,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (343,'620500','天水市','','','0002800005',29,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (344,'620600','武威市','','','0002800006',29,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (345,'620700','张掖市','','','0002800007',29,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (346,'620800','平凉市','','','0002800008',29,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (347,'620900','酒泉市','','','0002800009',29,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (348,'621000','庆阳市','','','0002800010',29,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (349,'621100','定西市','','','0002800011',29,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (350,'621200','陇南市','','','0002800012',29,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (351,'622900','临夏回族自治州','','','0002800013',29,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (352,'623000','甘南藏族自治州','','','0002800014',29,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (353,'630100','西宁市','','','0002900001',30,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (354,'630200','海东市','','','0002900002',30,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (355,'632200','海北藏族自治州','','','0002900003',30,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (356,'632300','黄南藏族自治州','','','0002900004',30,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (357,'632500','海南藏族自治州','','','0002900005',30,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (358,'632600','果洛藏族自治州','','','0002900006',30,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (359,'632700','玉树藏族自治州','','','0002900007',30,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (360,'632800','海西蒙古族藏族自治州','','','0002900008',30,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (361,'640100','银川市','','','0003000001',31,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (362,'640200','石嘴山市','','','0003000002',31,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (363,'640300','吴忠市','','','0003000003',31,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (364,'640400','固原市','','','0003000004',31,2,6,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (365,'640500','中卫市','','','0003000005',31,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (366,'650100','乌鲁木齐市','','','0003100001',32,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (367,'650200','克拉玛依市','','','0003100002',32,2,5,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (368,'652100','吐鲁番地区','','','0003100003',32,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (369,'652200','哈密地区','','','0003100004',32,2,3,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (370,'652300','昌吉回族自治州','','','0003100005',32,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (371,'652700','博尔塔拉蒙古自治州','','','0003100006',32,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (372,'652800','巴音郭楞蒙古自治州','','','0003100007',32,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (373,'652900','阿克苏地区','','','0003100008',32,2,9,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (374,'653000','克孜勒苏柯尔克孜自治州','','','0003100009',32,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (375,'653100','喀什地区','','','0003100010',32,2,12,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (376,'653200','和田地区','','','0003100011',32,2,8,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (377,'654000','伊犁哈萨克自治州','','','0003100012',32,2,10,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (378,'654200','塔城地区','','','0003100013',32,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (379,'654300','阿勒泰地区','','','0003100014',32,2,7,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (380,'659000','自治区直辖县级行政区划','','','0003100015',32,2,4,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (381,'110101','东城区','','','000010000100001',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (382,'110102','西城区','','','000010000100002',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (383,'110105','朝阳区','','','000010000100003',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (384,'110106','丰台区','','','000010000100004',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (385,'110107','石景山区','','','000010000100005',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (386,'110108','海淀区','','','000010000100006',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (387,'110109','门头沟区','','','000010000100007',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (388,'110111','房山区','','','000010000100008',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (389,'110112','通州区','','','000010000100009',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (390,'110113','顺义区','','','000010000100010',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (391,'110114','昌平区','','','000010000100011',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (392,'110115','大兴区','','','000010000100012',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (393,'110116','怀柔区','','','000010000100013',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (394,'110117','平谷区','','','000010000100014',36,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (395,'110228','密云县','','','000010000200001',37,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (396,'110229','延庆县','','','000010000200002',37,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (397,'120101','和平区','','','000020000100001',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (398,'120102','河东区','','','000020000100002',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (399,'120103','河西区','','','000020000100003',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (400,'120104','南开区','','','000020000100004',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (401,'120105','河北区','','','000020000100005',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (402,'120106','红桥区','','','000020000100006',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (403,'120110','东丽区','','','000020000100007',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (404,'120111','西青区','','','000020000100008',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (405,'120112','津南区','','','000020000100009',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (406,'120113','北辰区','','','000020000100010',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (407,'120114','武清区','','','000020000100011',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (408,'120115','宝坻区','','','000020000100012',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (409,'120116','滨海新区','','','000020000100013',38,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (410,'120221','宁河县','','','000020000200001',39,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (411,'120223','静海县','','','000020000200002',39,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (412,'120225','蓟县','','','000020000200003',39,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (413,'130101','石家庄市辖区','','','000030000100001',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (414,'130102','长安区','','','000030000100002',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (415,'130103','桥东区','','','000030000100003',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (416,'130104','桥西区','','','000030000100004',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (417,'130105','新华区','','','000030000100005',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (418,'130107','井陉矿区','','','000030000100006',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (419,'130108','裕华区','','','000030000100007',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (420,'130121','井陉县','','','000030000100008',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (421,'130123','正定县','','','000030000100009',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (422,'130124','栾城县','','','000030000100010',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (423,'130125','行唐县','','','000030000100011',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (424,'130126','灵寿县','','','000030000100012',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (425,'130127','高邑县','','','000030000100013',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (426,'130128','深泽县','','','000030000100014',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (427,'130129','赞皇县','','','000030000100015',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (428,'130130','无极县','','','000030000100016',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (429,'130131','平山县','','','000030000100017',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (430,'130132','元氏县','','','000030000100018',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (431,'130133','赵县','','','000030000100019',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (432,'130181','辛集市','','','000030000100020',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (433,'130182','藁城市','','','000030000100021',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (434,'130183','晋州市','','','000030000100022',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (435,'130184','新乐市','','','000030000100023',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (436,'130185','鹿泉市','','','000030000100024',40,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (437,'130201','唐山市辖区','','','000030000200001',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (438,'130202','路南区','','','000030000200002',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (439,'130203','路北区','','','000030000200003',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (440,'130204','古冶区','','','000030000200004',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (441,'130205','开平区','','','000030000200005',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (442,'130207','丰南区','','','000030000200006',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (443,'130208','丰润区','','','000030000200007',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (444,'130209','曹妃甸区','','','000030000200008',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (445,'130223','滦县','','','000030000200009',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (446,'130224','滦南县','','','000030000200010',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (447,'130225','乐亭县','','','000030000200011',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (448,'130227','迁西县','','','000030000200012',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (449,'130229','玉田县','','','000030000200013',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (450,'130281','遵化市','','','000030000200014',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (451,'130283','迁安市','','','000030000200015',41,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (452,'130301','秦皇岛市辖区','','','000030000300001',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (453,'130302','海港区','','','000030000300002',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (454,'130303','山海关区','','','000030000300003',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (455,'130304','北戴河区','','','000030000300004',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (456,'130321','青龙满族自治县','','','000030000300005',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (457,'130322','昌黎县','','','000030000300006',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (458,'130323','抚宁县','','','000030000300007',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (459,'130324','卢龙县','','','000030000300008',42,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (460,'130401','邯郸市辖区','','','000030000400001',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (461,'130402','邯山区','','','000030000400002',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (462,'130403','丛台区','','','000030000400003',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (463,'130404','复兴区','','','000030000400004',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (464,'130406','峰峰矿区','','','000030000400005',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (465,'130421','邯郸县','','','000030000400006',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (466,'130423','临漳县','','','000030000400007',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (467,'130424','成安县','','','000030000400008',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (468,'130425','大名县','','','000030000400009',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (469,'130426','涉县','','','000030000400010',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (470,'130427','磁县','','','000030000400011',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (471,'130428','肥乡县','','','000030000400012',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (472,'130429','永年县','','','000030000400013',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (473,'130430','邱县','','','000030000400014',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (474,'130431','鸡泽县','','','000030000400015',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (475,'130432','广平县','','','000030000400016',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (476,'130433','馆陶县','','','000030000400017',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (477,'130434','魏县','','','000030000400018',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (478,'130435','曲周县','','','000030000400019',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (479,'130481','武安市','','','000030000400020',43,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (480,'130501','邢台市辖区','','','000030000500001',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (481,'130502','桥东区','','','000030000500002',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (482,'130503','桥西区','','','000030000500003',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (483,'130521','邢台县','','','000030000500004',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (484,'130522','临城县','','','000030000500005',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (485,'130523','内丘县','','','000030000500006',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (486,'130524','柏乡县','','','000030000500007',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (487,'130525','隆尧县','','','000030000500008',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (488,'130526','任县','','','000030000500009',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (489,'130527','南和县','','','000030000500010',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (490,'130528','宁晋县','','','000030000500011',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (491,'130529','巨鹿县','','','000030000500012',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (492,'130530','新河县','','','000030000500013',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (493,'130531','广宗县','','','000030000500014',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (494,'130532','平乡县','','','000030000500015',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (495,'130533','威县','','','000030000500016',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (496,'130534','清河县','','','000030000500017',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (497,'130535','临西县','','','000030000500018',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (498,'130581','南宫市','','','000030000500019',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (499,'130582','沙河市','','','000030000500020',44,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (500,'130601','保定市辖区','','','000030000600001',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (501,'130602','新市区','','','000030000600002',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (502,'130603','北市区','','','000030000600003',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (503,'130604','南市区','','','000030000600004',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (504,'130621','满城县','','','000030000600005',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (505,'130622','清苑县','','','000030000600006',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (506,'130623','涞水县','','','000030000600007',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (507,'130624','阜平县','','','000030000600008',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (508,'130625','徐水县','','','000030000600009',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (509,'130626','定兴县','','','000030000600010',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (510,'130627','唐县','','','000030000600011',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (511,'130628','高阳县','','','000030000600012',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (512,'130629','容城县','','','000030000600013',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (513,'130630','涞源县','','','000030000600014',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (514,'130631','望都县','','','000030000600015',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (515,'130632','安新县','','','000030000600016',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (516,'130633','易县','','','000030000600017',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (517,'130634','曲阳县','','','000030000600018',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (518,'130635','蠡县','','','000030000600019',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (519,'130636','顺平县','','','000030000600020',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (520,'130637','博野县','','','000030000600021',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (521,'130638','雄县','','','000030000600022',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (522,'130681','涿州市','','','000030000600023',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (523,'130682','定州市','','','000030000600024',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (524,'130683','安国市','','','000030000600025',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (525,'130684','高碑店市','','','000030000600026',45,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (526,'130701','张家口市辖区','','','000030000700001',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (527,'130702','桥东区','','','000030000700002',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (528,'130703','桥西区','','','000030000700003',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (529,'130705','宣化区','','','000030000700004',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (530,'130706','下花园区','','','000030000700005',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (531,'130721','宣化县','','','000030000700006',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (532,'130722','张北县','','','000030000700007',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (533,'130723','康保县','','','000030000700008',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (534,'130724','沽源县','','','000030000700009',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (535,'130725','尚义县','','','000030000700010',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (536,'130726','蔚县','','','000030000700011',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (537,'130727','阳原县','','','000030000700012',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (538,'130728','怀安县','','','000030000700013',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (539,'130729','万全县','','','000030000700014',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (540,'130730','怀来县','','','000030000700015',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (541,'130731','涿鹿县','','','000030000700016',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (542,'130732','赤城县','','','000030000700017',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (543,'130733','崇礼县','','','000030000700018',46,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (544,'130801','承德市辖区','','','000030000800001',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (545,'130802','双桥区','','','000030000800002',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (546,'130803','双滦区','','','000030000800003',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (547,'130804','鹰手营子矿区','','','000030000800004',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (548,'130821','承德县','','','000030000800005',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (549,'130822','兴隆县','','','000030000800006',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (550,'130823','平泉县','','','000030000800007',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (551,'130824','滦平县','','','000030000800008',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (552,'130825','隆化县','','','000030000800009',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (553,'130826','丰宁满族自治县','','','000030000800010',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (554,'130827','宽城满族自治县','','','000030000800011',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (555,'130828','围场满族蒙古族自治县','','','000030000800012',47,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (556,'130901','沧州市辖区','','','000030000900001',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (557,'130902','新华区','','','000030000900002',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (558,'130903','运河区','','','000030000900003',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (559,'130921','沧县','','','000030000900004',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (560,'130922','青县','','','000030000900005',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (561,'130923','东光县','','','000030000900006',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (562,'130924','海兴县','','','000030000900007',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (563,'130925','盐山县','','','000030000900008',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (564,'130926','肃宁县','','','000030000900009',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (565,'130927','南皮县','','','000030000900010',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (566,'130928','吴桥县','','','000030000900011',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (567,'130929','献县','','','000030000900012',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (568,'130930','孟村回族自治县','','','000030000900013',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (569,'130981','泊头市','','','000030000900014',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (570,'130982','任丘市','','','000030000900015',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (571,'130983','黄骅市','','','000030000900016',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (572,'130984','河间市','','','000030000900017',48,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (573,'131001','廊坊市辖区','','','000030001000001',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (574,'131002','安次区','','','000030001000002',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (575,'131003','广阳区','','','000030001000003',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (576,'131022','固安县','','','000030001000004',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (577,'131023','永清县','','','000030001000005',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (578,'131024','香河县','','','000030001000006',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (579,'131025','大城县','','','000030001000007',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (580,'131026','文安县','','','000030001000008',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (581,'131028','大厂回族自治县','','','000030001000009',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (582,'131081','霸州市','','','000030001000010',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (583,'131082','三河市','','','000030001000011',49,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (584,'131101','衡水市辖区','','','000030001100001',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (585,'131102','桃城区','','','000030001100002',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (586,'131121','枣强县','','','000030001100003',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (587,'131122','武邑县','','','000030001100004',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (588,'131123','武强县','','','000030001100005',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (589,'131124','饶阳县','','','000030001100006',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (590,'131125','安平县','','','000030001100007',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (591,'131126','故城县','','','000030001100008',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (592,'131127','景县','','','000030001100009',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (593,'131128','阜城县','','','000030001100010',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (594,'131181','冀州市','','','000030001100011',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (595,'131182','深州市','','','000030001100012',50,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (596,'140101','太原市辖区','','','000040000100001',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (597,'140105','小店区','','','000040000100002',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (598,'140106','迎泽区','','','000040000100003',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (599,'140107','杏花岭区','','','000040000100004',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (600,'140108','尖草坪区','','','000040000100005',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (601,'140109','万柏林区','','','000040000100006',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (602,'140110','晋源区','','','000040000100007',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (603,'140121','清徐县','','','000040000100008',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (604,'140122','阳曲县','','','000040000100009',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (605,'140123','娄烦县','','','000040000100010',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (606,'140181','古交市','','','000040000100011',51,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (607,'140201','大同市辖区','','','000040000200001',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (608,'140202','城区','','','000040000200002',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (609,'140203','矿区','','','000040000200003',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (610,'140211','南郊区','','','000040000200004',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (611,'140212','新荣区','','','000040000200005',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (612,'140221','阳高县','','','000040000200006',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (613,'140222','天镇县','','','000040000200007',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (614,'140223','广灵县','','','000040000200008',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (615,'140224','灵丘县','','','000040000200009',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (616,'140225','浑源县','','','000040000200010',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (617,'140226','左云县','','','000040000200011',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (618,'140227','大同县','','','000040000200012',52,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (619,'140301','阳泉市辖区','','','000040000300001',53,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (620,'140302','城区','','','000040000300002',53,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (621,'140303','矿区','','','000040000300003',53,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (622,'140311','郊区','','','000040000300004',53,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (623,'140321','平定县','','','000040000300005',53,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (624,'140322','盂县','','','000040000300006',53,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (625,'140401','长治市辖区','','','000040000400001',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (626,'140402','城区','','','000040000400002',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (627,'140411','郊区','','','000040000400003',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (628,'140421','长治县','','','000040000400004',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (629,'140423','襄垣县','','','000040000400005',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (630,'140424','屯留县','','','000040000400006',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (631,'140425','平顺县','','','000040000400007',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (632,'140426','黎城县','','','000040000400008',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (633,'140427','壶关县','','','000040000400009',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (634,'140428','长子县','','','000040000400010',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (635,'140429','武乡县','','','000040000400011',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (636,'140430','沁县','','','000040000400012',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (637,'140431','沁源县','','','000040000400013',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (638,'140481','潞城市','','','000040000400014',54,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (639,'140501','晋城市辖区','','','000040000500001',55,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (640,'140502','城区','','','000040000500002',55,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (641,'140521','沁水县','','','000040000500003',55,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (642,'140522','阳城县','','','000040000500004',55,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (643,'140524','陵川县','','','000040000500005',55,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (644,'140525','泽州县','','','000040000500006',55,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (645,'140581','高平市','','','000040000500007',55,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (646,'140601','朔州市辖区','','','000040000600001',56,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (647,'140602','朔城区','','','000040000600002',56,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (648,'140603','平鲁区','','','000040000600003',56,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (649,'140621','山阴县','','','000040000600004',56,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (650,'140622','应县','','','000040000600005',56,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (651,'140623','右玉县','','','000040000600006',56,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (652,'140624','怀仁县','','','000040000600007',56,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (653,'140701','晋中市辖区','','','000040000700001',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (654,'140702','榆次区','','','000040000700002',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (655,'140721','榆社县','','','000040000700003',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (656,'140722','左权县','','','000040000700004',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (657,'140723','和顺县','','','000040000700005',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (658,'140724','昔阳县','','','000040000700006',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (659,'140725','寿阳县','','','000040000700007',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (660,'140726','太谷县','','','000040000700008',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (661,'140727','祁县','','','000040000700009',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (662,'140728','平遥县','','','000040000700010',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (663,'140729','灵石县','','','000040000700011',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (664,'140781','介休市','','','000040000700012',57,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (665,'140801','运城市辖区','','','000040000800001',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (666,'140802','盐湖区','','','000040000800002',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (667,'140821','临猗县','','','000040000800003',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (668,'140822','万荣县','','','000040000800004',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (669,'140823','闻喜县','','','000040000800005',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (670,'140824','稷山县','','','000040000800006',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (671,'140825','新绛县','','','000040000800007',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (672,'140826','绛县','','','000040000800008',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (673,'140827','垣曲县','','','000040000800009',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (674,'140828','夏县','','','000040000800010',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (675,'140829','平陆县','','','000040000800011',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (676,'140830','芮城县','','','000040000800012',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (677,'140881','永济市','','','000040000800013',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (678,'140882','河津市','','','000040000800014',58,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (679,'140901','忻州市辖区','','','000040000900001',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (680,'140902','忻府区','','','000040000900002',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (681,'140921','定襄县','','','000040000900003',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (682,'140922','五台县','','','000040000900004',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (683,'140923','代县','','','000040000900005',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (684,'140924','繁峙县','','','000040000900006',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (685,'140925','宁武县','','','000040000900007',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (686,'140926','静乐县','','','000040000900008',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (687,'140927','神池县','','','000040000900009',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (688,'140928','五寨县','','','000040000900010',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (689,'140929','岢岚县','','','000040000900011',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (690,'140930','河曲县','','','000040000900012',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (691,'140931','保德县','','','000040000900013',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (692,'140932','偏关县','','','000040000900014',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (693,'140981','原平市','','','000040000900015',59,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (694,'141001','临汾市辖区','','','000040001000001',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (695,'141002','尧都区','','','000040001000002',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (696,'141021','曲沃县','','','000040001000003',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (697,'141022','翼城县','','','000040001000004',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (698,'141023','襄汾县','','','000040001000005',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (699,'141024','洪洞县','','','000040001000006',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (700,'141025','古县','','','000040001000007',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (701,'141026','安泽县','','','000040001000008',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (702,'141027','浮山县','','','000040001000009',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (703,'141028','吉县','','','000040001000010',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (704,'141029','乡宁县','','','000040001000011',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (705,'141030','大宁县','','','000040001000012',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (706,'141031','隰县','','','000040001000013',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (707,'141032','永和县','','','000040001000014',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (708,'141033','蒲县','','','000040001000015',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (709,'141034','汾西县','','','000040001000016',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (710,'141081','侯马市','','','000040001000017',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (711,'141082','霍州市','','','000040001000018',60,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (712,'141101','吕梁市辖区','','','000040001100001',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (713,'141102','离石区','','','000040001100002',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (714,'141121','文水县','','','000040001100003',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (715,'141122','交城县','','','000040001100004',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (716,'141123','兴县','','','000040001100005',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (717,'141124','临县','','','000040001100006',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (718,'141125','柳林县','','','000040001100007',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (719,'141126','石楼县','','','000040001100008',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (720,'141127','岚县','','','000040001100009',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (721,'141128','方山县','','','000040001100010',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (722,'141129','中阳县','','','000040001100011',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (723,'141130','交口县','','','000040001100012',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (724,'141181','孝义市','','','000040001100013',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (725,'141182','汾阳市','','','000040001100014',61,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (726,'150101','呼和浩特市辖区','','','000050000100001',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (727,'150102','新城区','','','000050000100002',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (728,'150103','回民区','','','000050000100003',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (729,'150104','玉泉区','','','000050000100004',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (730,'150105','赛罕区','','','000050000100005',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (731,'150121','土默特左旗','','','000050000100006',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (732,'150122','托克托县','','','000050000100007',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (733,'150123','和林格尔县','','','000050000100008',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (734,'150124','清水河县','','','000050000100009',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (735,'150125','武川县','','','000050000100010',62,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (736,'150201','包头市辖区','','','000050000200001',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (737,'150202','东河区','','','000050000200002',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (738,'150203','昆都仑区','','','000050000200003',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (739,'150204','青山区','','','000050000200004',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (740,'150205','石拐区','','','000050000200005',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (741,'150206','白云鄂博矿区','','','000050000200006',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (742,'150207','九原区','','','000050000200007',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (743,'150221','土默特右旗','','','000050000200008',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (744,'150222','固阳县','','','000050000200009',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (745,'150223','达尔罕茂明安联合旗','','','000050000200010',63,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (746,'150301','乌海市辖区','','','000050000300001',64,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (747,'150302','海勃湾区','','','000050000300002',64,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (748,'150303','海南区','','','000050000300003',64,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (749,'150304','乌达区','','','000050000300004',64,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (750,'150401','赤峰市辖区','','','000050000400001',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (751,'150402','红山区','','','000050000400002',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (752,'150403','元宝山区','','','000050000400003',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (753,'150404','松山区','','','000050000400004',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (754,'150421','阿鲁科尔沁旗','','','000050000400005',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (755,'150422','巴林左旗','','','000050000400006',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (756,'150423','巴林右旗','','','000050000400007',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (757,'150424','林西县','','','000050000400008',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (758,'150425','克什克腾旗','','','000050000400009',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (759,'150426','翁牛特旗','','','000050000400010',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (760,'150428','喀喇沁旗','','','000050000400011',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (761,'150429','宁城县','','','000050000400012',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (762,'150430','敖汉旗','','','000050000400013',65,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (763,'150501','通辽市辖区','','','000050000500001',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (764,'150502','科尔沁区','','','000050000500002',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (765,'150521','科尔沁左翼中旗','','','000050000500003',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (766,'150522','科尔沁左翼后旗','','','000050000500004',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (767,'150523','开鲁县','','','000050000500005',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (768,'150524','库伦旗','','','000050000500006',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (769,'150525','奈曼旗','','','000050000500007',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (770,'150526','扎鲁特旗','','','000050000500008',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (771,'150581','霍林郭勒市','','','000050000500009',66,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (772,'150601','鄂尔多斯市辖区','','','000050000600001',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (773,'150602','东胜区','','','000050000600002',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (774,'150621','达拉特旗','','','000050000600003',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (775,'150622','准格尔旗','','','000050000600004',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (776,'150623','鄂托克前旗','','','000050000600005',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (777,'150624','鄂托克旗','','','000050000600006',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (778,'150625','杭锦旗','','','000050000600007',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (779,'150626','乌审旗','','','000050000600008',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (780,'150627','伊金霍洛旗','','','000050000600009',67,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (781,'150701','呼伦贝尔市辖区','','','000050000700001',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (782,'150702','海拉尔区','','','000050000700002',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (783,'150703','扎赉诺尔区','','','000050000700003',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (784,'150721','阿荣旗','','','000050000700004',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (785,'150722','莫力达瓦达斡尔族自治旗','','','000050000700005',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (786,'150723','鄂伦春自治旗','','','000050000700006',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (787,'150724','鄂温克族自治旗','','','000050000700007',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (788,'150725','陈巴尔虎旗','','','000050000700008',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (789,'150726','新巴尔虎左旗','','','000050000700009',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (790,'150727','新巴尔虎右旗','','','000050000700010',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (791,'150781','满洲里市','','','000050000700011',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (792,'150782','牙克石市','','','000050000700012',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (793,'150783','扎兰屯市','','','000050000700013',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (794,'150784','额尔古纳市','','','000050000700014',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (795,'150785','根河市','','','000050000700015',68,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (796,'150801','巴彦淖尔市辖区','','','000050000800001',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (797,'150802','临河区','','','000050000800002',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (798,'150821','五原县','','','000050000800003',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (799,'150822','磴口县','','','000050000800004',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (800,'150823','乌拉特前旗','','','000050000800005',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (801,'150824','乌拉特中旗','','','000050000800006',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (802,'150825','乌拉特后旗','','','000050000800007',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (803,'150826','杭锦后旗','','','000050000800008',69,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (804,'150901','乌兰察布市辖区','','','000050000900001',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (805,'150902','集宁区','','','000050000900002',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (806,'150921','卓资县','','','000050000900003',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (807,'150922','化德县','','','000050000900004',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (808,'150923','商都县','','','000050000900005',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (809,'150924','兴和县','','','000050000900006',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (810,'150925','凉城县','','','000050000900007',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (811,'150926','察哈尔右翼前旗','','','000050000900008',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (812,'150927','察哈尔右翼中旗','','','000050000900009',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (813,'150928','察哈尔右翼后旗','','','000050000900010',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (814,'150929','四子王旗','','','000050000900011',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (815,'150981','丰镇市','','','000050000900012',70,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (816,'152201','乌兰浩特市','','','000050001000001',71,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (817,'152202','阿尔山市','','','000050001000002',71,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (818,'152221','科尔沁右翼前旗','','','000050001000003',71,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (819,'152222','科尔沁右翼中旗','','','000050001000004',71,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (820,'152223','扎赉特旗','','','000050001000005',71,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (821,'152224','突泉县','','','000050001000006',71,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (822,'152501','二连浩特市','','','000050001100001',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (823,'152502','锡林浩特市','','','000050001100002',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (824,'152522','阿巴嘎旗','','','000050001100003',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (825,'152523','苏尼特左旗','','','000050001100004',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (826,'152524','苏尼特右旗','','','000050001100005',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (827,'152525','东乌珠穆沁旗','','','000050001100006',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (828,'152526','西乌珠穆沁旗','','','000050001100007',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (829,'152527','太仆寺旗','','','000050001100008',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (830,'152528','镶黄旗','','','000050001100009',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (831,'152529','正镶白旗','','','000050001100010',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (832,'152530','正蓝旗','','','000050001100011',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (833,'152531','多伦县','','','000050001100012',72,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (834,'152921','阿拉善左旗','','','000050001200001',73,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (835,'152922','阿拉善右旗','','','000050001200002',73,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (836,'152923','额济纳旗','','','000050001200003',73,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (837,'210101','沈阳市辖区','','','000060000100001',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (838,'210102','和平区','','','000060000100002',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (839,'210103','沈河区','','','000060000100003',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (840,'210104','大东区','','','000060000100004',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (841,'210105','皇姑区','','','000060000100005',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (842,'210106','铁西区','','','000060000100006',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (843,'210111','苏家屯区','','','000060000100007',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (844,'210112','东陵区','','','000060000100008',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (845,'210113','沈北新区','','','000060000100009',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (846,'210114','于洪区','','','000060000100010',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (847,'210122','辽中县','','','000060000100011',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (848,'210123','康平县','','','000060000100012',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (849,'210124','法库县','','','000060000100013',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (850,'210181','新民市','','','000060000100014',74,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (851,'210201','大连市辖区','','','000060000200001',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (852,'210202','中山区','','','000060000200002',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (853,'210203','西岗区','','','000060000200003',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (854,'210204','沙河口区','','','000060000200004',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (855,'210211','甘井子区','','','000060000200005',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (856,'210212','旅顺口区','','','000060000200006',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (857,'210213','金州区','','','000060000200007',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (858,'210224','长海县','','','000060000200008',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (859,'210281','瓦房店市','','','000060000200009',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (860,'210282','普兰店市','','','000060000200010',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (861,'210283','庄河市','','','000060000200011',75,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (862,'210301','鞍山市辖区','','','000060000300001',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (863,'210302','铁东区','','','000060000300002',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (864,'210303','铁西区','','','000060000300003',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (865,'210304','立山区','','','000060000300004',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (866,'210311','千山区','','','000060000300005',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (867,'210321','台安县','','','000060000300006',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (868,'210323','岫岩满族自治县','','','000060000300007',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (869,'210381','海城市','','','000060000300008',76,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (870,'210401','抚顺市辖区','','','000060000400001',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (871,'210402','新抚区','','','000060000400002',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (872,'210403','东洲区','','','000060000400003',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (873,'210404','望花区','','','000060000400004',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (874,'210411','顺城区','','','000060000400005',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (875,'210421','抚顺县','','','000060000400006',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (876,'210422','新宾满族自治县','','','000060000400007',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (877,'210423','清原满族自治县','','','000060000400008',77,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (878,'210501','本溪市辖区','','','000060000500001',78,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (879,'210502','平山区','','','000060000500002',78,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (880,'210503','溪湖区','','','000060000500003',78,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (881,'210504','明山区','','','000060000500004',78,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (882,'210505','南芬区','','','000060000500005',78,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (883,'210521','本溪满族自治县','','','000060000500006',78,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (884,'210522','桓仁满族自治县','','','000060000500007',78,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (885,'210601','丹东市辖区','','','000060000600001',79,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (886,'210602','元宝区','','','000060000600002',79,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (887,'210603','振兴区','','','000060000600003',79,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (888,'210604','振安区','','','000060000600004',79,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (889,'210624','宽甸满族自治县','','','000060000600005',79,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (890,'210681','东港市','','','000060000600006',79,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (891,'210682','凤城市','','','000060000600007',79,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (892,'210701','锦州市辖区','','','000060000700001',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (893,'210702','古塔区','','','000060000700002',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (894,'210703','凌河区','','','000060000700003',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (895,'210711','太和区','','','000060000700004',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (896,'210726','黑山县','','','000060000700005',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (897,'210727','义县','','','000060000700006',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (898,'210781','凌海市','','','000060000700007',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (899,'210782','北镇市','','','000060000700008',80,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (900,'210801','营口市辖区','','','000060000800001',81,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (901,'210802','站前区','','','000060000800002',81,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (902,'210803','西市区','','','000060000800003',81,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (903,'210804','鲅鱼圈区','','','000060000800004',81,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (904,'210811','老边区','','','000060000800005',81,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (905,'210881','盖州市','','','000060000800006',81,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (906,'210882','大石桥市','','','000060000800007',81,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (907,'210901','阜新市辖区','','','000060000900001',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (908,'210902','海州区','','','000060000900002',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (909,'210903','新邱区','','','000060000900003',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (910,'210904','太平区','','','000060000900004',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (911,'210905','清河门区','','','000060000900005',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (912,'210911','细河区','','','000060000900006',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (913,'210921','阜新蒙古族自治县','','','000060000900007',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (914,'210922','彰武县','','','000060000900008',82,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (915,'211001','辽阳市辖区','','','000060001000001',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (916,'211002','白塔区','','','000060001000002',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (917,'211003','文圣区','','','000060001000003',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (918,'211004','宏伟区','','','000060001000004',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (919,'211005','弓长岭区','','','000060001000005',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (920,'211011','太子河区','','','000060001000006',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (921,'211021','辽阳县','','','000060001000007',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (922,'211081','灯塔市','','','000060001000008',83,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (923,'211101','盘锦市辖区','','','000060001100001',84,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (924,'211102','双台子区','','','000060001100002',84,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (925,'211103','兴隆台区','','','000060001100003',84,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (926,'211121','大洼县','','','000060001100004',84,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (927,'211122','盘山县','','','000060001100005',84,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (928,'211201','铁岭市辖区','','','000060001200001',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (929,'211202','银州区','','','000060001200002',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (930,'211204','清河区','','','000060001200003',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (931,'211221','铁岭县','','','000060001200004',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (932,'211223','西丰县','','','000060001200005',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (933,'211224','昌图县','','','000060001200006',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (934,'211281','调兵山市','','','000060001200007',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (935,'211282','开原市','','','000060001200008',85,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (936,'211301','朝阳市辖区','','','000060001300001',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (937,'211302','双塔区','','','000060001300002',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (938,'211303','龙城区','','','000060001300003',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (939,'211321','朝阳县','','','000060001300004',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (940,'211322','建平县','','','000060001300005',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (941,'211324','喀喇沁左翼蒙古族自治县','','','000060001300006',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (942,'211381','北票市','','','000060001300007',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (943,'211382','凌源市','','','000060001300008',86,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (944,'211401','葫芦岛市辖区','','','000060001400001',87,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (945,'211402','连山区','','','000060001400002',87,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (946,'211403','龙港区','','','000060001400003',87,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (947,'211404','南票区','','','000060001400004',87,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (948,'211421','绥中县','','','000060001400005',87,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (949,'211422','建昌县','','','000060001400006',87,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (950,'211481','兴城市','','','000060001400007',87,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (951,'220101','长春市辖区','','','000070000100001',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (952,'220102','南关区','','','000070000100002',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (953,'220103','宽城区','','','000070000100003',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (954,'220104','朝阳区','','','000070000100004',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (955,'220105','二道区','','','000070000100005',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (956,'220106','绿园区','','','000070000100006',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (957,'220112','双阳区','','','000070000100007',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (958,'220122','农安县','','','000070000100008',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (959,'220181','九台市','','','000070000100009',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (960,'220182','榆树市','','','000070000100010',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (961,'220183','德惠市','','','000070000100011',88,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (962,'220201','吉林市辖区','','','000070000200001',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (963,'220202','昌邑区','','','000070000200002',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (964,'220203','龙潭区','','','000070000200003',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (965,'220204','船营区','','','000070000200004',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (966,'220211','丰满区','','','000070000200005',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (967,'220221','永吉县','','','000070000200006',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (968,'220281','蛟河市','','','000070000200007',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (969,'220282','桦甸市','','','000070000200008',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (970,'220283','舒兰市','','','000070000200009',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (971,'220284','磐石市','','','000070000200010',89,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (972,'220301','四平市辖区','','','000070000300001',90,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (973,'220302','铁西区','','','000070000300002',90,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (974,'220303','铁东区','','','000070000300003',90,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (975,'220322','梨树县','','','000070000300004',90,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (976,'220323','伊通满族自治县','','','000070000300005',90,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (977,'220381','公主岭市','','','000070000300006',90,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (978,'220382','双辽市','','','000070000300007',90,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (979,'220401','辽源市辖区','','','000070000400001',91,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (980,'220402','龙山区','','','000070000400002',91,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (981,'220403','西安区','','','000070000400003',91,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (982,'220421','东丰县','','','000070000400004',91,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (983,'220422','东辽县','','','000070000400005',91,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (984,'220501','通化市辖区','','','000070000500001',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (985,'220502','东昌区','','','000070000500002',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (986,'220503','二道江区','','','000070000500003',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (987,'220521','通化县','','','000070000500004',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (988,'220523','辉南县','','','000070000500005',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (989,'220524','柳河县','','','000070000500006',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (990,'220581','梅河口市','','','000070000500007',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (991,'220582','集安市','','','000070000500008',92,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (992,'220601','白山市辖区','','','000070000600001',93,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (993,'220602','浑江区','','','000070000600002',93,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (994,'220605','江源区','','','000070000600003',93,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (995,'220621','抚松县','','','000070000600004',93,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (996,'220622','靖宇县','','','000070000600005',93,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (997,'220623','长白朝鲜族自治县','','','000070000600006',93,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (998,'220681','临江市','','','000070000600007',93,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (999,'220701','松原市辖区','','','000070000700001',94,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1000,'220702','宁江区','','','000070000700002',94,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1001,'220721','前郭尔罗斯蒙古族自治县','','','000070000700003',94,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1002,'220722','长岭县','','','000070000700004',94,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1003,'220723','乾安县','','','000070000700005',94,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1004,'220781','扶余市','','','000070000700006',94,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1005,'220801','白城市辖区','','','000070000800001',95,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1006,'220802','洮北区','','','000070000800002',95,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1007,'220821','镇赉县','','','000070000800003',95,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1008,'220822','通榆县','','','000070000800004',95,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1009,'220881','洮南市','','','000070000800005',95,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1010,'220882','大安市','','','000070000800006',95,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1011,'222401','延吉市','','','000070000900001',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1012,'222402','图们市','','','000070000900002',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1013,'222403','敦化市','','','000070000900003',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1014,'222404','珲春市','','','000070000900004',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1015,'222405','龙井市','','','000070000900005',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1016,'222406','和龙市','','','000070000900006',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1017,'222424','汪清县','','','000070000900007',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1018,'222426','安图县','','','000070000900008',96,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1019,'230101','哈尔滨市辖区','','','000080000100001',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1020,'230102','道里区','','','000080000100002',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1021,'230103','南岗区','','','000080000100003',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1022,'230104','道外区','','','000080000100004',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1023,'230108','平房区','','','000080000100005',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1024,'230109','松北区','','','000080000100006',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1025,'230110','香坊区','','','000080000100007',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1026,'230111','呼兰区','','','000080000100008',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1027,'230112','阿城区','','','000080000100009',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1028,'230123','依兰县','','','000080000100010',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1029,'230124','方正县','','','000080000100011',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1030,'230125','宾县','','','000080000100012',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1031,'230126','巴彦县','','','000080000100013',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1032,'230127','木兰县','','','000080000100014',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1033,'230128','通河县','','','000080000100015',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1034,'230129','延寿县','','','000080000100016',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1035,'230182','双城市','','','000080000100017',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1036,'230183','尚志市','','','000080000100018',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1037,'230184','五常市','','','000080000100019',97,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1038,'230201','齐齐哈尔市辖区','','','000080000200001',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1039,'230202','龙沙区','','','000080000200002',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1040,'230203','建华区','','','000080000200003',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1041,'230204','铁锋区','','','000080000200004',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1042,'230205','昂昂溪区','','','000080000200005',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1043,'230206','富拉尔基区','','','000080000200006',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1044,'230207','碾子山区','','','000080000200007',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1045,'230208','梅里斯达斡尔族区','','','000080000200008',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1046,'230221','龙江县','','','000080000200009',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1047,'230223','依安县','','','000080000200010',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1048,'230224','泰来县','','','000080000200011',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1049,'230225','甘南县','','','000080000200012',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1050,'230227','富裕县','','','000080000200013',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1051,'230229','克山县','','','000080000200014',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1052,'230230','克东县','','','000080000200015',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1053,'230231','拜泉县','','','000080000200016',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1054,'230281','讷河市','','','000080000200017',98,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1055,'230301','鸡西市辖区','','','000080000300001',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1056,'230302','鸡冠区','','','000080000300002',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1057,'230303','恒山区','','','000080000300003',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1058,'230304','滴道区','','','000080000300004',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1059,'230305','梨树区','','','000080000300005',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1060,'230306','城子河区','','','000080000300006',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1061,'230307','麻山区','','','000080000300007',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1062,'230321','鸡东县','','','000080000300008',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1063,'230381','虎林市','','','000080000300009',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1064,'230382','密山市','','','000080000300010',99,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1065,'230401','鹤岗市辖区','','','000080000400001',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1066,'230402','向阳区','','','000080000400002',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1067,'230403','工农区','','','000080000400003',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1068,'230404','南山区','','','000080000400004',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1069,'230405','兴安区','','','000080000400005',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1070,'230406','东山区','','','000080000400006',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1071,'230407','兴山区','','','000080000400007',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1072,'230421','萝北县','','','000080000400008',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1073,'230422','绥滨县','','','000080000400009',100,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1074,'230501','双鸭山市辖区','','','000080000500001',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1075,'230502','尖山区','','','000080000500002',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1076,'230503','岭东区','','','000080000500003',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1077,'230505','四方台区','','','000080000500004',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1078,'230506','宝山区','','','000080000500005',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1079,'230521','集贤县','','','000080000500006',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1080,'230522','友谊县','','','000080000500007',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1081,'230523','宝清县','','','000080000500008',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1082,'230524','饶河县','','','000080000500009',101,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1083,'230601','大庆市辖区','','','000080000600001',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1084,'230602','萨尔图区','','','000080000600002',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1085,'230603','龙凤区','','','000080000600003',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1086,'230604','让胡路区','','','000080000600004',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1087,'230605','红岗区','','','000080000600005',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1088,'230606','大同区','','','000080000600006',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1089,'230621','肇州县','','','000080000600007',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1090,'230622','肇源县','','','000080000600008',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1091,'230623','林甸县','','','000080000600009',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1092,'230624','杜尔伯特蒙古族自治县','','','000080000600010',102,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1093,'230701','伊春市辖区','','','000080000700001',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1094,'230702','伊春区','','','000080000700002',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1095,'230703','南岔区','','','000080000700003',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1096,'230704','友好区','','','000080000700004',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1097,'230705','西林区','','','000080000700005',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1098,'230706','翠峦区','','','000080000700006',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1099,'230707','新青区','','','000080000700007',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1100,'230708','美溪区','','','000080000700008',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1101,'230709','金山屯区','','','000080000700009',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1102,'230710','五营区','','','000080000700010',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1103,'230711','乌马河区','','','000080000700011',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1104,'230712','汤旺河区','','','000080000700012',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1105,'230713','带岭区','','','000080000700013',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1106,'230714','乌伊岭区','','','000080000700014',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1107,'230715','红星区','','','000080000700015',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1108,'230716','上甘岭区','','','000080000700016',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1109,'230722','嘉荫县','','','000080000700017',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1110,'230781','铁力市','','','000080000700018',103,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1111,'230801','佳木斯市辖区','','','000080000800001',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1112,'230803','向阳区','','','000080000800002',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1113,'230804','前进区','','','000080000800003',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1114,'230805','东风区','','','000080000800004',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1115,'230811','郊区','','','000080000800005',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1116,'230822','桦南县','','','000080000800006',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1117,'230826','桦川县','','','000080000800007',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1118,'230828','汤原县','','','000080000800008',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1119,'230833','抚远县','','','000080000800009',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1120,'230881','同江市','','','000080000800010',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1121,'230882','富锦市','','','000080000800011',104,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1122,'230901','七台河市辖区','','','000080000900001',105,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1123,'230902','新兴区','','','000080000900002',105,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1124,'230903','桃山区','','','000080000900003',105,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1125,'230904','茄子河区','','','000080000900004',105,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1126,'230921','勃利县','','','000080000900005',105,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1127,'231001','牡丹江市辖区','','','000080001000001',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1128,'231002','东安区','','','000080001000002',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1129,'231003','阳明区','','','000080001000003',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1130,'231004','爱民区','','','000080001000004',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1131,'231005','西安区','','','000080001000005',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1132,'231024','东宁县','','','000080001000006',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1133,'231025','林口县','','','000080001000007',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1134,'231081','绥芬河市','','','000080001000008',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1135,'231083','海林市','','','000080001000009',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1136,'231084','宁安市','','','000080001000010',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1137,'231085','穆棱市','','','000080001000011',106,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1138,'231101','黑河市辖区','','','000080001100001',107,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1139,'231102','爱辉区','','','000080001100002',107,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1140,'231121','嫩江县','','','000080001100003',107,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1141,'231123','逊克县','','','000080001100004',107,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1142,'231124','孙吴县','','','000080001100005',107,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1143,'231181','北安市','','','000080001100006',107,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1144,'231182','五大连池市','','','000080001100007',107,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1145,'231201','绥化市辖区','','','000080001200001',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1146,'231202','北林区','','','000080001200002',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1147,'231221','望奎县','','','000080001200003',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1148,'231222','兰西县','','','000080001200004',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1149,'231223','青冈县','','','000080001200005',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1150,'231224','庆安县','','','000080001200006',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1151,'231225','明水县','','','000080001200007',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1152,'231226','绥棱县','','','000080001200008',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1153,'231281','安达市','','','000080001200009',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1154,'231282','肇东市','','','000080001200010',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1155,'231283','海伦市','','','000080001200011',108,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1156,'232721','呼玛县','','','000080001300001',109,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1157,'232722','塔河县','','','000080001300002',109,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1158,'232723','漠河县','','','000080001300003',109,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1159,'310101','黄浦区','','','000090000100001',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1160,'310104','徐汇区','','','000090000100002',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1161,'310105','长宁区','','','000090000100003',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1162,'310106','静安区','','','000090000100004',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1163,'310107','普陀区','','','000090000100005',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1164,'310108','闸北区','','','000090000100006',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1165,'310109','虹口区','','','000090000100007',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1166,'310110','杨浦区','','','000090000100008',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1167,'310112','闵行区','','','000090000100009',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1168,'310113','宝山区','','','000090000100010',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1169,'310114','嘉定区','','','000090000100011',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1170,'310115','浦东新区','','','000090000100012',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1171,'310116','金山区','','','000090000100013',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1172,'310117','松江区','','','000090000100014',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1173,'310118','青浦区','','','000090000100015',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1174,'310120','奉贤区','','','000090000100016',110,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1175,'310230','崇明县','','','000090000200001',111,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1176,'320101','南京市辖区','','','000100000100001',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1177,'320102','玄武区','','','000100000100002',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1178,'320104','秦淮区','','','000100000100003',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1179,'320105','建邺区','','','000100000100004',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1180,'320106','鼓楼区','','','000100000100005',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1181,'320111','浦口区','','','000100000100006',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1182,'320113','栖霞区','','','000100000100007',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1183,'320114','雨花台区','','','000100000100008',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1184,'320115','江宁区','','','000100000100009',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1185,'320116','六合区','','','000100000100010',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1186,'320117','溧水区','','','000100000100011',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1187,'320118','高淳区','','','000100000100012',112,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1188,'320201','无锡市辖区','','','000100000200001',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1189,'320202','崇安区','','','000100000200002',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1190,'320203','南长区','','','000100000200003',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1191,'320204','北塘区','','','000100000200004',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1192,'320205','锡山区','','','000100000200005',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1193,'320206','惠山区','','','000100000200006',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1194,'320211','滨湖区','','','000100000200007',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1195,'320281','江阴市','','','000100000200008',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1196,'320282','宜兴市','','','000100000200009',113,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1197,'320301','徐州市辖区','','','000100000300001',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1198,'320302','鼓楼区','','','000100000300002',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1199,'320303','云龙区','','','000100000300003',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1200,'320305','贾汪区','','','000100000300004',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1201,'320311','泉山区','','','000100000300005',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1202,'320312','铜山区','','','000100000300006',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1203,'320321','丰县','','','000100000300007',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1204,'320322','沛县','','','000100000300008',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1205,'320324','睢宁县','','','000100000300009',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1206,'320381','新沂市','','','000100000300010',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1207,'320382','邳州市','','','000100000300011',114,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1208,'320401','常州市辖区','','','000100000400001',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1209,'320402','天宁区','','','000100000400002',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1210,'320404','钟楼区','','','000100000400003',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1211,'320405','戚墅堰区','','','000100000400004',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1212,'320411','新北区','','','000100000400005',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1213,'320412','武进区','','','000100000400006',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1214,'320481','溧阳市','','','000100000400007',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1215,'320482','金坛市','','','000100000400008',115,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1216,'320501','苏州市辖区','','','000100000500001',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1217,'320505','虎丘区','','','000100000500002',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1218,'320506','吴中区','','','000100000500003',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1219,'320507','相城区','','','000100000500004',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1220,'320508','姑苏区','','','000100000500005',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1221,'320509','吴江区','','','000100000500006',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1222,'320581','常熟市','','','000100000500007',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1223,'320582','张家港市','','','000100000500008',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1224,'320583','昆山市','','','000100000500009',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1225,'320585','太仓市','','','000100000500010',116,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1226,'320601','南通市辖区','','','000100000600001',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1227,'320602','崇川区','','','000100000600002',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1228,'320611','港闸区','','','000100000600003',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1229,'320612','通州区','','','000100000600004',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1230,'320621','海安县','','','000100000600005',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1231,'320623','如东县','','','000100000600006',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1232,'320681','启东市','','','000100000600007',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1233,'320682','如皋市','','','000100000600008',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1234,'320684','海门市','','','000100000600009',117,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1235,'320701','连云港市辖区','','','000100000700001',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1236,'320703','连云区','','','000100000700002',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1237,'320705','新浦区','','','000100000700003',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1238,'320706','海州区','','','000100000700004',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1239,'320721','赣榆县','','','000100000700005',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1240,'320722','东海县','','','000100000700006',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1241,'320723','灌云县','','','000100000700007',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1242,'320724','灌南县','','','000100000700008',118,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1243,'320801','淮安市辖区','','','000100000800001',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1244,'320802','清河区','','','000100000800002',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1245,'320803','淮安区','','','000100000800003',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1246,'320804','淮阴区','','','000100000800004',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1247,'320811','清浦区','','','000100000800005',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1248,'320826','涟水县','','','000100000800006',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1249,'320829','洪泽县','','','000100000800007',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1250,'320830','盱眙县','','','000100000800008',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1251,'320831','金湖县','','','000100000800009',119,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1252,'320901','盐城市辖区','','','000100000900001',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1253,'320902','亭湖区','','','000100000900002',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1254,'320903','盐都区','','','000100000900003',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1255,'320921','响水县','','','000100000900004',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1256,'320922','滨海县','','','000100000900005',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1257,'320923','阜宁县','','','000100000900006',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1258,'320924','射阳县','','','000100000900007',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1259,'320925','建湖县','','','000100000900008',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1260,'320981','东台市','','','000100000900009',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1261,'320982','大丰市','','','000100000900010',120,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1262,'321001','扬州市辖区','','','000100001000001',121,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1263,'321002','广陵区','','','000100001000002',121,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1264,'321003','邗江区','','','000100001000003',121,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1265,'321012','江都区','','','000100001000004',121,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1266,'321023','宝应县','','','000100001000005',121,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1267,'321081','仪征市','','','000100001000006',121,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1268,'321084','高邮市','','','000100001000007',121,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1269,'321101','镇江市辖区','','','000100001100001',122,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1270,'321102','京口区','','','000100001100002',122,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1271,'321111','润州区','','','000100001100003',122,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1272,'321112','丹徒区','','','000100001100004',122,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1273,'321181','丹阳市','','','000100001100005',122,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1274,'321182','扬中市','','','000100001100006',122,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1275,'321183','句容市','','','000100001100007',122,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1276,'321201','泰州市辖区','','','000100001200001',123,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1277,'321202','海陵区','','','000100001200002',123,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1278,'321203','高港区','','','000100001200003',123,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1279,'321204','姜堰区','','','000100001200004',123,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1280,'321281','兴化市','','','000100001200005',123,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1281,'321282','靖江市','','','000100001200006',123,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1282,'321283','泰兴市','','','000100001200007',123,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1283,'321301','宿迁市辖区','','','000100001300001',124,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1284,'321302','宿城区','','','000100001300002',124,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1285,'321311','宿豫区','','','000100001300003',124,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1286,'321322','沭阳县','','','000100001300004',124,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1287,'321323','泗阳县','','','000100001300005',124,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1288,'321324','泗洪县','','','000100001300006',124,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1289,'330101','杭州市辖区','','','000110000100001',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1290,'330102','上城区','','','000110000100002',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1291,'330103','下城区','','','000110000100003',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1292,'330104','江干区','','','000110000100004',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1293,'330105','拱墅区','','','000110000100005',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1294,'330106','西湖区','','','000110000100006',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1295,'330108','滨江区','','','000110000100007',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1296,'330109','萧山区','','','000110000100008',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1297,'330110','余杭区','','','000110000100009',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1298,'330122','桐庐县','','','000110000100010',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1299,'330127','淳安县','','','000110000100011',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1300,'330182','建德市','','','000110000100012',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1301,'330183','富阳市','','','000110000100013',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1302,'330185','临安市','','','000110000100014',125,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1303,'330201','宁波市辖区','','','000110000200001',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1304,'330203','海曙区','','','000110000200002',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1305,'330204','江东区','','','000110000200003',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1306,'330205','江北区','','','000110000200004',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1307,'330206','北仑区','','','000110000200005',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1308,'330211','镇海区','','','000110000200006',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1309,'330212','鄞州区','','','000110000200007',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1310,'330225','象山县','','','000110000200008',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1311,'330226','宁海县','','','000110000200009',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1312,'330281','余姚市','','','000110000200010',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1313,'330282','慈溪市','','','000110000200011',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1314,'330283','奉化市','','','000110000200012',126,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1315,'330301','温州市辖区','','','000110000300001',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1316,'330302','鹿城区','','','000110000300002',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1317,'330303','龙湾区','','','000110000300003',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1318,'330304','瓯海区','','','000110000300004',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1319,'330322','洞头县','','','000110000300005',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1320,'330324','永嘉县','','','000110000300006',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1321,'330326','平阳县','','','000110000300007',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1322,'330327','苍南县','','','000110000300008',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1323,'330328','文成县','','','000110000300009',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1324,'330329','泰顺县','','','000110000300010',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1325,'330381','瑞安市','','','000110000300011',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1326,'330382','乐清市','','','000110000300012',127,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1327,'330401','嘉兴市辖区','','','000110000400001',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1328,'330402','南湖区','','','000110000400002',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1329,'330411','秀洲区','','','000110000400003',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1330,'330421','嘉善县','','','000110000400004',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1331,'330424','海盐县','','','000110000400005',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1332,'330481','海宁市','','','000110000400006',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1333,'330482','平湖市','','','000110000400007',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1334,'330483','桐乡市','','','000110000400008',128,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1335,'330501','湖州市辖区','','','000110000500001',129,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1336,'330502','吴兴区','','','000110000500002',129,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1337,'330503','南浔区','','','000110000500003',129,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1338,'330521','德清县','','','000110000500004',129,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1339,'330522','长兴县','','','000110000500005',129,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1340,'330523','安吉县','','','000110000500006',129,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1341,'330601','绍兴市辖区','','','000110000600001',130,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1342,'330602','越城区','','','000110000600002',130,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1343,'330621','绍兴县','','','000110000600003',130,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1344,'330624','新昌县','','','000110000600004',130,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1345,'330681','诸暨市','','','000110000600005',130,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1346,'330682','上虞市','','','000110000600006',130,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1347,'330683','嵊州市','','','000110000600007',130,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1348,'330701','金华市辖区','','','000110000700001',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1349,'330702','婺城区','','','000110000700002',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1350,'330703','金东区','','','000110000700003',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1351,'330723','武义县','','','000110000700004',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1352,'330726','浦江县','','','000110000700005',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1353,'330727','磐安县','','','000110000700006',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1354,'330781','兰溪市','','','000110000700007',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1355,'330782','义乌市','','','000110000700008',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1356,'330783','东阳市','','','000110000700009',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1357,'330784','永康市','','','000110000700010',131,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1358,'330801','衢州市辖区','','','000110000800001',132,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1359,'330802','柯城区','','','000110000800002',132,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1360,'330803','衢江区','','','000110000800003',132,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1361,'330822','常山县','','','000110000800004',132,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1362,'330824','开化县','','','000110000800005',132,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1363,'330825','龙游县','','','000110000800006',132,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1364,'330881','江山市','','','000110000800007',132,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1365,'330901','舟山市辖区','','','000110000900001',133,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1366,'330902','定海区','','','000110000900002',133,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1367,'330903','普陀区','','','000110000900003',133,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1368,'330921','岱山县','','','000110000900004',133,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1369,'330922','嵊泗县','','','000110000900005',133,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1370,'331001','台州市辖区','','','000110001000001',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1371,'331002','椒江区','','','000110001000002',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1372,'331003','黄岩区','','','000110001000003',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1373,'331004','路桥区','','','000110001000004',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1374,'331021','玉环县','','','000110001000005',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1375,'331022','三门县','','','000110001000006',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1376,'331023','天台县','','','000110001000007',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1377,'331024','仙居县','','','000110001000008',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1378,'331081','温岭市','','','000110001000009',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1379,'331082','临海市','','','000110001000010',134,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1380,'331101','丽水市辖区','','','000110001100001',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1381,'331102','莲都区','','','000110001100002',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1382,'331121','青田县','','','000110001100003',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1383,'331122','缙云县','','','000110001100004',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1384,'331123','遂昌县','','','000110001100005',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1385,'331124','松阳县','','','000110001100006',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1386,'331125','云和县','','','000110001100007',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1387,'331126','庆元县','','','000110001100008',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1388,'331127','景宁畲族自治县','','','000110001100009',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1389,'331181','龙泉市','','','000110001100010',135,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1390,'340101','合肥市辖区','','','000120000100001',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1391,'340102','瑶海区','','','000120000100002',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1392,'340103','庐阳区','','','000120000100003',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1393,'340104','蜀山区','','','000120000100004',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1394,'340111','包河区','','','000120000100005',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1395,'340121','长丰县','','','000120000100006',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1396,'340122','肥东县','','','000120000100007',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1397,'340123','肥西县','','','000120000100008',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1398,'340124','庐江县','','','000120000100009',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1399,'340181','巢湖市','','','000120000100010',136,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1400,'340201','芜湖市辖区','','','000120000200001',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1401,'340202','镜湖区','','','000120000200002',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1402,'340203','弋江区','','','000120000200003',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1403,'340207','鸠江区','','','000120000200004',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1404,'340208','三山区','','','000120000200005',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1405,'340221','芜湖县','','','000120000200006',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1406,'340222','繁昌县','','','000120000200007',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1407,'340223','南陵县','','','000120000200008',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1408,'340225','无为县','','','000120000200009',137,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1409,'340301','蚌埠市辖区','','','000120000300001',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1410,'340302','龙子湖区','','','000120000300002',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1411,'340303','蚌山区','','','000120000300003',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1412,'340304','禹会区','','','000120000300004',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1413,'340311','淮上区','','','000120000300005',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1414,'340321','怀远县','','','000120000300006',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1415,'340322','五河县','','','000120000300007',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1416,'340323','固镇县','','','000120000300008',138,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1417,'340401','淮南市辖区','','','000120000400001',139,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1418,'340402','大通区','','','000120000400002',139,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1419,'340403','田家庵区','','','000120000400003',139,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1420,'340404','谢家集区','','','000120000400004',139,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1421,'340405','八公山区','','','000120000400005',139,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1422,'340406','潘集区','','','000120000400006',139,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1423,'340421','凤台县','','','000120000400007',139,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1424,'340501','马鞍山市辖区','','','000120000500001',140,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1425,'340503','花山区','','','000120000500002',140,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1426,'340504','雨山区','','','000120000500003',140,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1427,'340506','博望区','','','000120000500004',140,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1428,'340521','当涂县','','','000120000500005',140,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1429,'340522','含山县','','','000120000500006',140,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1430,'340523','和县','','','000120000500007',140,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1431,'340601','淮北市辖区','','','000120000600001',141,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1432,'340602','杜集区','','','000120000600002',141,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1433,'340603','相山区','','','000120000600003',141,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1434,'340604','烈山区','','','000120000600004',141,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1435,'340621','濉溪县','','','000120000600005',141,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1436,'340701','铜陵市辖区','','','000120000700001',142,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1437,'340702','铜官山区','','','000120000700002',142,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1438,'340703','狮子山区','','','000120000700003',142,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1439,'340711','郊区','','','000120000700004',142,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1440,'340721','铜陵县','','','000120000700005',142,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1441,'340801','安庆市辖区','','','000120000800001',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1442,'340802','迎江区','','','000120000800002',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1443,'340803','大观区','','','000120000800003',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1444,'340811','宜秀区','','','000120000800004',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1445,'340822','怀宁县','','','000120000800005',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1446,'340823','枞阳县','','','000120000800006',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1447,'340824','潜山县','','','000120000800007',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1448,'340825','太湖县','','','000120000800008',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1449,'340826','宿松县','','','000120000800009',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1450,'340827','望江县','','','000120000800010',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1451,'340828','岳西县','','','000120000800011',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1452,'340881','桐城市','','','000120000800012',143,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1453,'341001','黄山市辖区','','','000120000900001',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1454,'341002','屯溪区','','','000120000900002',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1455,'341003','黄山区','','','000120000900003',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1456,'341004','徽州区','','','000120000900004',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1457,'341021','歙县','','','000120000900005',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1458,'341022','休宁县','','','000120000900006',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1459,'341023','黟县','','','000120000900007',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1460,'341024','祁门县','','','000120000900008',144,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1461,'341101','滁州市辖区','','','000120001000001',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1462,'341102','琅琊区','','','000120001000002',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1463,'341103','南谯区','','','000120001000003',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1464,'341122','来安县','','','000120001000004',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1465,'341124','全椒县','','','000120001000005',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1466,'341125','定远县','','','000120001000006',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1467,'341126','凤阳县','','','000120001000007',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1468,'341181','天长市','','','000120001000008',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1469,'341182','明光市','','','000120001000009',145,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1470,'341201','阜阳市辖区','','','000120001100001',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1471,'341202','颍州区','','','000120001100002',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1472,'341203','颍东区','','','000120001100003',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1473,'341204','颍泉区','','','000120001100004',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1474,'341221','临泉县','','','000120001100005',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1475,'341222','太和县','','','000120001100006',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1476,'341225','阜南县','','','000120001100007',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1477,'341226','颍上县','','','000120001100008',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1478,'341282','界首市','','','000120001100009',146,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1479,'341301','宿州市辖区','','','000120001200001',147,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1480,'341302','埇桥区','','','000120001200002',147,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1481,'341321','砀山县','','','000120001200003',147,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1482,'341322','萧县','','','000120001200004',147,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1483,'341323','灵璧县','','','000120001200005',147,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1484,'341324','泗县','','','000120001200006',147,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1485,'341501','六安市辖区','','','000120001300001',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1486,'341502','金安区','','','000120001300002',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1487,'341503','裕安区','','','000120001300003',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1488,'341521','寿县','','','000120001300004',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1489,'341522','霍邱县','','','000120001300005',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1490,'341523','舒城县','','','000120001300006',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1491,'341524','金寨县','','','000120001300007',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1492,'341525','霍山县','','','000120001300008',148,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1493,'341601','亳州市辖区','','','000120001400001',149,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1494,'341602','谯城区','','','000120001400002',149,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1495,'341621','涡阳县','','','000120001400003',149,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1496,'341622','蒙城县','','','000120001400004',149,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1497,'341623','利辛县','','','000120001400005',149,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1498,'341701','池州市辖区','','','000120001500001',150,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1499,'341702','贵池区','','','000120001500002',150,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1500,'341721','东至县','','','000120001500003',150,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1501,'341722','石台县','','','000120001500004',150,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1502,'341723','青阳县','','','000120001500005',150,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1503,'341801','宣城市辖区','','','000120001600001',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1504,'341802','宣州区','','','000120001600002',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1505,'341821','郎溪县','','','000120001600003',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1506,'341822','广德县','','','000120001600004',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1507,'341823','泾县','','','000120001600005',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1508,'341824','绩溪县','','','000120001600006',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1509,'341825','旌德县','','','000120001600007',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1510,'341881','宁国市','','','000120001600008',151,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1511,'350101','福州市辖区','','','000130000100001',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1512,'350102','鼓楼区','','','000130000100002',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1513,'350103','台江区','','','000130000100003',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1514,'350104','仓山区','','','000130000100004',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1515,'350105','马尾区','','','000130000100005',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1516,'350111','晋安区','','','000130000100006',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1517,'350121','闽侯县','','','000130000100007',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1518,'350122','连江县','','','000130000100008',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1519,'350123','罗源县','','','000130000100009',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1520,'350124','闽清县','','','000130000100010',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1521,'350125','永泰县','','','000130000100011',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1522,'350128','平潭县','','','000130000100012',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1523,'350181','福清市','','','000130000100013',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1524,'350182','长乐市','','','000130000100014',152,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1525,'350201','厦门市辖区','','','000130000200001',153,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1526,'350203','思明区','','','000130000200002',153,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1527,'350205','海沧区','','','000130000200003',153,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1528,'350206','湖里区','','','000130000200004',153,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1529,'350211','集美区','','','000130000200005',153,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1530,'350212','同安区','','','000130000200006',153,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1531,'350213','翔安区','','','000130000200007',153,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1532,'350301','莆田市辖区','','','000130000300001',154,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1533,'350302','城厢区','','','000130000300002',154,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1534,'350303','涵江区','','','000130000300003',154,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1535,'350304','荔城区','','','000130000300004',154,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1536,'350305','秀屿区','','','000130000300005',154,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1537,'350322','仙游县','','','000130000300006',154,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1538,'350401','三明市辖区','','','000130000400001',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1539,'350402','梅列区','','','000130000400002',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1540,'350403','三元区','','','000130000400003',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1541,'350421','明溪县','','','000130000400004',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1542,'350423','清流县','','','000130000400005',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1543,'350424','宁化县','','','000130000400006',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1544,'350425','大田县','','','000130000400007',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1545,'350426','尤溪县','','','000130000400008',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1546,'350427','沙县','','','000130000400009',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1547,'350428','将乐县','','','000130000400010',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1548,'350429','泰宁县','','','000130000400011',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1549,'350430','建宁县','','','000130000400012',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1550,'350481','永安市','','','000130000400013',155,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1551,'350501','泉州市辖区','','','000130000500001',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1552,'350502','鲤城区','','','000130000500002',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1553,'350503','丰泽区','','','000130000500003',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1554,'350504','洛江区','','','000130000500004',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1555,'350505','泉港区','','','000130000500005',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1556,'350521','惠安县','','','000130000500006',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1557,'350524','安溪县','','','000130000500007',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1558,'350525','永春县','','','000130000500008',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1559,'350526','德化县','','','000130000500009',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1560,'350527','金门县','','','000130000500010',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1561,'350581','石狮市','','','000130000500011',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1562,'350582','晋江市','','','000130000500012',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1563,'350583','南安市','','','000130000500013',156,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1564,'350601','漳州市辖区','','','000130000600001',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1565,'350602','芗城区','','','000130000600002',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1566,'350603','龙文区','','','000130000600003',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1567,'350622','云霄县','','','000130000600004',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1568,'350623','漳浦县','','','000130000600005',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1569,'350624','诏安县','','','000130000600006',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1570,'350625','长泰县','','','000130000600007',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1571,'350626','东山县','','','000130000600008',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1572,'350627','南靖县','','','000130000600009',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1573,'350628','平和县','','','000130000600010',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1574,'350629','华安县','','','000130000600011',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1575,'350681','龙海市','','','000130000600012',157,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1576,'350701','南平市辖区','','','000130000700001',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1577,'350702','延平区','','','000130000700002',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1578,'350721','顺昌县','','','000130000700003',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1579,'350722','浦城县','','','000130000700004',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1580,'350723','光泽县','','','000130000700005',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1581,'350724','松溪县','','','000130000700006',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1582,'350725','政和县','','','000130000700007',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1583,'350781','邵武市','','','000130000700008',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1584,'350782','武夷山市','','','000130000700009',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1585,'350783','建瓯市','','','000130000700010',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1586,'350784','建阳市','','','000130000700011',158,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1587,'350801','龙岩市辖区','','','000130000800001',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1588,'350802','新罗区','','','000130000800002',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1589,'350821','长汀县','','','000130000800003',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1590,'350822','永定县','','','000130000800004',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1591,'350823','上杭县','','','000130000800005',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1592,'350824','武平县','','','000130000800006',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1593,'350825','连城县','','','000130000800007',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1594,'350881','漳平市','','','000130000800008',159,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1595,'350901','宁德市辖区','','','000130000900001',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1596,'350902','蕉城区','','','000130000900002',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1597,'350921','霞浦县','','','000130000900003',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1598,'350922','古田县','','','000130000900004',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1599,'350923','屏南县','','','000130000900005',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1600,'350924','寿宁县','','','000130000900006',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1601,'350925','周宁县','','','000130000900007',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1602,'350926','柘荣县','','','000130000900008',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1603,'350981','福安市','','','000130000900009',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1604,'350982','福鼎市','','','000130000900010',160,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1605,'360101','南昌市辖区','','','000140000100001',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1606,'360102','东湖区','','','000140000100002',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1607,'360103','西湖区','','','000140000100003',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1608,'360104','青云谱区','','','000140000100004',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1609,'360105','湾里区','','','000140000100005',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1610,'360111','青山湖区','','','000140000100006',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1611,'360121','南昌县','','','000140000100007',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1612,'360122','新建县','','','000140000100008',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1613,'360123','安义县','','','000140000100009',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1614,'360124','进贤县','','','000140000100010',161,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1615,'360201','景德镇市辖区','','','000140000200001',162,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1616,'360202','昌江区','','','000140000200002',162,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1617,'360203','珠山区','','','000140000200003',162,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1618,'360222','浮梁县','','','000140000200004',162,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1619,'360281','乐平市','','','000140000200005',162,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1620,'360301','萍乡市辖区','','','000140000300001',163,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1621,'360302','安源区','','','000140000300002',163,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1622,'360313','湘东区','','','000140000300003',163,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1623,'360321','莲花县','','','000140000300004',163,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1624,'360322','上栗县','','','000140000300005',163,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1625,'360323','芦溪县','','','000140000300006',163,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1626,'360401','九江市辖区','','','000140000400001',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1627,'360402','庐山区','','','000140000400002',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1628,'360403','浔阳区','','','000140000400003',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1629,'360421','九江县','','','000140000400004',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1630,'360423','武宁县','','','000140000400005',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1631,'360424','修水县','','','000140000400006',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1632,'360425','永修县','','','000140000400007',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1633,'360426','德安县','','','000140000400008',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1634,'360427','星子县','','','000140000400009',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1635,'360428','都昌县','','','000140000400010',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1636,'360429','湖口县','','','000140000400011',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1637,'360430','彭泽县','','','000140000400012',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1638,'360481','瑞昌市','','','000140000400013',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1639,'360482','共青城市','','','000140000400014',164,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1640,'360501','新余市辖区','','','000140000500001',165,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1641,'360502','渝水区','','','000140000500002',165,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1642,'360521','分宜县','','','000140000500003',165,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1643,'360601','鹰潭市辖区','','','000140000600001',166,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1644,'360602','月湖区','','','000140000600002',166,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1645,'360622','余江县','','','000140000600003',166,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1646,'360681','贵溪市','','','000140000600004',166,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1647,'360701','赣州市辖区','','','000140000700001',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1648,'360702','章贡区','','','000140000700002',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1649,'360721','赣县','','','000140000700003',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1650,'360722','信丰县','','','000140000700004',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1651,'360723','大余县','','','000140000700005',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1652,'360724','上犹县','','','000140000700006',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1653,'360725','崇义县','','','000140000700007',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1654,'360726','安远县','','','000140000700008',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1655,'360727','龙南县','','','000140000700009',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1656,'360728','定南县','','','000140000700010',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1657,'360729','全南县','','','000140000700011',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1658,'360730','宁都县','','','000140000700012',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1659,'360731','于都县','','','000140000700013',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1660,'360732','兴国县','','','000140000700014',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1661,'360733','会昌县','','','000140000700015',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1662,'360734','寻乌县','','','000140000700016',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1663,'360735','石城县','','','000140000700017',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1664,'360781','瑞金市','','','000140000700018',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1665,'360782','南康市','','','000140000700019',167,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1666,'360801','吉安市辖区','','','000140000800001',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1667,'360802','吉州区','','','000140000800002',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1668,'360803','青原区','','','000140000800003',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1669,'360821','吉安县','','','000140000800004',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1670,'360822','吉水县','','','000140000800005',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1671,'360823','峡江县','','','000140000800006',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1672,'360824','新干县','','','000140000800007',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1673,'360825','永丰县','','','000140000800008',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1674,'360826','泰和县','','','000140000800009',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1675,'360827','遂川县','','','000140000800010',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1676,'360828','万安县','','','000140000800011',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1677,'360829','安福县','','','000140000800012',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1678,'360830','永新县','','','000140000800013',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1679,'360881','井冈山市','','','000140000800014',168,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1680,'360901','宜春市辖区','','','000140000900001',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1681,'360902','袁州区','','','000140000900002',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1682,'360921','奉新县','','','000140000900003',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1683,'360922','万载县','','','000140000900004',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1684,'360923','上高县','','','000140000900005',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1685,'360924','宜丰县','','','000140000900006',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1686,'360925','靖安县','','','000140000900007',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1687,'360926','铜鼓县','','','000140000900008',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1688,'360981','丰城市','','','000140000900009',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1689,'360982','樟树市','','','000140000900010',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1690,'360983','高安市','','','000140000900011',169,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1691,'361001','抚州市辖区','','','000140001000001',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1692,'361002','临川区','','','000140001000002',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1693,'361021','南城县','','','000140001000003',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1694,'361022','黎川县','','','000140001000004',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1695,'361023','南丰县','','','000140001000005',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1696,'361024','崇仁县','','','000140001000006',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1697,'361025','乐安县','','','000140001000007',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1698,'361026','宜黄县','','','000140001000008',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1699,'361027','金溪县','','','000140001000009',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1700,'361028','资溪县','','','000140001000010',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1701,'361029','东乡县','','','000140001000011',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1702,'361030','广昌县','','','000140001000012',170,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1703,'361101','上饶市辖区','','','000140001100001',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1704,'361102','信州区','','','000140001100002',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1705,'361121','上饶县','','','000140001100003',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1706,'361122','广丰县','','','000140001100004',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1707,'361123','玉山县','','','000140001100005',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1708,'361124','铅山县','','','000140001100006',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1709,'361125','横峰县','','','000140001100007',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1710,'361126','弋阳县','','','000140001100008',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1711,'361127','余干县','','','000140001100009',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1712,'361128','鄱阳县','','','000140001100010',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1713,'361129','万年县','','','000140001100011',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1714,'361130','婺源县','','','000140001100012',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1715,'361181','德兴市','','','000140001100013',171,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1716,'370101','济南市辖区','','','000150000100001',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1717,'370102','历下区','','','000150000100002',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1718,'370103','市中区','','','000150000100003',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1719,'370104','槐荫区','','','000150000100004',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1720,'370105','天桥区','','','000150000100005',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1721,'370112','历城区','','','000150000100006',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1722,'370113','长清区','','','000150000100007',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1723,'370124','平阴县','','','000150000100008',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1724,'370125','济阳县','','','000150000100009',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1725,'370126','商河县','','','000150000100010',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1726,'370181','章丘市','','','000150000100011',172,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1727,'370201','青岛市辖区','','','000150000200001',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1728,'370202','市南区','','','000150000200002',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1729,'370203','市北区','','','000150000200003',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1730,'370211','黄岛区','','','000150000200004',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1731,'370212','崂山区','','','000150000200005',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1732,'370213','李沧区','','','000150000200006',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1733,'370214','城阳区','','','000150000200007',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1734,'370281','胶州市','','','000150000200008',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1735,'370282','即墨市','','','000150000200009',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1736,'370283','平度市','','','000150000200010',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1737,'370285','莱西市','','','000150000200011',173,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1738,'370301','淄博市辖区','','','000150000300001',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1739,'370302','淄川区','','','000150000300002',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1740,'370303','张店区','','','000150000300003',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1741,'370304','博山区','','','000150000300004',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1742,'370305','临淄区','','','000150000300005',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1743,'370306','周村区','','','000150000300006',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1744,'370321','桓台县','','','000150000300007',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1745,'370322','高青县','','','000150000300008',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1746,'370323','沂源县','','','000150000300009',174,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1747,'370401','枣庄市辖区','','','000150000400001',175,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1748,'370402','市中区','','','000150000400002',175,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1749,'370403','薛城区','','','000150000400003',175,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1750,'370404','峄城区','','','000150000400004',175,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1751,'370405','台儿庄区','','','000150000400005',175,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1752,'370406','山亭区','','','000150000400006',175,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1753,'370481','滕州市','','','000150000400007',175,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1754,'370501','东营市辖区','','','000150000500001',176,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1755,'370502','东营区','','','000150000500002',176,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1756,'370503','河口区','','','000150000500003',176,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1757,'370521','垦利县','','','000150000500004',176,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1758,'370522','利津县','','','000150000500005',176,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1759,'370523','广饶县','','','000150000500006',176,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1760,'370601','烟台市辖区','','','000150000600001',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1761,'370602','芝罘区','','','000150000600002',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1762,'370611','福山区','','','000150000600003',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1763,'370612','牟平区','','','000150000600004',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1764,'370613','莱山区','','','000150000600005',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1765,'370634','长岛县','','','000150000600006',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1766,'370681','龙口市','','','000150000600007',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1767,'370682','莱阳市','','','000150000600008',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1768,'370683','莱州市','','','000150000600009',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1769,'370684','蓬莱市','','','000150000600010',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1770,'370685','招远市','','','000150000600011',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1771,'370686','栖霞市','','','000150000600012',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1772,'370687','海阳市','','','000150000600013',177,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1773,'370701','潍坊市辖区','','','000150000700001',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1774,'370702','潍城区','','','000150000700002',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1775,'370703','寒亭区','','','000150000700003',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1776,'370704','坊子区','','','000150000700004',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1777,'370705','奎文区','','','000150000700005',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1778,'370724','临朐县','','','000150000700006',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1779,'370725','昌乐县','','','000150000700007',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1780,'370781','青州市','','','000150000700008',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1781,'370782','诸城市','','','000150000700009',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1782,'370783','寿光市','','','000150000700010',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1783,'370784','安丘市','','','000150000700011',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1784,'370785','高密市','','','000150000700012',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1785,'370786','昌邑市','','','000150000700013',178,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1786,'370801','济宁市辖区','','','000150000800001',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1787,'370802','市中区','','','000150000800002',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1788,'370811','任城区','','','000150000800003',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1789,'370826','微山县','','','000150000800004',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1790,'370827','鱼台县','','','000150000800005',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1791,'370828','金乡县','','','000150000800006',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1792,'370829','嘉祥县','','','000150000800007',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1793,'370830','汶上县','','','000150000800008',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1794,'370831','泗水县','','','000150000800009',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1795,'370832','梁山县','','','000150000800010',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1796,'370881','曲阜市','','','000150000800011',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1797,'370882','兖州市','','','000150000800012',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1798,'370883','邹城市','','','000150000800013',179,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1799,'370901','泰安市辖区','','','000150000900001',180,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1800,'370902','泰山区','','','000150000900002',180,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1801,'370911','岱岳区','','','000150000900003',180,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1802,'370921','宁阳县','','','000150000900004',180,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1803,'370923','东平县','','','000150000900005',180,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1804,'370982','新泰市','','','000150000900006',180,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1805,'370983','肥城市','','','000150000900007',180,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1806,'371001','威海市辖区','','','000150001000001',181,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1807,'371002','环翠区','','','000150001000002',181,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1808,'371081','文登市','','','000150001000003',181,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1809,'371082','荣成市','','','000150001000004',181,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1810,'371083','乳山市','','','000150001000005',181,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1811,'371101','日照市辖区','','','000150001100001',182,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1812,'371102','东港区','','','000150001100002',182,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1813,'371103','岚山区','','','000150001100003',182,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1814,'371121','五莲县','','','000150001100004',182,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1815,'371122','莒县','','','000150001100005',182,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1816,'371201','莱芜市辖区','','','000150001200001',183,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1817,'371202','莱城区','','','000150001200002',183,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1818,'371203','钢城区','','','000150001200003',183,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1819,'371301','临沂市辖区','','','000150001300001',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1820,'371302','兰山区','','','000150001300002',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1821,'371311','罗庄区','','','000150001300003',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1822,'371312','河东区','','','000150001300004',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1823,'371321','沂南县','','','000150001300005',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1824,'371322','郯城县','','','000150001300006',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1825,'371323','沂水县','','','000150001300007',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1826,'371324','苍山县','','','000150001300008',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1827,'371325','费县','','','000150001300009',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1828,'371326','平邑县','','','000150001300010',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1829,'371327','莒南县','','','000150001300011',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1830,'371328','蒙阴县','','','000150001300012',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1831,'371329','临沭县','','','000150001300013',184,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1832,'371401','德州市辖区','','','000150001400001',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1833,'371402','德城区','','','000150001400002',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1834,'371421','陵县','','','000150001400003',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1835,'371422','宁津县','','','000150001400004',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1836,'371423','庆云县','','','000150001400005',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1837,'371424','临邑县','','','000150001400006',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1838,'371425','齐河县','','','000150001400007',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1839,'371426','平原县','','','000150001400008',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1840,'371427','夏津县','','','000150001400009',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1841,'371428','武城县','','','000150001400010',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1842,'371481','乐陵市','','','000150001400011',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1843,'371482','禹城市','','','000150001400012',185,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1844,'371501','聊城市辖区','','','000150001500001',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1845,'371502','东昌府区','','','000150001500002',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1846,'371521','阳谷县','','','000150001500003',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1847,'371522','莘县','','','000150001500004',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1848,'371523','茌平县','','','000150001500005',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1849,'371524','东阿县','','','000150001500006',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1850,'371525','冠县','','','000150001500007',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1851,'371526','高唐县','','','000150001500008',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1852,'371581','临清市','','','000150001500009',186,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1853,'371601','滨州市辖区','','','000150001600001',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1854,'371602','滨城区','','','000150001600002',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1855,'371621','惠民县','','','000150001600003',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1856,'371622','阳信县','','','000150001600004',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1857,'371623','无棣县','','','000150001600005',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1858,'371624','沾化县','','','000150001600006',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1859,'371625','博兴县','','','000150001600007',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1860,'371626','邹平县','','','000150001600008',187,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1861,'371701','菏泽市辖区','','','000150001700001',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1862,'371702','牡丹区','','','000150001700002',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1863,'371721','曹县','','','000150001700003',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1864,'371722','单县','','','000150001700004',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1865,'371723','成武县','','','000150001700005',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1866,'371724','巨野县','','','000150001700006',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1867,'371725','郓城县','','','000150001700007',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1868,'371726','鄄城县','','','000150001700008',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1869,'371727','定陶县','','','000150001700009',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1870,'371728','东明县','','','000150001700010',188,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1871,'410101','郑州市辖区','','','000160000100001',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1872,'410102','中原区','','','000160000100002',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1873,'410103','二七区','','','000160000100003',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1874,'410104','管城回族区','','','000160000100004',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1875,'410105','金水区','','','000160000100005',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1876,'410106','上街区','','','000160000100006',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1877,'410108','惠济区','','','000160000100007',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1878,'410122','中牟县','','','000160000100008',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1879,'410181','巩义市','','','000160000100009',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1880,'410182','荥阳市','','','000160000100010',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1881,'410183','新密市','','','000160000100011',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1882,'410184','新郑市','','','000160000100012',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1883,'410185','登封市','','','000160000100013',189,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1884,'410201','开封市辖区','','','000160000200001',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1885,'410202','龙亭区','','','000160000200002',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1886,'410203','顺河回族区','','','000160000200003',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1887,'410204','鼓楼区','','','000160000200004',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1888,'410205','禹王台区','','','000160000200005',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1889,'410211','金明区','','','000160000200006',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1890,'410221','杞县','','','000160000200007',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1891,'410222','通许县','','','000160000200008',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1892,'410223','尉氏县','','','000160000200009',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1893,'410224','开封县','','','000160000200010',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1894,'410225','兰考县','','','000160000200011',190,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1895,'410301','洛阳市辖区','','','000160000300001',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1896,'410302','老城区','','','000160000300002',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1897,'410303','西工区','','','000160000300003',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1898,'410304','瀍河回族区','','','000160000300004',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1899,'410305','涧西区','','','000160000300005',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1900,'410306','吉利区','','','000160000300006',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1901,'410311','洛龙区','','','000160000300007',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1902,'410322','孟津县','','','000160000300008',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1903,'410323','新安县','','','000160000300009',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1904,'410324','栾川县','','','000160000300010',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1905,'410325','嵩县','','','000160000300011',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1906,'410326','汝阳县','','','000160000300012',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1907,'410327','宜阳县','','','000160000300013',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1908,'410328','洛宁县','','','000160000300014',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1909,'410329','伊川县','','','000160000300015',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1910,'410381','偃师市','','','000160000300016',191,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1911,'410401','平顶山市辖区','','','000160000400001',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1912,'410402','新华区','','','000160000400002',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1913,'410403','卫东区','','','000160000400003',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1914,'410404','石龙区','','','000160000400004',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1915,'410411','湛河区','','','000160000400005',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1916,'410421','宝丰县','','','000160000400006',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1917,'410422','叶县','','','000160000400007',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1918,'410423','鲁山县','','','000160000400008',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1919,'410425','郏县','','','000160000400009',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1920,'410481','舞钢市','','','000160000400010',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1921,'410482','汝州市','','','000160000400011',192,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1922,'410501','安阳市辖区','','','000160000500001',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1923,'410502','文峰区','','','000160000500002',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1924,'410503','北关区','','','000160000500003',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1925,'410505','殷都区','','','000160000500004',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1926,'410506','龙安区','','','000160000500005',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1927,'410522','安阳县','','','000160000500006',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1928,'410523','汤阴县','','','000160000500007',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1929,'410526','滑县','','','000160000500008',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1930,'410527','内黄县','','','000160000500009',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1931,'410581','林州市','','','000160000500010',193,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1932,'410601','鹤壁市辖区','','','000160000600001',194,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1933,'410602','鹤山区','','','000160000600002',194,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1934,'410603','山城区','','','000160000600003',194,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1935,'410611','淇滨区','','','000160000600004',194,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1936,'410621','浚县','','','000160000600005',194,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1937,'410622','淇县','','','000160000600006',194,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1938,'410701','新乡市辖区','','','000160000700001',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1939,'410702','红旗区','','','000160000700002',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1940,'410703','卫滨区','','','000160000700003',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1941,'410704','凤泉区','','','000160000700004',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1942,'410711','牧野区','','','000160000700005',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1943,'410721','新乡县','','','000160000700006',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1944,'410724','获嘉县','','','000160000700007',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1945,'410725','原阳县','','','000160000700008',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1946,'410726','延津县','','','000160000700009',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1947,'410727','封丘县','','','000160000700010',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1948,'410728','长垣县','','','000160000700011',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1949,'410781','卫辉市','','','000160000700012',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1950,'410782','辉县市','','','000160000700013',195,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1951,'410801','焦作市辖区','','','000160000800001',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1952,'410802','解放区','','','000160000800002',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1953,'410803','中站区','','','000160000800003',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1954,'410804','马村区','','','000160000800004',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1955,'410811','山阳区','','','000160000800005',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1956,'410821','修武县','','','000160000800006',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1957,'410822','博爱县','','','000160000800007',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1958,'410823','武陟县','','','000160000800008',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1959,'410825','温县','','','000160000800009',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1960,'410882','沁阳市','','','000160000800010',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1961,'410883','孟州市','','','000160000800011',196,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1962,'410901','濮阳市辖区','','','000160000900001',197,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1963,'410902','华龙区','','','000160000900002',197,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1964,'410922','清丰县','','','000160000900003',197,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1965,'410923','南乐县','','','000160000900004',197,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1966,'410926','范县','','','000160000900005',197,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1967,'410927','台前县','','','000160000900006',197,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1968,'410928','濮阳县','','','000160000900007',197,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1969,'411001','许昌市辖区','','','000160001000001',198,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1970,'411002','魏都区','','','000160001000002',198,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1971,'411023','许昌县','','','000160001000003',198,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1972,'411024','鄢陵县','','','000160001000004',198,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1973,'411025','襄城县','','','000160001000005',198,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1974,'411081','禹州市','','','000160001000006',198,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1975,'411082','长葛市','','','000160001000007',198,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1976,'411101','漯河市辖区','','','000160001100001',199,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1977,'411102','源汇区','','','000160001100002',199,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1978,'411103','郾城区','','','000160001100003',199,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1979,'411104','召陵区','','','000160001100004',199,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1980,'411121','舞阳县','','','000160001100005',199,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1981,'411122','临颍县','','','000160001100006',199,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1982,'411201','三门峡市辖区','','','000160001200001',200,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1983,'411202','湖滨区','','','000160001200002',200,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1984,'411221','渑池县','','','000160001200003',200,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1985,'411222','陕县','','','000160001200004',200,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1986,'411224','卢氏县','','','000160001200005',200,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1987,'411281','义马市','','','000160001200006',200,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1988,'411282','灵宝市','','','000160001200007',200,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1989,'411301','南阳市辖区','','','000160001300001',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1990,'411302','宛城区','','','000160001300002',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1991,'411303','卧龙区','','','000160001300003',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1992,'411321','南召县','','','000160001300004',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1993,'411322','方城县','','','000160001300005',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1994,'411323','西峡县','','','000160001300006',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1995,'411324','镇平县','','','000160001300007',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1996,'411325','内乡县','','','000160001300008',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1997,'411326','淅川县','','','000160001300009',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1998,'411327','社旗县','','','000160001300010',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (1999,'411328','唐河县','','','000160001300011',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2000,'411329','新野县','','','000160001300012',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2001,'411330','桐柏县','','','000160001300013',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2002,'411381','邓州市','','','000160001300014',201,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2003,'411401','商丘市辖区','','','000160001400001',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2004,'411402','梁园区','','','000160001400002',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2005,'411403','睢阳区','','','000160001400003',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2006,'411421','民权县','','','000160001400004',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2007,'411422','睢县','','','000160001400005',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2008,'411423','宁陵县','','','000160001400006',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2009,'411424','柘城县','','','000160001400007',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2010,'411425','虞城县','','','000160001400008',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2011,'411426','夏邑县','','','000160001400009',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2012,'411481','永城市','','','000160001400010',202,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2013,'411501','信阳市辖区','','','000160001500001',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2014,'411502','浉河区','','','000160001500002',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2015,'411503','平桥区','','','000160001500003',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2016,'411521','罗山县','','','000160001500004',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2017,'411522','光山县','','','000160001500005',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2018,'411523','新县','','','000160001500006',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2019,'411524','商城县','','','000160001500007',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2020,'411525','固始县','','','000160001500008',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2021,'411526','潢川县','','','000160001500009',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2022,'411527','淮滨县','','','000160001500010',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2023,'411528','息县','','','000160001500011',203,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2024,'411601','周口市辖区','','','000160001600001',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2025,'411602','川汇区','','','000160001600002',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2026,'411621','扶沟县','','','000160001600003',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2027,'411622','西华县','','','000160001600004',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2028,'411623','商水县','','','000160001600005',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2029,'411624','沈丘县','','','000160001600006',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2030,'411625','郸城县','','','000160001600007',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2031,'411626','淮阳县','','','000160001600008',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2032,'411627','太康县','','','000160001600009',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2033,'411628','鹿邑县','','','000160001600010',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2034,'411681','项城市','','','000160001600011',204,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2035,'411701','驻马店市辖区','','','000160001700001',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2036,'411702','驿城区','','','000160001700002',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2037,'411721','西平县','','','000160001700003',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2038,'411722','上蔡县','','','000160001700004',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2039,'411723','平舆县','','','000160001700005',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2040,'411724','正阳县','','','000160001700006',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2041,'411725','确山县','','','000160001700007',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2042,'411726','泌阳县','','','000160001700008',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2043,'411727','汝南县','','','000160001700009',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2044,'411728','遂平县','','','000160001700010',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2045,'411729','新蔡县','','','000160001700011',205,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2046,'419001','济源市','','','000160001800001',206,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2047,'420101','武汉市辖区','','','000170000100001',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2048,'420102','江岸区','','','000170000100002',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2049,'420103','江汉区','','','000170000100003',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2050,'420104','硚口区','','','000170000100004',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2051,'420105','汉阳区','','','000170000100005',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2052,'420106','武昌区','','','000170000100006',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2053,'420107','青山区','','','000170000100007',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2054,'420111','洪山区','','','000170000100008',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2055,'420112','东西湖区','','','000170000100009',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2056,'420113','汉南区','','','000170000100010',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2057,'420114','蔡甸区','','','000170000100011',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2058,'420115','江夏区','','','000170000100012',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2059,'420116','黄陂区','','','000170000100013',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2060,'420117','新洲区','','','000170000100014',207,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2061,'420201','黄石市辖区','','','000170000200001',208,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2062,'420202','黄石港区','','','000170000200002',208,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2063,'420203','西塞山区','','','000170000200003',208,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2064,'420204','下陆区','','','000170000200004',208,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2065,'420205','铁山区','','','000170000200005',208,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2066,'420222','阳新县','','','000170000200006',208,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2067,'420281','大冶市','','','000170000200007',208,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2068,'420301','十堰市辖区','','','000170000300001',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2069,'420302','茅箭区','','','000170000300002',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2070,'420303','张湾区','','','000170000300003',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2071,'420321','郧县','','','000170000300004',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2072,'420322','郧西县','','','000170000300005',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2073,'420323','竹山县','','','000170000300006',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2074,'420324','竹溪县','','','000170000300007',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2075,'420325','房县','','','000170000300008',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2076,'420381','丹江口市','','','000170000300009',209,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2077,'420501','宜昌市辖区','','','000170000400001',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2078,'420502','西陵区','','','000170000400002',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2079,'420503','伍家岗区','','','000170000400003',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2080,'420504','点军区','','','000170000400004',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2081,'420505','猇亭区','','','000170000400005',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2082,'420506','夷陵区','','','000170000400006',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2083,'420525','远安县','','','000170000400007',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2084,'420526','兴山县','','','000170000400008',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2085,'420527','秭归县','','','000170000400009',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2086,'420528','长阳土家族自治县','','','000170000400010',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2087,'420529','五峰土家族自治县','','','000170000400011',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2088,'420581','宜都市','','','000170000400012',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2089,'420582','当阳市','','','000170000400013',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2090,'420583','枝江市','','','000170000400014',210,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2091,'420601','襄阳市辖区','','','000170000500001',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2092,'420602','襄城区','','','000170000500002',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2093,'420606','樊城区','','','000170000500003',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2094,'420607','襄州区','','','000170000500004',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2095,'420624','南漳县','','','000170000500005',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2096,'420625','谷城县','','','000170000500006',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2097,'420626','保康县','','','000170000500007',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2098,'420682','老河口市','','','000170000500008',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2099,'420683','枣阳市','','','000170000500009',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2100,'420684','宜城市','','','000170000500010',211,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2101,'420701','鄂州市辖区','','','000170000600001',212,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2102,'420702','梁子湖区','','','000170000600002',212,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2103,'420703','华容区','','','000170000600003',212,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2104,'420704','鄂城区','','','000170000600004',212,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2105,'420801','荆门市辖区','','','000170000700001',213,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2106,'420802','东宝区','','','000170000700002',213,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2107,'420804','掇刀区','','','000170000700003',213,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2108,'420821','京山县','','','000170000700004',213,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2109,'420822','沙洋县','','','000170000700005',213,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2110,'420881','钟祥市','','','000170000700006',213,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2111,'420901','孝感市辖区','','','000170000800001',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2112,'420902','孝南区','','','000170000800002',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2113,'420921','孝昌县','','','000170000800003',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2114,'420922','大悟县','','','000170000800004',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2115,'420923','云梦县','','','000170000800005',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2116,'420981','应城市','','','000170000800006',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2117,'420982','安陆市','','','000170000800007',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2118,'420984','汉川市','','','000170000800008',214,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2119,'421001','荆州市辖区','','','000170000900001',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2120,'421002','沙市区','','','000170000900002',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2121,'421003','荆州区','','','000170000900003',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2122,'421022','公安县','','','000170000900004',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2123,'421023','监利县','','','000170000900005',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2124,'421024','江陵县','','','000170000900006',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2125,'421081','石首市','','','000170000900007',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2126,'421083','洪湖市','','','000170000900008',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2127,'421087','松滋市','','','000170000900009',215,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2128,'421101','黄冈市辖区','','','000170001000001',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2129,'421102','黄州区','','','000170001000002',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2130,'421121','团风县','','','000170001000003',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2131,'421122','红安县','','','000170001000004',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2132,'421123','罗田县','','','000170001000005',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2133,'421124','英山县','','','000170001000006',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2134,'421125','浠水县','','','000170001000007',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2135,'421126','蕲春县','','','000170001000008',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2136,'421127','黄梅县','','','000170001000009',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2137,'421181','麻城市','','','000170001000010',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2138,'421182','武穴市','','','000170001000011',216,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2139,'421201','咸宁市辖区','','','000170001100001',217,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2140,'421202','咸安区','','','000170001100002',217,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2141,'421221','嘉鱼县','','','000170001100003',217,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2142,'421222','通城县','','','000170001100004',217,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2143,'421223','崇阳县','','','000170001100005',217,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2144,'421224','通山县','','','000170001100006',217,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2145,'421281','赤壁市','','','000170001100007',217,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2146,'421301','随州市辖区','','','000170001200001',218,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2147,'421303','曾都区','','','000170001200002',218,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2148,'421321','随县','','','000170001200003',218,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2149,'421381','广水市','','','000170001200004',218,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2150,'422801','恩施市','','','000170001300001',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2151,'422802','利川市','','','000170001300002',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2152,'422822','建始县','','','000170001300003',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2153,'422823','巴东县','','','000170001300004',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2154,'422825','宣恩县','','','000170001300005',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2155,'422826','咸丰县','','','000170001300006',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2156,'422827','来凤县','','','000170001300007',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2157,'422828','鹤峰县','','','000170001300008',219,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2158,'429004','仙桃市','','','000170001400001',220,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2159,'429005','潜江市','','','000170001400002',220,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2160,'429006','天门市','','','000170001400003',220,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2161,'429021','神农架林区','','','000170001400004',220,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2162,'430101','长沙市辖区','','','000180000100001',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2163,'430102','芙蓉区','','','000180000100002',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2164,'430103','天心区','','','000180000100003',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2165,'430104','岳麓区','','','000180000100004',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2166,'430105','开福区','','','000180000100005',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2167,'430111','雨花区','','','000180000100006',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2168,'430112','望城区','','','000180000100007',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2169,'430121','长沙县','','','000180000100008',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2170,'430124','宁乡县','','','000180000100009',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2171,'430181','浏阳市','','','000180000100010',221,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2172,'430201','株洲市辖区','','','000180000200001',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2173,'430202','荷塘区','','','000180000200002',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2174,'430203','芦淞区','','','000180000200003',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2175,'430204','石峰区','','','000180000200004',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2176,'430211','天元区','','','000180000200005',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2177,'430221','株洲县','','','000180000200006',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2178,'430223','攸县','','','000180000200007',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2179,'430224','茶陵县','','','000180000200008',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2180,'430225','炎陵县','','','000180000200009',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2181,'430281','醴陵市','','','000180000200010',222,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2182,'430301','湘潭市辖区','','','000180000300001',223,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2183,'430302','雨湖区','','','000180000300002',223,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2184,'430304','岳塘区','','','000180000300003',223,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2185,'430321','湘潭县','','','000180000300004',223,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2186,'430381','湘乡市','','','000180000300005',223,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2187,'430382','韶山市','','','000180000300006',223,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2188,'430401','衡阳市辖区','','','000180000400001',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2189,'430405','珠晖区','','','000180000400002',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2190,'430406','雁峰区','','','000180000400003',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2191,'430407','石鼓区','','','000180000400004',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2192,'430408','蒸湘区','','','000180000400005',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2193,'430412','南岳区','','','000180000400006',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2194,'430421','衡阳县','','','000180000400007',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2195,'430422','衡南县','','','000180000400008',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2196,'430423','衡山县','','','000180000400009',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2197,'430424','衡东县','','','000180000400010',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2198,'430426','祁东县','','','000180000400011',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2199,'430481','耒阳市','','','000180000400012',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2200,'430482','常宁市','','','000180000400013',224,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2201,'430501','邵阳市辖区','','','000180000500001',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2202,'430502','双清区','','','000180000500002',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2203,'430503','大祥区','','','000180000500003',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2204,'430511','北塔区','','','000180000500004',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2205,'430521','邵东县','','','000180000500005',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2206,'430522','新邵县','','','000180000500006',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2207,'430523','邵阳县','','','000180000500007',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2208,'430524','隆回县','','','000180000500008',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2209,'430525','洞口县','','','000180000500009',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2210,'430527','绥宁县','','','000180000500010',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2211,'430528','新宁县','','','000180000500011',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2212,'430529','城步苗族自治县','','','000180000500012',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2213,'430581','武冈市','','','000180000500013',225,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2214,'430601','岳阳市辖区','','','000180000600001',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2215,'430602','岳阳楼区','','','000180000600002',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2216,'430603','云溪区','','','000180000600003',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2217,'430611','君山区','','','000180000600004',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2218,'430621','岳阳县','','','000180000600005',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2219,'430623','华容县','','','000180000600006',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2220,'430624','湘阴县','','','000180000600007',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2221,'430626','平江县','','','000180000600008',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2222,'430681','汨罗市','','','000180000600009',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2223,'430682','临湘市','','','000180000600010',226,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2224,'430701','常德市辖区','','','000180000700001',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2225,'430702','武陵区','','','000180000700002',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2226,'430703','鼎城区','','','000180000700003',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2227,'430721','安乡县','','','000180000700004',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2228,'430722','汉寿县','','','000180000700005',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2229,'430723','澧县','','','000180000700006',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2230,'430724','临澧县','','','000180000700007',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2231,'430725','桃源县','','','000180000700008',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2232,'430726','石门县','','','000180000700009',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2233,'430781','津市市','','','000180000700010',227,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2234,'430801','张家界市辖区','','','000180000800001',228,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2235,'430802','永定区','','','000180000800002',228,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2236,'430811','武陵源区','','','000180000800003',228,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2237,'430821','慈利县','','','000180000800004',228,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2238,'430822','桑植县','','','000180000800005',228,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2239,'430901','益阳市辖区','','','000180000900001',229,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2240,'430902','资阳区','','','000180000900002',229,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2241,'430903','赫山区','','','000180000900003',229,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2242,'430921','南县','','','000180000900004',229,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2243,'430922','桃江县','','','000180000900005',229,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2244,'430923','安化县','','','000180000900006',229,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2245,'430981','沅江市','','','000180000900007',229,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2246,'431001','郴州市辖区','','','000180001000001',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2247,'431002','北湖区','','','000180001000002',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2248,'431003','苏仙区','','','000180001000003',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2249,'431021','桂阳县','','','000180001000004',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2250,'431022','宜章县','','','000180001000005',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2251,'431023','永兴县','','','000180001000006',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2252,'431024','嘉禾县','','','000180001000007',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2253,'431025','临武县','','','000180001000008',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2254,'431026','汝城县','','','000180001000009',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2255,'431027','桂东县','','','000180001000010',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2256,'431028','安仁县','','','000180001000011',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2257,'431081','资兴市','','','000180001000012',230,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2258,'431101','永州市辖区','','','000180001100001',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2259,'431102','零陵区','','','000180001100002',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2260,'431103','冷水滩区','','','000180001100003',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2261,'431121','祁阳县','','','000180001100004',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2262,'431122','东安县','','','000180001100005',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2263,'431123','双牌县','','','000180001100006',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2264,'431124','道县','','','000180001100007',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2265,'431125','江永县','','','000180001100008',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2266,'431126','宁远县','','','000180001100009',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2267,'431127','蓝山县','','','000180001100010',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2268,'431128','新田县','','','000180001100011',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2269,'431129','江华瑶族自治县','','','000180001100012',231,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2270,'431201','怀化市辖区','','','000180001200001',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2271,'431202','鹤城区','','','000180001200002',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2272,'431221','中方县','','','000180001200003',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2273,'431222','沅陵县','','','000180001200004',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2274,'431223','辰溪县','','','000180001200005',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2275,'431224','溆浦县','','','000180001200006',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2276,'431225','会同县','','','000180001200007',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2277,'431226','麻阳苗族自治县','','','000180001200008',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2278,'431227','新晃侗族自治县','','','000180001200009',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2279,'431228','芷江侗族自治县','','','000180001200010',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2280,'431229','靖州苗族侗族自治县','','','000180001200011',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2281,'431230','通道侗族自治县','','','000180001200012',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2282,'431281','洪江市','','','000180001200013',232,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2283,'431301','娄底市辖区','','','000180001300001',233,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2284,'431302','娄星区','','','000180001300002',233,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2285,'431321','双峰县','','','000180001300003',233,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2286,'431322','新化县','','','000180001300004',233,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2287,'431381','冷水江市','','','000180001300005',233,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2288,'431382','涟源市','','','000180001300006',233,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2289,'433101','吉首市','','','000180001400001',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2290,'433122','泸溪县','','','000180001400002',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2291,'433123','凤凰县','','','000180001400003',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2292,'433124','花垣县','','','000180001400004',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2293,'433125','保靖县','','','000180001400005',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2294,'433126','古丈县','','','000180001400006',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2295,'433127','永顺县','','','000180001400007',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2296,'433130','龙山县','','','000180001400008',234,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2297,'440101','广州市辖区','','','000190000100001',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2298,'440103','荔湾区','','','000190000100002',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2299,'440104','越秀区','','','000190000100003',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2300,'440105','海珠区','','','000190000100004',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2301,'440106','天河区','','','000190000100005',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2302,'440111','白云区','','','000190000100006',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2303,'440112','黄埔区','','','000190000100007',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2304,'440113','番禺区','','','000190000100008',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2305,'440114','花都区','','','000190000100009',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2306,'440115','南沙区','','','000190000100010',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2307,'440116','萝岗区','','','000190000100011',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2308,'440183','增城市','','','000190000100012',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2309,'440184','从化市','','','000190000100013',235,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2310,'440201','韶关市辖区','','','000190000200001',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2311,'440203','武江区','','','000190000200002',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2312,'440204','浈江区','','','000190000200003',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2313,'440205','曲江区','','','000190000200004',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2314,'440222','始兴县','','','000190000200005',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2315,'440224','仁化县','','','000190000200006',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2316,'440229','翁源县','','','000190000200007',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2317,'440232','乳源瑶族自治县','','','000190000200008',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2318,'440233','新丰县','','','000190000200009',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2319,'440281','乐昌市','','','000190000200010',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2320,'440282','南雄市','','','000190000200011',236,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2321,'440301','深圳市辖区','','','000190000300001',237,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2322,'440303','罗湖区','','','000190000300002',237,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2323,'440304','福田区','','','000190000300003',237,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2324,'440305','南山区','','','000190000300004',237,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2325,'440306','宝安区','','','000190000300005',237,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2326,'440307','龙岗区','','','000190000300006',237,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2327,'440308','盐田区','','','000190000300007',237,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2328,'440401','珠海市辖区','','','000190000400001',238,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2329,'440402','香洲区','','','000190000400002',238,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2330,'440403','斗门区','','','000190000400003',238,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2331,'440404','金湾区','','','000190000400004',238,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2332,'440501','汕头市辖区','','','000190000500001',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2333,'440507','龙湖区','','','000190000500002',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2334,'440511','金平区','','','000190000500003',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2335,'440512','濠江区','','','000190000500004',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2336,'440513','潮阳区','','','000190000500005',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2337,'440514','潮南区','','','000190000500006',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2338,'440515','澄海区','','','000190000500007',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2339,'440523','南澳县','','','000190000500008',239,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2340,'440601','佛山市辖区','','','000190000600001',240,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2341,'440604','禅城区','','','000190000600002',240,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2342,'440605','南海区','','','000190000600003',240,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2343,'440606','顺德区','','','000190000600004',240,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2344,'440607','三水区','','','000190000600005',240,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2345,'440608','高明区','','','000190000600006',240,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2346,'440701','江门市辖区','','','000190000700001',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2347,'440703','蓬江区','','','000190000700002',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2348,'440704','江海区','','','000190000700003',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2349,'440705','新会区','','','000190000700004',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2350,'440781','台山市','','','000190000700005',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2351,'440783','开平市','','','000190000700006',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2352,'440784','鹤山市','','','000190000700007',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2353,'440785','恩平市','','','000190000700008',241,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2354,'440801','湛江市辖区','','','000190000800001',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2355,'440802','赤坎区','','','000190000800002',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2356,'440803','霞山区','','','000190000800003',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2357,'440804','坡头区','','','000190000800004',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2358,'440811','麻章区','','','000190000800005',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2359,'440823','遂溪县','','','000190000800006',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2360,'440825','徐闻县','','','000190000800007',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2361,'440881','廉江市','','','000190000800008',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2362,'440882','雷州市','','','000190000800009',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2363,'440883','吴川市','','','000190000800010',242,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2364,'440901','茂名市辖区','','','000190000900001',243,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2365,'440902','茂南区','','','000190000900002',243,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2366,'440903','茂港区','','','000190000900003',243,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2367,'440923','电白县','','','000190000900004',243,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2368,'440981','高州市','','','000190000900005',243,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2369,'440982','化州市','','','000190000900006',243,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2370,'440983','信宜市','','','000190000900007',243,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2371,'441201','肇庆市辖区','','','000190001000001',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2372,'441202','端州区','','','000190001000002',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2373,'441203','鼎湖区','','','000190001000003',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2374,'441223','广宁县','','','000190001000004',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2375,'441224','怀集县','','','000190001000005',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2376,'441225','封开县','','','000190001000006',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2377,'441226','德庆县','','','000190001000007',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2378,'441283','高要市','','','000190001000008',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2379,'441284','四会市','','','000190001000009',244,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2380,'441301','惠州市辖区','','','000190001100001',245,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2381,'441302','惠城区','','','000190001100002',245,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2382,'441303','惠阳区','','','000190001100003',245,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2383,'441322','博罗县','','','000190001100004',245,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2384,'441323','惠东县','','','000190001100005',245,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2385,'441324','龙门县','','','000190001100006',245,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2386,'441401','梅州市辖区','','','000190001200001',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2387,'441402','梅江区','','','000190001200002',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2388,'441421','梅县','','','000190001200003',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2389,'441422','大埔县','','','000190001200004',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2390,'441423','丰顺县','','','000190001200005',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2391,'441424','五华县','','','000190001200006',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2392,'441426','平远县','','','000190001200007',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2393,'441427','蕉岭县','','','000190001200008',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2394,'441481','兴宁市','','','000190001200009',246,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2395,'441501','汕尾市辖区','','','000190001300001',247,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2396,'441502','城区','','','000190001300002',247,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2397,'441521','海丰县','','','000190001300003',247,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2398,'441523','陆河县','','','000190001300004',247,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2399,'441581','陆丰市','','','000190001300005',247,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2400,'441601','河源市辖区','','','000190001400001',248,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2401,'441602','源城区','','','000190001400002',248,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2402,'441621','紫金县','','','000190001400003',248,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2403,'441622','龙川县','','','000190001400004',248,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2404,'441623','连平县','','','000190001400005',248,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2405,'441624','和平县','','','000190001400006',248,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2406,'441625','东源县','','','000190001400007',248,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2407,'441701','阳江市辖区','','','000190001500001',249,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2408,'441702','江城区','','','000190001500002',249,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2409,'441721','阳西县','','','000190001500003',249,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2410,'441723','阳东县','','','000190001500004',249,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2411,'441781','阳春市','','','000190001500005',249,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2412,'441801','清远市辖区','','','000190001600001',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2413,'441802','清城区','','','000190001600002',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2414,'441803','清新区','','','000190001600003',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2415,'441821','佛冈县','','','000190001600004',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2416,'441823','阳山县','','','000190001600005',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2417,'441825','连山壮族瑶族自治县','','','000190001600006',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2418,'441826','连南瑶族自治县','','','000190001600007',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2419,'441881','英德市','','','000190001600008',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2420,'441882','连州市','','','000190001600009',250,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2421,'445101','潮州市辖区','','','000190001900001',253,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2422,'445102','湘桥区','','','000190001900002',253,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2423,'445103','潮安区','','','000190001900003',253,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2424,'445122','饶平县','','','000190001900004',253,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2425,'445201','揭阳市辖区','','','000190002000001',254,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2426,'445202','榕城区','','','000190002000002',254,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2427,'445203','揭东区','','','000190002000003',254,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2428,'445222','揭西县','','','000190002000004',254,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2429,'445224','惠来县','','','000190002000005',254,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2430,'445281','普宁市','','','000190002000006',254,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2431,'445301','云浮市辖区','','','000190002100001',255,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2432,'445302','云城区','','','000190002100002',255,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2433,'445321','新兴县','','','000190002100003',255,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2434,'445322','郁南县','','','000190002100004',255,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2435,'445323','云安县','','','000190002100005',255,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2436,'445381','罗定市','','','000190002100006',255,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2437,'450101','南宁市辖区','','','000200000100001',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2438,'450102','兴宁区','','','000200000100002',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2439,'450103','青秀区','','','000200000100003',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2440,'450105','江南区','','','000200000100004',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2441,'450107','西乡塘区','','','000200000100005',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2442,'450108','良庆区','','','000200000100006',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2443,'450109','邕宁区','','','000200000100007',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2444,'450122','武鸣县','','','000200000100008',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2445,'450123','隆安县','','','000200000100009',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2446,'450124','马山县','','','000200000100010',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2447,'450125','上林县','','','000200000100011',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2448,'450126','宾阳县','','','000200000100012',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2449,'450127','横县','','','000200000100013',256,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2450,'450201','柳州市辖区','','','000200000200001',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2451,'450202','城中区','','','000200000200002',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2452,'450203','鱼峰区','','','000200000200003',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2453,'450204','柳南区','','','000200000200004',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2454,'450205','柳北区','','','000200000200005',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2455,'450221','柳江县','','','000200000200006',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2456,'450222','柳城县','','','000200000200007',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2457,'450223','鹿寨县','','','000200000200008',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2458,'450224','融安县','','','000200000200009',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2459,'450225','融水苗族自治县','','','000200000200010',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2460,'450226','三江侗族自治县','','','000200000200011',257,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2461,'450301','桂林市辖区','','','000200000300001',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2462,'450302','秀峰区','','','000200000300002',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2463,'450303','叠彩区','','','000200000300003',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2464,'450304','象山区','','','000200000300004',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2465,'450305','七星区','','','000200000300005',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2466,'450311','雁山区','','','000200000300006',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2467,'450312','临桂区','','','000200000300007',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2468,'450321','阳朔县','','','000200000300008',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2469,'450323','灵川县','','','000200000300009',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2470,'450324','全州县','','','000200000300010',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2471,'450325','兴安县','','','000200000300011',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2472,'450326','永福县','','','000200000300012',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2473,'450327','灌阳县','','','000200000300013',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2474,'450328','龙胜各族自治县','','','000200000300014',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2475,'450329','资源县','','','000200000300015',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2476,'450330','平乐县','','','000200000300016',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2477,'450331','荔浦县','','','000200000300017',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2478,'450332','恭城瑶族自治县','','','000200000300018',258,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2479,'450401','梧州市辖区','','','000200000400001',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2480,'450403','万秀区','','','000200000400002',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2481,'450405','长洲区','','','000200000400003',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2482,'450406','龙圩区','','','000200000400004',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2483,'450421','苍梧县','','','000200000400005',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2484,'450422','藤县','','','000200000400006',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2485,'450423','蒙山县','','','000200000400007',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2486,'450481','岑溪市','','','000200000400008',259,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2487,'450501','北海市辖区','','','000200000500001',260,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2488,'450502','海城区','','','000200000500002',260,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2489,'450503','银海区','','','000200000500003',260,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2490,'450512','铁山港区','','','000200000500004',260,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2491,'450521','合浦县','','','000200000500005',260,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2492,'450601','防城港市辖区','','','000200000600001',261,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2493,'450602','港口区','','','000200000600002',261,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2494,'450603','防城区','','','000200000600003',261,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2495,'450621','上思县','','','000200000600004',261,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2496,'450681','东兴市','','','000200000600005',261,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2497,'450701','钦州市辖区','','','000200000700001',262,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2498,'450702','钦南区','','','000200000700002',262,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2499,'450703','钦北区','','','000200000700003',262,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2500,'450721','灵山县','','','000200000700004',262,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2501,'450722','浦北县','','','000200000700005',262,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2502,'450801','贵港市辖区','','','000200000800001',263,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2503,'450802','港北区','','','000200000800002',263,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2504,'450803','港南区','','','000200000800003',263,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2505,'450804','覃塘区','','','000200000800004',263,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2506,'450821','平南县','','','000200000800005',263,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2507,'450881','桂平市','','','000200000800006',263,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2508,'450901','玉林市辖区','','','000200000900001',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2509,'450902','玉州区','','','000200000900002',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2510,'450903','福绵区','','','000200000900003',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2511,'450921','容县','','','000200000900004',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2512,'450922','陆川县','','','000200000900005',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2513,'450923','博白县','','','000200000900006',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2514,'450924','兴业县','','','000200000900007',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2515,'450981','北流市','','','000200000900008',264,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2516,'451001','百色市辖区','','','000200001000001',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2517,'451002','右江区','','','000200001000002',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2518,'451021','田阳县','','','000200001000003',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2519,'451022','田东县','','','000200001000004',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2520,'451023','平果县','','','000200001000005',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2521,'451024','德保县','','','000200001000006',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2522,'451025','靖西县','','','000200001000007',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2523,'451026','那坡县','','','000200001000008',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2524,'451027','凌云县','','','000200001000009',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2525,'451028','乐业县','','','000200001000010',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2526,'451029','田林县','','','000200001000011',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2527,'451030','西林县','','','000200001000012',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2528,'451031','隆林各族自治县','','','000200001000013',265,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2529,'451101','贺州市辖区','','','000200001100001',266,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2530,'451102','八步区','','','000200001100002',266,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2531,'451121','昭平县','','','000200001100003',266,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2532,'451122','钟山县','','','000200001100004',266,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2533,'451123','富川瑶族自治县','','','000200001100005',266,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2534,'451201','河池市辖区','','','000200001200001',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2535,'451202','金城江区','','','000200001200002',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2536,'451221','南丹县','','','000200001200003',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2537,'451222','天峨县','','','000200001200004',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2538,'451223','凤山县','','','000200001200005',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2539,'451224','东兰县','','','000200001200006',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2540,'451225','罗城仫佬族自治县','','','000200001200007',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2541,'451226','环江毛南族自治县','','','000200001200008',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2542,'451227','巴马瑶族自治县','','','000200001200009',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2543,'451228','都安瑶族自治县','','','000200001200010',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2544,'451229','大化瑶族自治县','','','000200001200011',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2545,'451281','宜州市','','','000200001200012',267,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2546,'451301','来宾市辖区','','','000200001300001',268,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2547,'451302','兴宾区','','','000200001300002',268,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2548,'451321','忻城县','','','000200001300003',268,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2549,'451322','象州县','','','000200001300004',268,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2550,'451323','武宣县','','','000200001300005',268,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2551,'451324','金秀瑶族自治县','','','000200001300006',268,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2552,'451381','合山市','','','000200001300007',268,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2553,'451401','崇左市辖区','','','000200001400001',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2554,'451402','江州区','','','000200001400002',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2555,'451421','扶绥县','','','000200001400003',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2556,'451422','宁明县','','','000200001400004',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2557,'451423','龙州县','','','000200001400005',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2558,'451424','大新县','','','000200001400006',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2559,'451425','天等县','','','000200001400007',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2560,'451481','凭祥市','','','000200001400008',269,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2561,'460101','海口市辖区','','','000210000100001',270,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2562,'460105','秀英区','','','000210000100002',270,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2563,'460106','龙华区','','','000210000100003',270,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2564,'460107','琼山区','','','000210000100004',270,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2565,'460108','美兰区','','','000210000100005',270,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2566,'460201','三亚市辖区','','','000210000200001',271,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2567,'460321','西沙群岛','','','000210000300001',272,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2568,'460322','南沙群岛','','','000210000300002',272,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2569,'460323','中沙群岛的岛礁及其海域','','','000210000300003',272,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2570,'469001','五指山市','','','000210000400001',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2571,'469002','琼海市','','','000210000400002',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2572,'469003','儋州市','','','000210000400003',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2573,'469005','文昌市','','','000210000400004',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2574,'469006','万宁市','','','000210000400005',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2575,'469007','东方市','','','000210000400006',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2576,'469021','定安县','','','000210000400007',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2577,'469022','屯昌县','','','000210000400008',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2578,'469023','澄迈县','','','000210000400009',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2579,'469024','临高县','','','000210000400010',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2580,'469025','白沙黎族自治县','','','000210000400011',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2581,'469026','昌江黎族自治县','','','000210000400012',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2582,'469027','乐东黎族自治县','','','000210000400013',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2583,'469028','陵水黎族自治县','','','000210000400014',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2584,'469029','保亭黎族苗族自治县','','','000210000400015',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2585,'469030','琼中黎族苗族自治县','','','000210000400016',273,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2586,'500101','万州区','','','000220000100001',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2587,'500102','涪陵区','','','000220000100002',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2588,'500103','渝中区','','','000220000100003',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2589,'500104','大渡口区','','','000220000100004',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2590,'500105','江北区','','','000220000100005',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2591,'500106','沙坪坝区','','','000220000100006',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2592,'500107','九龙坡区','','','000220000100007',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2593,'500108','南岸区','','','000220000100008',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2594,'500109','北碚区','','','000220000100009',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2595,'500110','綦江区','','','000220000100010',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2596,'500111','大足区','','','000220000100011',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2597,'500112','渝北区','','','000220000100012',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2598,'500113','巴南区','','','000220000100013',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2599,'500114','黔江区','','','000220000100014',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2600,'500115','长寿区','','','000220000100015',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2601,'500116','江津区','','','000220000100016',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2602,'500117','合川区','','','000220000100017',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2603,'500118','永川区','','','000220000100018',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2604,'500119','南川区','','','000220000100019',274,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2605,'500223','潼南县','','','000220000200001',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2606,'500224','铜梁县','','','000220000200002',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2607,'500226','荣昌县','','','000220000200003',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2608,'500227','璧山县','','','000220000200004',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2609,'500228','梁平县','','','000220000200005',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2610,'500229','城口县','','','000220000200006',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2611,'500230','丰都县','','','000220000200007',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2612,'500231','垫江县','','','000220000200008',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2613,'500232','武隆县','','','000220000200009',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2614,'500233','忠县','','','000220000200010',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2615,'500234','开县','','','000220000200011',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2616,'500235','云阳县','','','000220000200012',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2617,'500236','奉节县','','','000220000200013',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2618,'500237','巫山县','','','000220000200014',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2619,'500238','巫溪县','','','000220000200015',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2620,'500240','石柱土家族自治县','','','000220000200016',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2621,'500241','秀山土家族苗族自治县','','','000220000200017',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2622,'500242','酉阳土家族苗族自治县','','','000220000200018',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2623,'500243','彭水苗族土家族自治县','','','000220000200019',275,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2624,'510101','成都市辖区','','','000230000100001',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2625,'510104','锦江区','','','000230000100002',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2626,'510105','青羊区','','','000230000100003',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2627,'510106','金牛区','','','000230000100004',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2628,'510107','武侯区','','','000230000100005',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2629,'510108','成华区','','','000230000100006',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2630,'510112','龙泉驿区','','','000230000100007',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2631,'510113','青白江区','','','000230000100008',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2632,'510114','新都区','','','000230000100009',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2633,'510115','温江区','','','000230000100010',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2634,'510121','金堂县','','','000230000100011',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2635,'510122','双流县','','','000230000100012',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2636,'510124','郫县','','','000230000100013',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2637,'510129','大邑县','','','000230000100014',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2638,'510131','蒲江县','','','000230000100015',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2639,'510132','新津县','','','000230000100016',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2640,'510181','都江堰市','','','000230000100017',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2641,'510182','彭州市','','','000230000100018',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2642,'510183','邛崃市','','','000230000100019',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2643,'510184','崇州市','','','000230000100020',276,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2644,'510301','自贡市辖区','','','000230000200001',277,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2645,'510302','自流井区','','','000230000200002',277,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2646,'510303','贡井区','','','000230000200003',277,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2647,'510304','大安区','','','000230000200004',277,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2648,'510311','沿滩区','','','000230000200005',277,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2649,'510321','荣县','','','000230000200006',277,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2650,'510322','富顺县','','','000230000200007',277,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2651,'510401','攀枝花市辖区','','','000230000300001',278,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2652,'510402','东区','','','000230000300002',278,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2653,'510403','西区','','','000230000300003',278,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2654,'510411','仁和区','','','000230000300004',278,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2655,'510421','米易县','','','000230000300005',278,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2656,'510422','盐边县','','','000230000300006',278,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2657,'510501','泸州市辖区','','','000230000400001',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2658,'510502','江阳区','','','000230000400002',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2659,'510503','纳溪区','','','000230000400003',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2660,'510504','龙马潭区','','','000230000400004',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2661,'510521','泸县','','','000230000400005',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2662,'510522','合江县','','','000230000400006',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2663,'510524','叙永县','','','000230000400007',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2664,'510525','古蔺县','','','000230000400008',279,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2665,'510601','德阳市辖区','','','000230000500001',280,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2666,'510603','旌阳区','','','000230000500002',280,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2667,'510623','中江县','','','000230000500003',280,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2668,'510626','罗江县','','','000230000500004',280,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2669,'510681','广汉市','','','000230000500005',280,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2670,'510682','什邡市','','','000230000500006',280,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2671,'510683','绵竹市','','','000230000500007',280,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2672,'510701','绵阳市辖区','','','000230000600001',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2673,'510703','涪城区','','','000230000600002',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2674,'510704','游仙区','','','000230000600003',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2675,'510722','三台县','','','000230000600004',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2676,'510723','盐亭县','','','000230000600005',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2677,'510724','安县','','','000230000600006',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2678,'510725','梓潼县','','','000230000600007',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2679,'510726','北川羌族自治县','','','000230000600008',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2680,'510727','平武县','','','000230000600009',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2681,'510781','江油市','','','000230000600010',281,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2682,'510801','广元市辖区','','','000230000700001',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2683,'510802','利州区','','','000230000700002',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2684,'510811','元坝区','','','000230000700003',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2685,'510812','朝天区','','','000230000700004',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2686,'510821','旺苍县','','','000230000700005',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2687,'510822','青川县','','','000230000700006',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2688,'510823','剑阁县','','','000230000700007',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2689,'510824','苍溪县','','','000230000700008',282,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2690,'510901','遂宁市辖区','','','000230000800001',283,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2691,'510903','船山区','','','000230000800002',283,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2692,'510904','安居区','','','000230000800003',283,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2693,'510921','蓬溪县','','','000230000800004',283,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2694,'510922','射洪县','','','000230000800005',283,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2695,'510923','大英县','','','000230000800006',283,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2696,'511001','内江市辖区','','','000230000900001',284,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2697,'511002','市中区','','','000230000900002',284,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2698,'511011','东兴区','','','000230000900003',284,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2699,'511024','威远县','','','000230000900004',284,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2700,'511025','资中县','','','000230000900005',284,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2701,'511028','隆昌县','','','000230000900006',284,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2702,'511101','乐山市辖区','','','000230001000001',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2703,'511102','市中区','','','000230001000002',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2704,'511111','沙湾区','','','000230001000003',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2705,'511112','五通桥区','','','000230001000004',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2706,'511113','金口河区','','','000230001000005',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2707,'511123','犍为县','','','000230001000006',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2708,'511124','井研县','','','000230001000007',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2709,'511126','夹江县','','','000230001000008',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2710,'511129','沐川县','','','000230001000009',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2711,'511132','峨边彝族自治县','','','000230001000010',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2712,'511133','马边彝族自治县','','','000230001000011',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2713,'511181','峨眉山市','','','000230001000012',285,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2714,'511301','南充市辖区','','','000230001100001',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2715,'511302','顺庆区','','','000230001100002',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2716,'511303','高坪区','','','000230001100003',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2717,'511304','嘉陵区','','','000230001100004',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2718,'511321','南部县','','','000230001100005',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2719,'511322','营山县','','','000230001100006',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2720,'511323','蓬安县','','','000230001100007',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2721,'511324','仪陇县','','','000230001100008',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2722,'511325','西充县','','','000230001100009',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2723,'511381','阆中市','','','000230001100010',286,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2724,'511401','眉山市辖区','','','000230001200001',287,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2725,'511402','东坡区','','','000230001200002',287,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2726,'511421','仁寿县','','','000230001200003',287,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2727,'511422','彭山县','','','000230001200004',287,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2728,'511423','洪雅县','','','000230001200005',287,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2729,'511424','丹棱县','','','000230001200006',287,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2730,'511425','青神县','','','000230001200007',287,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2731,'511501','宜宾市辖区','','','000230001300001',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2732,'511502','翠屏区','','','000230001300002',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2733,'511503','南溪区','','','000230001300003',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2734,'511521','宜宾县','','','000230001300004',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2735,'511523','江安县','','','000230001300005',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2736,'511524','长宁县','','','000230001300006',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2737,'511525','高县','','','000230001300007',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2738,'511526','珙县','','','000230001300008',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2739,'511527','筠连县','','','000230001300009',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2740,'511528','兴文县','','','000230001300010',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2741,'511529','屏山县','','','000230001300011',288,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2742,'511601','广安市辖区','','','000230001400001',289,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2743,'511602','广安区','','','000230001400002',289,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2744,'511603','前锋区','','','000230001400003',289,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2745,'511621','岳池县','','','000230001400004',289,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2746,'511622','武胜县','','','000230001400005',289,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2747,'511623','邻水县','','','000230001400006',289,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2748,'511681','华蓥市','','','000230001400007',289,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2749,'511701','达州市辖区','','','000230001500001',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2750,'511702','通川区','','','000230001500002',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2751,'511703','达川区','','','000230001500003',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2752,'511722','宣汉县','','','000230001500004',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2753,'511723','开江县','','','000230001500005',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2754,'511724','大竹县','','','000230001500006',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2755,'511725','渠县','','','000230001500007',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2756,'511781','万源市','','','000230001500008',290,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2757,'511801','雅安市辖区','','','000230001600001',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2758,'511802','雨城区','','','000230001600002',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2759,'511803','名山区','','','000230001600003',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2760,'511822','荥经县','','','000230001600004',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2761,'511823','汉源县','','','000230001600005',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2762,'511824','石棉县','','','000230001600006',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2763,'511825','天全县','','','000230001600007',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2764,'511826','芦山县','','','000230001600008',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2765,'511827','宝兴县','','','000230001600009',291,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2766,'511901','巴中市辖区','','','000230001700001',292,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2767,'511902','巴州区','','','000230001700002',292,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2768,'511903','恩阳区','','','000230001700003',292,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2769,'511921','通江县','','','000230001700004',292,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2770,'511922','南江县','','','000230001700005',292,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2771,'511923','平昌县','','','000230001700006',292,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2772,'512001','资阳市辖区','','','000230001800001',293,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2773,'512002','雁江区','','','000230001800002',293,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2774,'512021','安岳县','','','000230001800003',293,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2775,'512022','乐至县','','','000230001800004',293,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2776,'512081','简阳市','','','000230001800005',293,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2777,'513221','汶川县','','','000230001900001',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2778,'513222','理县','','','000230001900002',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2779,'513223','茂县','','','000230001900003',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2780,'513224','松潘县','','','000230001900004',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2781,'513225','九寨沟县','','','000230001900005',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2782,'513226','金川县','','','000230001900006',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2783,'513227','小金县','','','000230001900007',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2784,'513228','黑水县','','','000230001900008',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2785,'513229','马尔康县','','','000230001900009',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2786,'513230','壤塘县','','','000230001900010',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2787,'513231','阿坝县','','','000230001900011',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2788,'513232','若尔盖县','','','000230001900012',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2789,'513233','红原县','','','000230001900013',294,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2790,'513321','康定县','','','000230002000001',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2791,'513322','泸定县','','','000230002000002',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2792,'513323','丹巴县','','','000230002000003',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2793,'513324','九龙县','','','000230002000004',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2794,'513325','雅江县','','','000230002000005',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2795,'513326','道孚县','','','000230002000006',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2796,'513327','炉霍县','','','000230002000007',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2797,'513328','甘孜县','','','000230002000008',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2798,'513329','新龙县','','','000230002000009',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2799,'513330','德格县','','','000230002000010',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2800,'513331','白玉县','','','000230002000011',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2801,'513332','石渠县','','','000230002000012',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2802,'513333','色达县','','','000230002000013',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2803,'513334','理塘县','','','000230002000014',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2804,'513335','巴塘县','','','000230002000015',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2805,'513336','乡城县','','','000230002000016',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2806,'513337','稻城县','','','000230002000017',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2807,'513338','得荣县','','','000230002000018',295,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2808,'513401','西昌市','','','000230002100001',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2809,'513422','木里藏族自治县','','','000230002100002',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2810,'513423','盐源县','','','000230002100003',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2811,'513424','德昌县','','','000230002100004',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2812,'513425','会理县','','','000230002100005',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2813,'513426','会东县','','','000230002100006',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2814,'513427','宁南县','','','000230002100007',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2815,'513428','普格县','','','000230002100008',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2816,'513429','布拖县','','','000230002100009',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2817,'513430','金阳县','','','000230002100010',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2818,'513431','昭觉县','','','000230002100011',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2819,'513432','喜德县','','','000230002100012',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2820,'513433','冕宁县','','','000230002100013',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2821,'513434','越西县','','','000230002100014',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2822,'513435','甘洛县','','','000230002100015',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2823,'513436','美姑县','','','000230002100016',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2824,'513437','雷波县','','','000230002100017',296,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2825,'520101','贵阳市辖区','','','000240000100001',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2826,'520102','南明区','','','000240000100002',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2827,'520103','云岩区','','','000240000100003',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2828,'520111','花溪区','','','000240000100004',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2829,'520112','乌当区','','','000240000100005',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2830,'520113','白云区','','','000240000100006',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2831,'520115','观山湖区','','','000240000100007',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2832,'520121','开阳县','','','000240000100008',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2833,'520122','息烽县','','','000240000100009',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2834,'520123','修文县','','','000240000100010',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2835,'520181','清镇市','','','000240000100011',297,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2836,'520201','钟山区','','','000240000200001',298,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2837,'520203','六枝特区','','','000240000200002',298,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2838,'520221','水城县','','','000240000200003',298,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2839,'520222','盘县','','','000240000200004',298,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2840,'520301','遵义市辖区','','','000240000300001',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2841,'520302','红花岗区','','','000240000300002',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2842,'520303','汇川区','','','000240000300003',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2843,'520321','遵义县','','','000240000300004',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2844,'520322','桐梓县','','','000240000300005',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2845,'520323','绥阳县','','','000240000300006',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2846,'520324','正安县','','','000240000300007',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2847,'520325','道真仡佬族苗族自治县','','','000240000300008',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2848,'520326','务川仡佬族苗族自治县','','','000240000300009',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2849,'520327','凤冈县','','','000240000300010',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2850,'520328','湄潭县','','','000240000300011',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2851,'520329','余庆县','','','000240000300012',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2852,'520330','习水县','','','000240000300013',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2853,'520381','赤水市','','','000240000300014',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2854,'520382','仁怀市','','','000240000300015',299,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2855,'520401','安顺市辖区','','','000240000400001',300,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2856,'520402','西秀区','','','000240000400002',300,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2857,'520421','平坝县','','','000240000400003',300,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2858,'520422','普定县','','','000240000400004',300,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2859,'520423','镇宁布依族苗族自治县','','','000240000400005',300,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2860,'520424','关岭布依族苗族自治县','','','000240000400006',300,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2861,'520425','紫云苗族布依族自治县','','','000240000400007',300,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2862,'520501','毕节市辖区','','','000240000500001',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2863,'520502','七星关区','','','000240000500002',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2864,'520521','大方县','','','000240000500003',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2865,'520522','黔西县','','','000240000500004',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2866,'520523','金沙县','','','000240000500005',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2867,'520524','织金县','','','000240000500006',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2868,'520525','纳雍县','','','000240000500007',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2869,'520526','威宁彝族回族苗族自治县','','','000240000500008',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2870,'520527','赫章县','','','000240000500009',301,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2871,'520601','铜仁市辖区','','','000240000600001',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2872,'520602','碧江区','','','000240000600002',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2873,'520603','万山区','','','000240000600003',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2874,'520621','江口县','','','000240000600004',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2875,'520622','玉屏侗族自治县','','','000240000600005',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2876,'520623','石阡县','','','000240000600006',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2877,'520624','思南县','','','000240000600007',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2878,'520625','印江土家族苗族自治县','','','000240000600008',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2879,'520626','德江县','','','000240000600009',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2880,'520627','沿河土家族自治县','','','000240000600010',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2881,'520628','松桃苗族自治县','','','000240000600011',302,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2882,'522301','兴义市','','','000240000700001',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2883,'522322','兴仁县','','','000240000700002',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2884,'522323','普安县','','','000240000700003',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2885,'522324','晴隆县','','','000240000700004',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2886,'522325','贞丰县','','','000240000700005',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2887,'522326','望谟县','','','000240000700006',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2888,'522327','册亨县','','','000240000700007',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2889,'522328','安龙县','','','000240000700008',303,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2890,'522601','凯里市','','','000240000800001',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2891,'522622','黄平县','','','000240000800002',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2892,'522623','施秉县','','','000240000800003',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2893,'522624','三穗县','','','000240000800004',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2894,'522625','镇远县','','','000240000800005',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2895,'522626','岑巩县','','','000240000800006',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2896,'522627','天柱县','','','000240000800007',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2897,'522628','锦屏县','','','000240000800008',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2898,'522629','剑河县','','','000240000800009',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2899,'522630','台江县','','','000240000800010',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2900,'522631','黎平县','','','000240000800011',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2901,'522632','榕江县','','','000240000800012',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2902,'522633','从江县','','','000240000800013',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2903,'522634','雷山县','','','000240000800014',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2904,'522635','麻江县','','','000240000800015',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2905,'522636','丹寨县','','','000240000800016',304,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2906,'522701','都匀市','','','000240000900001',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2907,'522702','福泉市','','','000240000900002',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2908,'522722','荔波县','','','000240000900003',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2909,'522723','贵定县','','','000240000900004',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2910,'522725','瓮安县','','','000240000900005',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2911,'522726','独山县','','','000240000900006',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2912,'522727','平塘县','','','000240000900007',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2913,'522728','罗甸县','','','000240000900008',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2914,'522729','长顺县','','','000240000900009',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2915,'522730','龙里县','','','000240000900010',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2916,'522731','惠水县','','','000240000900011',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2917,'522732','三都水族自治县','','','000240000900012',305,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2918,'530101','昆明市辖区','','','000250000100001',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2919,'530102','五华区','','','000250000100002',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2920,'530103','盘龙区','','','000250000100003',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2921,'530111','官渡区','','','000250000100004',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2922,'530112','西山区','','','000250000100005',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2923,'530113','东川区','','','000250000100006',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2924,'530114','呈贡区','','','000250000100007',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2925,'530122','晋宁县','','','000250000100008',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2926,'530124','富民县','','','000250000100009',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2927,'530125','宜良县','','','000250000100010',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2928,'530126','石林彝族自治县','','','000250000100011',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2929,'530127','嵩明县','','','000250000100012',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2930,'530128','禄劝彝族苗族自治县','','','000250000100013',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2931,'530129','寻甸回族彝族自治县','','','000250000100014',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2932,'530181','安宁市','','','000250000100015',306,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2933,'530301','曲靖市辖区','','','000250000200001',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2934,'530302','麒麟区','','','000250000200002',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2935,'530321','马龙县','','','000250000200003',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2936,'530322','陆良县','','','000250000200004',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2937,'530323','师宗县','','','000250000200005',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2938,'530324','罗平县','','','000250000200006',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2939,'530325','富源县','','','000250000200007',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2940,'530326','会泽县','','','000250000200008',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2941,'530328','沾益县','','','000250000200009',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2942,'530381','宣威市','','','000250000200010',307,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2943,'530401','玉溪市辖区','','','000250000300001',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2944,'530402','红塔区','','','000250000300002',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2945,'530421','江川县','','','000250000300003',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2946,'530422','澄江县','','','000250000300004',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2947,'530423','通海县','','','000250000300005',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2948,'530424','华宁县','','','000250000300006',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2949,'530425','易门县','','','000250000300007',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2950,'530426','峨山彝族自治县','','','000250000300008',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2951,'530427','新平彝族傣族自治县','','','000250000300009',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2952,'530428','元江哈尼族彝族傣族自治县','','','000250000300010',308,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2953,'530501','保山市辖区','','','000250000400001',309,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2954,'530502','隆阳区','','','000250000400002',309,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2955,'530521','施甸县','','','000250000400003',309,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2956,'530522','腾冲县','','','000250000400004',309,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2957,'530523','龙陵县','','','000250000400005',309,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2958,'530524','昌宁县','','','000250000400006',309,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2959,'530601','昭通市辖区','','','000250000500001',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2960,'530602','昭阳区','','','000250000500002',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2961,'530621','鲁甸县','','','000250000500003',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2962,'530622','巧家县','','','000250000500004',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2963,'530623','盐津县','','','000250000500005',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2964,'530624','大关县','','','000250000500006',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2965,'530625','永善县','','','000250000500007',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2966,'530626','绥江县','','','000250000500008',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2967,'530627','镇雄县','','','000250000500009',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2968,'530628','彝良县','','','000250000500010',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2969,'530629','威信县','','','000250000500011',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2970,'530630','水富县','','','000250000500012',310,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2971,'530701','丽江市辖区','','','000250000600001',311,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2972,'530702','古城区','','','000250000600002',311,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2973,'530721','玉龙纳西族自治县','','','000250000600003',311,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2974,'530722','永胜县','','','000250000600004',311,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2975,'530723','华坪县','','','000250000600005',311,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2976,'530724','宁蒗彝族自治县','','','000250000600006',311,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2977,'530801','普洱市辖区','','','000250000700001',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2978,'530802','思茅区','','','000250000700002',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2979,'530821','宁洱哈尼族彝族自治县','','','000250000700003',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2980,'530822','墨江哈尼族自治县','','','000250000700004',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2981,'530823','景东彝族自治县','','','000250000700005',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2982,'530824','景谷傣族彝族自治县','','','000250000700006',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2983,'530825','镇沅彝族哈尼族拉祜族自治县','','','000250000700007',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2984,'530826','江城哈尼族彝族自治县','','','000250000700008',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2985,'530827','孟连傣族拉祜族佤族自治县','','','000250000700009',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2986,'530828','澜沧拉祜族自治县','','','000250000700010',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2987,'530829','西盟佤族自治县','','','000250000700011',312,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2988,'530901','临沧市辖区','','','000250000800001',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2989,'530902','临翔区','','','000250000800002',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2990,'530921','凤庆县','','','000250000800003',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2991,'530922','云县','','','000250000800004',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2992,'530923','永德县','','','000250000800005',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2993,'530924','镇康县','','','000250000800006',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2994,'530925','双江拉祜族佤族布朗族傣族自治县','','','000250000800007',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2995,'530926','耿马傣族佤族自治县','','','000250000800008',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2996,'530927','沧源佤族自治县','','','000250000800009',313,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2997,'532301','楚雄市','','','000250000900001',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2998,'532322','双柏县','','','000250000900002',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (2999,'532323','牟定县','','','000250000900003',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3000,'532324','南华县','','','000250000900004',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3001,'532325','姚安县','','','000250000900005',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3002,'532326','大姚县','','','000250000900006',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3003,'532327','永仁县','','','000250000900007',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3004,'532328','元谋县','','','000250000900008',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3005,'532329','武定县','','','000250000900009',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3006,'532331','禄丰县','','','000250000900010',314,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3007,'532501','个旧市','','','000250001000001',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3008,'532502','开远市','','','000250001000002',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3009,'532503','蒙自市','','','000250001000003',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3010,'532504','弥勒市','','','000250001000004',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3011,'532523','屏边苗族自治县','','','000250001000005',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3012,'532524','建水县','','','000250001000006',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3013,'532525','石屏县','','','000250001000007',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3014,'532527','泸西县','','','000250001000008',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3015,'532528','元阳县','','','000250001000009',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3016,'532529','红河县','','','000250001000010',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3017,'532530','金平苗族瑶族傣族自治县','','','000250001000011',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3018,'532531','绿春县','','','000250001000012',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3019,'532532','河口瑶族自治县','','','000250001000013',315,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3020,'532601','文山市','','','000250001100001',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3021,'532622','砚山县','','','000250001100002',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3022,'532623','西畴县','','','000250001100003',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3023,'532624','麻栗坡县','','','000250001100004',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3024,'532625','马关县','','','000250001100005',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3025,'532626','丘北县','','','000250001100006',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3026,'532627','广南县','','','000250001100007',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3027,'532628','富宁县','','','000250001100008',316,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3028,'532801','景洪市','','','000250001200001',317,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3029,'532822','勐海县','','','000250001200002',317,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3030,'532823','勐腊县','','','000250001200003',317,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3031,'532901','大理市','','','000250001300001',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3032,'532922','漾濞彝族自治县','','','000250001300002',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3033,'532923','祥云县','','','000250001300003',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3034,'532924','宾川县','','','000250001300004',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3035,'532925','弥渡县','','','000250001300005',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3036,'532926','南涧彝族自治县','','','000250001300006',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3037,'532927','巍山彝族回族自治县','','','000250001300007',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3038,'532928','永平县','','','000250001300008',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3039,'532929','云龙县','','','000250001300009',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3040,'532930','洱源县','','','000250001300010',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3041,'532931','剑川县','','','000250001300011',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3042,'532932','鹤庆县','','','000250001300012',318,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3043,'533102','瑞丽市','','','000250001400001',319,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3044,'533103','芒市','','','000250001400002',319,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3045,'533122','梁河县','','','000250001400003',319,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3046,'533123','盈江县','','','000250001400004',319,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3047,'533124','陇川县','','','000250001400005',319,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3048,'533321','泸水县','','','000250001500001',320,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3049,'533323','福贡县','','','000250001500002',320,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3050,'533324','贡山独龙族怒族自治县','','','000250001500003',320,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3051,'533325','兰坪白族普米族自治县','','','000250001500004',320,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3052,'533421','香格里拉县','','','000250001600001',321,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3053,'533422','德钦县','','','000250001600002',321,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3054,'533423','维西傈僳族自治县','','','000250001600003',321,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3055,'540101','拉萨市辖区','','','000260000100001',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3056,'540102','城关区','','','000260000100002',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3057,'540121','林周县','','','000260000100003',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3058,'540122','当雄县','','','000260000100004',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3059,'540123','尼木县','','','000260000100005',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3060,'540124','曲水县','','','000260000100006',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3061,'540125','堆龙德庆县','','','000260000100007',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3062,'540126','达孜县','','','000260000100008',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3063,'540127','墨竹工卡县','','','000260000100009',322,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3064,'542121','昌都县','','','000260000200001',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3065,'542122','江达县','','','000260000200002',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3066,'542123','贡觉县','','','000260000200003',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3067,'542124','类乌齐县','','','000260000200004',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3068,'542125','丁青县','','','000260000200005',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3069,'542126','察雅县','','','000260000200006',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3070,'542127','八宿县','','','000260000200007',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3071,'542128','左贡县','','','000260000200008',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3072,'542129','芒康县','','','000260000200009',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3073,'542132','洛隆县','','','000260000200010',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3074,'542133','边坝县','','','000260000200011',323,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3075,'542221','乃东县','','','000260000300001',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3076,'542222','扎囊县','','','000260000300002',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3077,'542223','贡嘎县','','','000260000300003',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3078,'542224','桑日县','','','000260000300004',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3079,'542225','琼结县','','','000260000300005',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3080,'542226','曲松县','','','000260000300006',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3081,'542227','措美县','','','000260000300007',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3082,'542228','洛扎县','','','000260000300008',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3083,'542229','加查县','','','000260000300009',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3084,'542231','隆子县','','','000260000300010',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3085,'542232','错那县','','','000260000300011',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3086,'542233','浪卡子县','','','000260000300012',324,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3087,'542301','日喀则市','','','000260000400001',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3088,'542322','南木林县','','','000260000400002',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3089,'542323','江孜县','','','000260000400003',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3090,'542324','定日县','','','000260000400004',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3091,'542325','萨迦县','','','000260000400005',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3092,'542326','拉孜县','','','000260000400006',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3093,'542327','昂仁县','','','000260000400007',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3094,'542328','谢通门县','','','000260000400008',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3095,'542329','白朗县','','','000260000400009',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3096,'542330','仁布县','','','000260000400010',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3097,'542331','康马县','','','000260000400011',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3098,'542332','定结县','','','000260000400012',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3099,'542333','仲巴县','','','000260000400013',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3100,'542334','亚东县','','','000260000400014',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3101,'542335','吉隆县','','','000260000400015',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3102,'542336','聂拉木县','','','000260000400016',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3103,'542337','萨嘎县','','','000260000400017',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3104,'542338','岗巴县','','','000260000400018',325,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3105,'542421','那曲县','','','000260000500001',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3106,'542422','嘉黎县','','','000260000500002',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3107,'542423','比如县','','','000260000500003',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3108,'542424','聂荣县','','','000260000500004',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3109,'542425','安多县','','','000260000500005',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3110,'542426','申扎县','','','000260000500006',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3111,'542427','索县','','','000260000500007',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3112,'542428','班戈县','','','000260000500008',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3113,'542429','巴青县','','','000260000500009',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3114,'542430','尼玛县','','','000260000500010',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3115,'542431','双湖县','','','000260000500011',326,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3116,'542521','普兰县','','','000260000600001',327,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3117,'542522','札达县','','','000260000600002',327,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3118,'542523','噶尔县','','','000260000600003',327,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3119,'542524','日土县','','','000260000600004',327,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3120,'542525','革吉县','','','000260000600005',327,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3121,'542526','改则县','','','000260000600006',327,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3122,'542527','措勤县','','','000260000600007',327,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3123,'542621','林芝县','','','000260000700001',328,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3124,'542622','工布江达县','','','000260000700002',328,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3125,'542623','米林县','','','000260000700003',328,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3126,'542624','墨脱县','','','000260000700004',328,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3127,'542625','波密县','','','000260000700005',328,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3128,'542626','察隅县','','','000260000700006',328,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3129,'542627','朗县','','','000260000700007',328,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3130,'610101','西安市辖区','','','000270000100001',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3131,'610102','新城区','','','000270000100002',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3132,'610103','碑林区','','','000270000100003',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3133,'610104','莲湖区','','','000270000100004',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3134,'610111','灞桥区','','','000270000100005',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3135,'610112','未央区','','','000270000100006',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3136,'610113','雁塔区','','','000270000100007',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3137,'610114','阎良区','','','000270000100008',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3138,'610115','临潼区','','','000270000100009',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3139,'610116','长安区','','','000270000100010',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3140,'610122','蓝田县','','','000270000100011',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3141,'610124','周至县','','','000270000100012',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3142,'610125','户县','','','000270000100013',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3143,'610126','高陵县','','','000270000100014',329,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3144,'610201','铜川市辖区','','','000270000200001',330,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3145,'610202','王益区','','','000270000200002',330,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3146,'610203','印台区','','','000270000200003',330,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3147,'610204','耀州区','','','000270000200004',330,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3148,'610222','宜君县','','','000270000200005',330,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3149,'610301','宝鸡市辖区','','','000270000300001',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3150,'610302','渭滨区','','','000270000300002',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3151,'610303','金台区','','','000270000300003',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3152,'610304','陈仓区','','','000270000300004',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3153,'610322','凤翔县','','','000270000300005',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3154,'610323','岐山县','','','000270000300006',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3155,'610324','扶风县','','','000270000300007',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3156,'610326','眉县','','','000270000300008',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3157,'610327','陇县','','','000270000300009',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3158,'610328','千阳县','','','000270000300010',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3159,'610329','麟游县','','','000270000300011',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3160,'610330','凤县','','','000270000300012',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3161,'610331','太白县','','','000270000300013',331,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3162,'610401','咸阳市辖区','','','000270000400001',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3163,'610402','秦都区','','','000270000400002',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3164,'610403','杨陵区','','','000270000400003',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3165,'610404','渭城区','','','000270000400004',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3166,'610422','三原县','','','000270000400005',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3167,'610423','泾阳县','','','000270000400006',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3168,'610424','乾县','','','000270000400007',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3169,'610425','礼泉县','','','000270000400008',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3170,'610426','永寿县','','','000270000400009',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3171,'610427','彬县','','','000270000400010',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3172,'610428','长武县','','','000270000400011',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3173,'610429','旬邑县','','','000270000400012',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3174,'610430','淳化县','','','000270000400013',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3175,'610431','武功县','','','000270000400014',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3176,'610481','兴平市','','','000270000400015',332,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3177,'610501','渭南市辖区','','','000270000500001',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3178,'610502','临渭区','','','000270000500002',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3179,'610521','华县','','','000270000500003',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3180,'610522','潼关县','','','000270000500004',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3181,'610523','大荔县','','','000270000500005',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3182,'610524','合阳县','','','000270000500006',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3183,'610525','澄城县','','','000270000500007',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3184,'610526','蒲城县','','','000270000500008',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3185,'610527','白水县','','','000270000500009',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3186,'610528','富平县','','','000270000500010',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3187,'610581','韩城市','','','000270000500011',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3188,'610582','华阴市','','','000270000500012',333,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3189,'610601','延安市辖区','','','000270000600001',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3190,'610602','宝塔区','','','000270000600002',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3191,'610621','延长县','','','000270000600003',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3192,'610622','延川县','','','000270000600004',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3193,'610623','子长县','','','000270000600005',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3194,'610624','安塞县','','','000270000600006',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3195,'610625','志丹县','','','000270000600007',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3196,'610626','吴起县','','','000270000600008',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3197,'610627','甘泉县','','','000270000600009',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3198,'610628','富县','','','000270000600010',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3199,'610629','洛川县','','','000270000600011',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3200,'610630','宜川县','','','000270000600012',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3201,'610631','黄龙县','','','000270000600013',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3202,'610632','黄陵县','','','000270000600014',334,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3203,'610701','汉中市辖区','','','000270000700001',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3204,'610702','汉台区','','','000270000700002',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3205,'610721','南郑县','','','000270000700003',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3206,'610722','城固县','','','000270000700004',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3207,'610723','洋县','','','000270000700005',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3208,'610724','西乡县','','','000270000700006',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3209,'610725','勉县','','','000270000700007',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3210,'610726','宁强县','','','000270000700008',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3211,'610727','略阳县','','','000270000700009',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3212,'610728','镇巴县','','','000270000700010',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3213,'610729','留坝县','','','000270000700011',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3214,'610730','佛坪县','','','000270000700012',335,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3215,'610801','榆林市辖区','','','000270000800001',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3216,'610802','榆阳区','','','000270000800002',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3217,'610821','神木县','','','000270000800003',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3218,'610822','府谷县','','','000270000800004',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3219,'610823','横山县','','','000270000800005',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3220,'610824','靖边县','','','000270000800006',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3221,'610825','定边县','','','000270000800007',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3222,'610826','绥德县','','','000270000800008',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3223,'610827','米脂县','','','000270000800009',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3224,'610828','佳县','','','000270000800010',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3225,'610829','吴堡县','','','000270000800011',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3226,'610830','清涧县','','','000270000800012',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3227,'610831','子洲县','','','000270000800013',336,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3228,'610901','安康市辖区','','','000270000900001',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3229,'610902','汉滨区','','','000270000900002',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3230,'610921','汉阴县','','','000270000900003',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3231,'610922','石泉县','','','000270000900004',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3232,'610923','宁陕县','','','000270000900005',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3233,'610924','紫阳县','','','000270000900006',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3234,'610925','岚皋县','','','000270000900007',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3235,'610926','平利县','','','000270000900008',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3236,'610927','镇坪县','','','000270000900009',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3237,'610928','旬阳县','','','000270000900010',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3238,'610929','白河县','','','000270000900011',337,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3239,'611001','商洛市辖区','','','000270001000001',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3240,'611002','商州区','','','000270001000002',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3241,'611021','洛南县','','','000270001000003',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3242,'611022','丹凤县','','','000270001000004',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3243,'611023','商南县','','','000270001000005',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3244,'611024','山阳县','','','000270001000006',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3245,'611025','镇安县','','','000270001000007',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3246,'611026','柞水县','','','000270001000008',338,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3247,'620101','兰州市辖区','','','000280000100001',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3248,'620102','城关区','','','000280000100002',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3249,'620103','七里河区','','','000280000100003',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3250,'620104','西固区','','','000280000100004',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3251,'620105','安宁区','','','000280000100005',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3252,'620111','红古区','','','000280000100006',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3253,'620121','永登县','','','000280000100007',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3254,'620122','皋兰县','','','000280000100008',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3255,'620123','榆中县','','','000280000100009',339,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3256,'620201','嘉峪关市辖区','','','000280000200001',340,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3257,'620301','金昌市辖区','','','000280000300001',341,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3258,'620302','金川区','','','000280000300002',341,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3259,'620321','永昌县','','','000280000300003',341,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3260,'620401','白银市辖区','','','000280000400001',342,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3261,'620402','白银区','','','000280000400002',342,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3262,'620403','平川区','','','000280000400003',342,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3263,'620421','靖远县','','','000280000400004',342,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3264,'620422','会宁县','','','000280000400005',342,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3265,'620423','景泰县','','','000280000400006',342,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3266,'620501','天水市辖区','','','000280000500001',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3267,'620502','秦州区','','','000280000500002',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3268,'620503','麦积区','','','000280000500003',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3269,'620521','清水县','','','000280000500004',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3270,'620522','秦安县','','','000280000500005',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3271,'620523','甘谷县','','','000280000500006',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3272,'620524','武山县','','','000280000500007',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3273,'620525','张家川回族自治县','','','000280000500008',343,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3274,'620601','武威市辖区','','','000280000600001',344,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3275,'620602','凉州区','','','000280000600002',344,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3276,'620621','民勤县','','','000280000600003',344,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3277,'620622','古浪县','','','000280000600004',344,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3278,'620623','天祝藏族自治县','','','000280000600005',344,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3279,'620701','张掖市辖区','','','000280000700001',345,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3280,'620702','甘州区','','','000280000700002',345,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3281,'620721','肃南裕固族自治县','','','000280000700003',345,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3282,'620722','民乐县','','','000280000700004',345,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3283,'620723','临泽县','','','000280000700005',345,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3284,'620724','高台县','','','000280000700006',345,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3285,'620725','山丹县','','','000280000700007',345,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3286,'620801','平凉市辖区','','','000280000800001',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3287,'620802','崆峒区','','','000280000800002',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3288,'620821','泾川县','','','000280000800003',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3289,'620822','灵台县','','','000280000800004',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3290,'620823','崇信县','','','000280000800005',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3291,'620824','华亭县','','','000280000800006',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3292,'620825','庄浪县','','','000280000800007',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3293,'620826','静宁县','','','000280000800008',346,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3294,'620901','酒泉市辖区','','','000280000900001',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3295,'620902','肃州区','','','000280000900002',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3296,'620921','金塔县','','','000280000900003',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3297,'620922','瓜州县','','','000280000900004',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3298,'620923','肃北蒙古族自治县','','','000280000900005',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3299,'620924','阿克塞哈萨克族自治县','','','000280000900006',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3300,'620981','玉门市','','','000280000900007',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3301,'620982','敦煌市','','','000280000900008',347,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3302,'621001','庆阳市辖区','','','000280001000001',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3303,'621002','西峰区','','','000280001000002',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3304,'621021','庆城县','','','000280001000003',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3305,'621022','环县','','','000280001000004',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3306,'621023','华池县','','','000280001000005',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3307,'621024','合水县','','','000280001000006',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3308,'621025','正宁县','','','000280001000007',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3309,'621026','宁县','','','000280001000008',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3310,'621027','镇原县','','','000280001000009',348,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3311,'621101','定西市辖区','','','000280001100001',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3312,'621102','安定区','','','000280001100002',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3313,'621121','通渭县','','','000280001100003',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3314,'621122','陇西县','','','000280001100004',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3315,'621123','渭源县','','','000280001100005',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3316,'621124','临洮县','','','000280001100006',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3317,'621125','漳县','','','000280001100007',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3318,'621126','岷县','','','000280001100008',349,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3319,'621201','陇南市辖区','','','000280001200001',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3320,'621202','武都区','','','000280001200002',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3321,'621221','成县','','','000280001200003',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3322,'621222','文县','','','000280001200004',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3323,'621223','宕昌县','','','000280001200005',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3324,'621224','康县','','','000280001200006',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3325,'621225','西和县','','','000280001200007',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3326,'621226','礼县','','','000280001200008',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3327,'621227','徽县','','','000280001200009',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3328,'621228','两当县','','','000280001200010',350,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3329,'622901','临夏市','','','000280001300001',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3330,'622921','临夏县','','','000280001300002',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3331,'622922','康乐县','','','000280001300003',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3332,'622923','永靖县','','','000280001300004',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3333,'622924','广河县','','','000280001300005',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3334,'622925','和政县','','','000280001300006',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3335,'622926','东乡族自治县','','','000280001300007',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3336,'622927','积石山保安族东乡族撒拉族自治县','','','000280001300008',351,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3337,'623001','合作市','','','000280001400001',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3338,'623021','临潭县','','','000280001400002',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3339,'623022','卓尼县','','','000280001400003',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3340,'623023','舟曲县','','','000280001400004',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3341,'623024','迭部县','','','000280001400005',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3342,'623025','玛曲县','','','000280001400006',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3343,'623026','碌曲县','','','000280001400007',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3344,'623027','夏河县','','','000280001400008',352,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3345,'630101','西宁市辖区','','','000290000100001',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3346,'630102','城东区','','','000290000100002',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3347,'630103','城中区','','','000290000100003',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3348,'630104','城西区','','','000290000100004',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3349,'630105','城北区','','','000290000100005',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3350,'630121','大通回族土族自治县','','','000290000100006',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3351,'630122','湟中县','','','000290000100007',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3352,'630123','湟源县','','','000290000100008',353,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3353,'630202','乐都区','','','000290000200001',354,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3354,'630221','平安县','','','000290000200002',354,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3355,'630222','民和回族土族自治县','','','000290000200003',354,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3356,'630223','互助土族自治县','','','000290000200004',354,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3357,'630224','化隆回族自治县','','','000290000200005',354,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3358,'630225','循化撒拉族自治县','','','000290000200006',354,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3359,'632221','门源回族自治县','','','000290000300001',355,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3360,'632222','祁连县','','','000290000300002',355,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3361,'632223','海晏县','','','000290000300003',355,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3362,'632224','刚察县','','','000290000300004',355,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3363,'632321','同仁县','','','000290000400001',356,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3364,'632322','尖扎县','','','000290000400002',356,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3365,'632323','泽库县','','','000290000400003',356,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3366,'632324','河南蒙古族自治县','','','000290000400004',356,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3367,'632521','共和县','','','000290000500001',357,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3368,'632522','同德县','','','000290000500002',357,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3369,'632523','贵德县','','','000290000500003',357,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3370,'632524','兴海县','','','000290000500004',357,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3371,'632525','贵南县','','','000290000500005',357,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3372,'632621','玛沁县','','','000290000600001',358,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3373,'632622','班玛县','','','000290000600002',358,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3374,'632623','甘德县','','','000290000600003',358,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3375,'632624','达日县','','','000290000600004',358,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3376,'632625','久治县','','','000290000600005',358,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3377,'632626','玛多县','','','000290000600006',358,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3378,'632701','玉树市','','','000290000700001',359,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3379,'632722','杂多县','','','000290000700002',359,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3380,'632723','称多县','','','000290000700003',359,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3381,'632724','治多县','','','000290000700004',359,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3382,'632725','囊谦县','','','000290000700005',359,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3383,'632726','曲麻莱县','','','000290000700006',359,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3384,'632801','格尔木市','','','000290000800001',360,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3385,'632802','德令哈市','','','000290000800002',360,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3386,'632821','乌兰县','','','000290000800003',360,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3387,'632822','都兰县','','','000290000800004',360,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3388,'632823','天峻县','','','000290000800005',360,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3389,'640101','银川市辖区','','','000300000100001',361,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3390,'640104','兴庆区','','','000300000100002',361,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3391,'640105','西夏区','','','000300000100003',361,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3392,'640106','金凤区','','','000300000100004',361,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3393,'640121','永宁县','','','000300000100005',361,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3394,'640122','贺兰县','','','000300000100006',361,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3395,'640181','灵武市','','','000300000100007',361,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3396,'640201','石嘴山市辖区','','','000300000200001',362,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3397,'640202','大武口区','','','000300000200002',362,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3398,'640205','惠农区','','','000300000200003',362,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3399,'640221','平罗县','','','000300000200004',362,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3400,'640301','吴忠市辖区','','','000300000300001',363,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3401,'640302','利通区','','','000300000300002',363,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3402,'640303','红寺堡区','','','000300000300003',363,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3403,'640323','盐池县','','','000300000300004',363,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3404,'640324','同心县','','','000300000300005',363,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3405,'640381','青铜峡市','','','000300000300006',363,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3406,'640401','固原市辖区','','','000300000400001',364,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3407,'640402','原州区','','','000300000400002',364,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3408,'640422','西吉县','','','000300000400003',364,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3409,'640423','隆德县','','','000300000400004',364,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3410,'640424','泾源县','','','000300000400005',364,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3411,'640425','彭阳县','','','000300000400006',364,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3412,'640501','中卫市辖区','','','000300000500001',365,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3413,'640502','沙坡头区','','','000300000500002',365,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3414,'640521','中宁县','','','000300000500003',365,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3415,'640522','海原县','','','000300000500004',365,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3416,'650101','乌鲁木齐市辖区','','','000310000100001',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3417,'650102','天山区','','','000310000100002',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3418,'650103','沙依巴克区','','','000310000100003',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3419,'650104','新市区','','','000310000100004',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3420,'650105','水磨沟区','','','000310000100005',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3421,'650106','头屯河区','','','000310000100006',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3422,'650107','达坂城区','','','000310000100007',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3423,'650109','米东区','','','000310000100008',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3424,'650121','乌鲁木齐县','','','000310000100009',366,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3425,'650201','克拉玛依市辖区','','','000310000200001',367,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3426,'650202','独山子区','','','000310000200002',367,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3427,'650203','克拉玛依区','','','000310000200003',367,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3428,'650204','白碱滩区','','','000310000200004',367,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3429,'650205','乌尔禾区','','','000310000200005',367,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3430,'652101','吐鲁番市','','','000310000300001',368,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3431,'652122','鄯善县','','','000310000300002',368,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3432,'652123','托克逊县','','','000310000300003',368,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3433,'652201','哈密市','','','000310000400001',369,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3434,'652222','巴里坤哈萨克自治县','','','000310000400002',369,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3435,'652223','伊吾县','','','000310000400003',369,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3436,'652301','昌吉市','','','000310000500001',370,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3437,'652302','阜康市','','','000310000500002',370,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3438,'652323','呼图壁县','','','000310000500003',370,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3439,'652324','玛纳斯县','','','000310000500004',370,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3440,'652325','奇台县','','','000310000500005',370,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3441,'652327','吉木萨尔县','','','000310000500006',370,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3442,'652328','木垒哈萨克自治县','','','000310000500007',370,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3443,'652701','博乐市','','','000310000600001',371,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3444,'652702','阿拉山口市','','','000310000600002',371,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3445,'652722','精河县','','','000310000600003',371,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3446,'652723','温泉县','','','000310000600004',371,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3447,'652801','库尔勒市','','','000310000700001',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3448,'652822','轮台县','','','000310000700002',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3449,'652823','尉犁县','','','000310000700003',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3450,'652824','若羌县','','','000310000700004',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3451,'652825','且末县','','','000310000700005',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3452,'652826','焉耆回族自治县','','','000310000700006',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3453,'652827','和静县','','','000310000700007',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3454,'652828','和硕县','','','000310000700008',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3455,'652829','博湖县','','','000310000700009',372,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3456,'652901','阿克苏市','','','000310000800001',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3457,'652922','温宿县','','','000310000800002',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3458,'652923','库车县','','','000310000800003',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3459,'652924','沙雅县','','','000310000800004',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3460,'652925','新和县','','','000310000800005',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3461,'652926','拜城县','','','000310000800006',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3462,'652927','乌什县','','','000310000800007',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3463,'652928','阿瓦提县','','','000310000800008',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3464,'652929','柯坪县','','','000310000800009',373,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3465,'653001','阿图什市','','','000310000900001',374,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3466,'653022','阿克陶县','','','000310000900002',374,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3467,'653023','阿合奇县','','','000310000900003',374,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3468,'653024','乌恰县','','','000310000900004',374,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3469,'653101','喀什市','','','000310001000001',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3470,'653121','疏附县','','','000310001000002',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3471,'653122','疏勒县','','','000310001000003',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3472,'653123','英吉沙县','','','000310001000004',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3473,'653124','泽普县','','','000310001000005',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3474,'653125','莎车县','','','000310001000006',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3475,'653126','叶城县','','','000310001000007',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3476,'653127','麦盖提县','','','000310001000008',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3477,'653128','岳普湖县','','','000310001000009',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3478,'653129','伽师县','','','000310001000010',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3479,'653130','巴楚县','','','000310001000011',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3480,'653131','塔什库尔干塔吉克自治县','','','000310001000012',375,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3481,'653201','和田市','','','000310001100001',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3482,'653221','和田县','','','000310001100002',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3483,'653222','墨玉县','','','000310001100003',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3484,'653223','皮山县','','','000310001100004',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3485,'653224','洛浦县','','','000310001100005',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3486,'653225','策勒县','','','000310001100006',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3487,'653226','于田县','','','000310001100007',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3488,'653227','民丰县','','','000310001100008',376,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3489,'654002','伊宁市','','','000310001200001',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3490,'654003','奎屯市','','','000310001200002',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3491,'654021','伊宁县','','','000310001200003',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3492,'654022','察布查尔锡伯自治县','','','000310001200004',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3493,'654023','霍城县','','','000310001200005',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3494,'654024','巩留县','','','000310001200006',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3495,'654025','新源县','','','000310001200007',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3496,'654026','昭苏县','','','000310001200008',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3497,'654027','特克斯县','','','000310001200009',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3498,'654028','尼勒克县','','','000310001200010',377,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3499,'654201','塔城市','','','000310001300001',378,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3500,'654202','乌苏市','','','000310001300002',378,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3501,'654221','额敏县','','','000310001300003',378,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3502,'654223','沙湾县','','','000310001300004',378,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3503,'654224','托里县','','','000310001300005',378,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3504,'654225','裕民县','','','000310001300006',378,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3505,'654226','和布克赛尔蒙古自治县','','','000310001300007',378,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3506,'654301','阿勒泰市','','','000310001400001',379,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3507,'654321','布尔津县','','','000310001400002',379,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3508,'654322','富蕴县','','','000310001400003',379,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3509,'654323','福海县','','','000310001400004',379,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3510,'654324','哈巴河县','','','000310001400005',379,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3511,'654325','青河县','','','000310001400006',379,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3512,'654326','吉木乃县','','','000310001400007',379,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3513,'659001','石河子市','','','000310001500001',380,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3514,'659002','阿拉尔市','','','000310001500002',380,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3515,'659003','图木舒克市','','','000310001500003',380,3,0,0,1,NULL);
    INSERT INTO [BD_Area_Sys] ([AreaID],[AreaNO],[AreaName],[AreaAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[AreaType],[Stt],[Remark]) values (3516,'659004','五家渠市','','','000310001500004',380,3,0,0,1,NULL);
SET IDENTITY_INSERT [BD_Area_Sys] OFF
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area_Sys]') AND name = N'IX_BD_Area_Sys_AreaIDAreaName') 
	CREATE  INDEX IX_BD_Area_Sys_AreaIDAreaName on BD_Area_Sys ([AreaID],[AreaName]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area_Sys]') AND name = N'IX_BD_Area_Sys_ParIDAreaNOAreaName') 
	CREATE  INDEX IX_BD_Area_Sys_ParIDAreaNOAreaName on BD_Area_Sys ([ParID],[AreaNO],[AreaName]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area_Sys]') AND name = N'IX_BD_Area_Sys_ParID') 
	CREATE  INDEX IX_BD_Area_Sys_ParID on BD_Area_Sys ([ParID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area_Sys]') AND name = N'IX_BD_Area_Sys_AreaNO') 
	CREATE  INDEX IX_BD_Area_Sys_AreaNO on BD_Area_Sys ([AreaNO]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Area_Sys]') AND name = N'IX_BD_Area_Sys_AreaName') 
	CREATE  INDEX IX_BD_Area_Sys_AreaName on BD_Area_Sys ([AreaName]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM [BD_Area_Sys] WHERE AreaID = 1 AND AreaNO = 'ALL') 	
	UPDATE [BD_Area_Sys] SET AreaNO = 'ALL' WHERE AreaID = 1




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_BaseOperatedRecord]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_BaseOperatedRecord]
(
    [RecordID] [BIGINT] IDENTITY(1,1) NOT NULL,
    [IfParentClass]	int default(0),		--是否父类 1=父类、0=子类
    [BaseInfoID] [int] ,		--基本信息ID
    [BaseType] varchar(50),		--基本信息类型（P=商品、B=往来单位、K=仓库、E=职员、A=地区、D=部门）
    [OperateType] varchar(50),	--操作类型(New=新增、Modify=编辑、Delete=删除、Stop=停用、Start=启用)
    [LastUpdateTime] datetime	--最后操作时间
)
END

 




/*====================== TABLE: [BD_Btype] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Btype]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Btype]
(
    [BTypeID] [int] IDENTITY(1,1) NOT NULL,
    [BTypeCode] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_BTypeCode] DEFAULT '',
    [BTypeName] [varchar](100) NOT NULL,
    [BtypeAbbName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_BtypeAbbName] DEFAULT '',
    [Spell] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_Spell] DEFAULT '',
    [BtypeTypeID] [int] NULL,
    [AreaID] [int] NOT NULL CONSTRAINT [DF_BD_Btype_AreaID] DEFAULT (0),
    [PriceLvl] [tinyint] NOT NULL CONSTRAINT [DF_BD_Btype_PriceLvl] DEFAULT (1),
    [LinkMan] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_LinkMan] DEFAULT '',
    [Tel] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_Tel] DEFAULT '',
    [MTel] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Btype_MTel] DEFAULT '',
    [Email] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_Email] DEFAULT '',
    [Adress] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Btype_Adress] DEFAULT '',
    [Bank] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_Bank] DEFAULT '',
    [BankAcntNo] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_BankAcntNo] DEFAULT '',
    [TaxNo] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_TaxNo] DEFAULT '',
    [Boss] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_Boss] DEFAULT '',
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Btype_Stt] DEFAULT (1),
    [Remark] [varchar](256) NULL,    
    [PaidCircle] [tinyint] NOT NULL CONSTRAINT [DF_BD_Btype_PaidCircle] DEFAULT (0),
    [StatementPeriod] [smallint] NOT NULL CONSTRAINT [DF_BD_Btype_StatementPeriod] DEFAULT (0),    
    [PriceTrack] [tinyint] NOT NULL CONSTRAINT [DF_BD_Btype_PriceTrack] DEFAULT (1),
    [PaidDeadline] [tinyint] NOT NULL CONSTRAINT [DF_BD_Btype_PaidDeadline] DEFAULT (0),
    CONSTRAINT [PK_BD_Btype] PRIMARY KEY CLUSTERED ([BTypeID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_Btype' AND a.Name='PriceTrack')
    ALTER TABLE BD_Btype ADD PriceTrack TINYINT NOT NULL CONSTRAINT [DF_BD_Btype_PriceTrack] DEFAULT (1)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_Btype' AND a.Name='PaidCircle')
    ALTER TABLE BD_Btype ADD PaidCircle TINYINT NOT NULL CONSTRAINT [DF_BD_Btype_PaidCircle] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_Btype' AND a.Name='StatementPeriod')
    ALTER TABLE BD_Btype ADD StatementPeriod SMALLINT NOT NULL CONSTRAINT [DF_BD_Btype_StatementPeriod] DEFAULT (0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Btype]') AND name = N'IX_BD_Btype_BTypeIDBTypeName') 
	CREATE  INDEX IX_BD_Btype_BTypeIDBTypeName on BD_Btype ([BTypeID],[BTypeName]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Btype]') AND name = N'IX_BD_Btype_AreaID') 
	CREATE  INDEX IX_BD_Btype_AreaID on BD_Btype ([AreaID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Btype]') AND name = N'IX_BD_Btype_BTypeCodeBTypeName') 
	CREATE  INDEX IX_BD_Btype_BTypeCodeBTypeName on BD_Btype ([BTypeCode],[BTypeName]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Btype]') AND name = N'IX_BD_Btype_BtypeTypeID') 
	CREATE  INDEX IX_BD_Btype_BtypeTypeID on BD_Btype ([BtypeTypeID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_Btype' AND a.Name='PaidDeadline')
    ALTER TABLE dbo.BD_Btype ADD PaidDeadline tinyint NOT NULL CONSTRAINT [DF_BD_Btype_PaidDeadline] DEFAULT (0)

 




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BD_Btype_CustomItem]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[BD_Btype_CustomItem]
(
    [CustItemID] [int] NOT NULL,
    [CustItemName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Btype_CustomItem_CustItemName] DEFAULT '',
    [IsShow] [bit] NOT NULL CONSTRAINT [DF_BD_Btype_CustomItem_IsShow] DEFAULT (0),
    [SourceType] [tinyint] NOT NULL CONSTRAINT [DF_BD_Btype_CustomItem_SourceType] DEFAULT (0),
    [Source] [int] NOT NULL CONSTRAINT [DF_BD_Btype_CustomItem_Source] DEFAULT (0),
    CONSTRAINT [PK_BD_Btype_CustomItem] PRIMARY KEY NONCLUSTERED ([CustItemID])
)
INSERT INTO [dbo].[BD_Btype_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (1,'自定义字段1',0,1,0)
INSERT INTO [dbo].[BD_Btype_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (2,'自定义字段2',0,1,0)
INSERT INTO [dbo].[BD_Btype_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (3,'自定义字段3',0,1,0)
INSERT INTO [dbo].[BD_Btype_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (4,'自定义字段4',0,1,0)
INSERT INTO [dbo].[BD_Btype_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (5,'自定义字段5',0,1,0)
END




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BD_Btype_CustomVal]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[BD_Btype_CustomVal]
(
    [CustValID] [int] IDENTITY(1,1) NOT NULL,
    [BaseID] [int] NOT NULL,
    [CustVal1] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Btype_CustomVal_CustVal1] DEFAULT '',
    [CustVal2] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Btype_CustomVal_CustVal2] DEFAULT '',
    [CustVal3] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Btype_CustomVal_CustVal3] DEFAULT '',
    [CustVal4] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Btype_CustomVal_CustVal4] DEFAULT '',
    [CustVal5] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Btype_CustomVal_CustVal5] DEFAULT '',
    CONSTRAINT [PK_BD_Btype_CustomVal] PRIMARY KEY NONCLUSTERED ([CustValID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Btype_CustomVal]') AND name = N'IX_BD_Btype_CustomVal_BaseID') 
	CREATE UNIQUE CLUSTERED INDEX IX_BD_Btype_CustomVal_BaseID on BD_Btype_CustomVal ([BaseID]) WITH (FILLFACTOR = 90);




/*====================== TABLE: [BD_Btype_Type] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Btype_Type]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Btype_Type]
(
    [BtypeTypeID] [int] IDENTITY(1,1) NOT NULL,
    [TypeCode] [varchar](50) NOT NULL,
    [TypeName] [varchar](100) NOT NULL,
    [Path] [varchar](25) NOT NULL CONSTRAINT [DF_BD_Btype_Type_Path] DEFAULT '',
    [ParID] [int] NOT NULL CONSTRAINT [DF_BD_Btype_Type_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_BD_Btype_Type_Lvl] DEFAULT (0),
    [SonNum] [int] NOT NULL CONSTRAINT [DF_BD_Btype_Type_SonNum] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Btype_Type_Stt] DEFAULT (1),
    CONSTRAINT [PK_BD_Btype_Type] PRIMARY KEY CLUSTERED ([BtypeTypeID])
)
SET IDENTITY_INSERT [BD_Btype_Type] ON
    INSERT INTO [BD_Btype_Type] ([BtypeTypeID],[TypeCode],[TypeName],[Path],[ParID],[Lvl],[SonNum],[Stt]) values (1,'ALL','全部往来单位','',0,0,3,1);
	INSERT INTO [BD_Btype_Type] ([BtypeTypeID],[TypeCode],[TypeName],[Path],[ParID],[Lvl],[SonNum],[Stt]) values (2,'Suppliers','供应商','00001',1,1,0,1);
	INSERT INTO [BD_Btype_Type] ([BtypeTypeID],[TypeCode],[TypeName],[Path],[ParID],[Lvl],[SonNum],[Stt]) values (3,'Customer','客户','00002',1,1,0,1);
	INSERT INTO [BD_Btype_Type] ([BtypeTypeID],[TypeCode],[TypeName],[Path],[ParID],[Lvl],[SonNum],[Stt]) values (4,'APLL','物流公司','00003',1,1,0,1);
	SET IDENTITY_INSERT [BD_Btype_Type] OFF
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Btype_Type]') AND name = N'IX_BD_Btype_Type_Path') 
	CREATE  INDEX IX_BD_Btype_Type_Path on BD_Btype_Type ([Path]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Btype_Type]') AND name = N'IX_BD_Btype_Type_ParID') 
	CREATE  INDEX IX_BD_Btype_Type_ParID on BD_Btype_Type ([ParID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BD_Custom]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[BD_Custom]
(
    [CustID] [int] IDENTITY(1,1) NOT NULL,
    [CustTypeID] [int] NOT NULL,
    [CustCode] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Custom_CustCode] DEFAULT '',
    [CustName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Custom_CustName] DEFAULT '',
    CONSTRAINT [PK_BD_Custom] PRIMARY KEY NONCLUSTERED ([CustID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BD_Custom_Type]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[BD_Custom_Type]
(
    [CustTypeID] [int] IDENTITY(1,1) NOT NULL,
    [TypeCode] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Custom_Type_TypeCode] DEFAULT '',
    [TypeName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Custom_Type_TypeName] DEFAULT '',
    CONSTRAINT [PK_BD_Custom_Type] PRIMARY KEY NONCLUSTERED ([CustTypeID])
)
END





/*====================== TABLE: [BD_Dept] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Dept]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Dept]
(
    [DeptID] [int] IDENTITY(1,1) NOT NULL,
    [DeptCode] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Dept_DeptCode] DEFAULT '',
    [DeptName] [varchar](100) NOT NULL,
    [DeptAbbName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Dept_DeptAbbName] DEFAULT '',
    [Spell] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Dept_Spell] DEFAULT '',
    [Path] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Dept_Path] DEFAULT '',
    [ParID] [int] NOT NULL CONSTRAINT [DF_BD_Dept_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_BD_Dept_Lvl] DEFAULT (0),
    [SonNum] [int] NOT NULL CONSTRAINT [DF_BD_Dept_SonNum] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Dept_Stt] DEFAULT (1),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_BD_Dept] PRIMARY KEY CLUSTERED ([DeptId])
)
SET IDENTITY_INSERT [BD_Dept] ON
    INSERT INTO [BD_Dept] ([DeptId],[DeptCode],[DeptName],[DeptAbbName],[Spell],[Path],[ParID],[Lvl],[SonNum],[Stt],[Remark]) values (1,'ALL','全部部门','','','',0,0,1,1,NULL);
SET IDENTITY_INSERT [BD_Dept] OFF
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Dept]') AND name = N'IX_BD_Dept_DeptIdDeptName') 
	CREATE  INDEX IX_BD_Dept_DeptIdDeptName on BD_Dept ([DeptId],[DeptName]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Dept]') AND name = N'IX_BD_Dept_ParID') 
	CREATE  INDEX IX_BD_Dept_ParID on BD_Dept ([ParID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Dept]') AND name = N'IX_BD_Dept_DeptCode') 
	CREATE  INDEX IX_BD_Dept_DeptCode on BD_Dept ([DeptCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Dept]') AND name = N'IX_BD_Dept_DeptName') 
	CREATE  INDEX IX_BD_Dept_DeptName on BD_Dept ([DeptName]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM [BD_Dept] WHERE DeptID = 1 AND DeptCode = 'ALL') 	
	UPDATE [BD_Dept] SET DeptCode = 'ALL' WHERE DeptID = 1



/*====================== TABLE: [BD_Employee] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Employee]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Employee]
(
    [ElyID] [int] IDENTITY(1,1) NOT NULL,
    [ElyCode] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Employee_ElyCode] DEFAULT '',
    [ElyName] [varchar](50) NOT NULL,
    [Spell] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Employee_Spell] DEFAULT '',
    [Sex] [tinyint] NOT NULL CONSTRAINT [DF_BD_Employee_Sex] DEFAULT (0),
    [Birthday] [date] NOT NULL CONSTRAINT [DF_BD_Employee_Birthday] DEFAULT '1900-01-01',
    [IdCard] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Employee_IdCard] DEFAULT '',
    [Addr] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Employee_Addr] DEFAULT '',
    [PostCode] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Employee_PostCode] DEFAULT '',
    [Tel] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Employee_Tel] DEFAULT '',
    [MTel] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Employee_MTel] DEFAULT '',
    [Email] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Employee_Email] DEFAULT '',
    [QQ] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Employee_QQ] DEFAULT '',
    [EntryDate] [date] NOT NULL CONSTRAINT [DF_BD_Employee_EntryDate] DEFAULT getdate(),
    [DeptId] [int] NULL CONSTRAINT [DF_BD_Employee_DeptId] DEFAULT (0),
    [DemitDate] [date] NOT NULL CONSTRAINT [DF_BD_Employee_DemitDate] DEFAULT '9999-01-01',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_BD_Employee_Stt] DEFAULT (1),
    [Remark] [varchar](256) NULL,
    [IsUpload][TINYINT]NOT NULL CONSTRAINT [DF_BD_Employee_IsUpload]  DEFAULT(0),
    CONSTRAINT [PK_BD_Employee] PRIMARY KEY CLUSTERED ([ElyID])
)
SET IDENTITY_INSERT [BD_Employee] ON
    INSERT INTO [BD_Employee] ([ElyID],[ElyCode],[ElyName],[Spell],[Sex],[Birthday],[IdCard],[Addr],[PostCode],[Tel],[MTel],[Email],[QQ],[EntryDate],[DeptId],[DemitDate],[Stt],[Remark]) values (1,'admin','超级管理员','admin',0,'1900-01-01','','','','','','','','1900-01-01',0,'9999-01-01',1,'');
SET IDENTITY_INSERT [BD_Employee] OFF
END
  
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Employee]') AND name = N'IX_BD_Employee_ElyIDElyName') 
	CREATE INDEX IX_BD_Employee_ElyIDElyName on BD_Employee ([ElyID],[ElyName]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Employee]') AND name = N'IX_BD_Employee_ElyCode') 
	CREATE INDEX IX_BD_Employee_ElyCode on BD_Employee ([ElyCode]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Employee]') AND name = N'IX_BD_Employee_ElyName') 
	CREATE INDEX IX_BD_Employee_ElyName on BD_Employee ([ElyName]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM [BD_Employee] WHERE ElyID = 1 AND DeptId=0)	
	UPDATE [BD_Employee] SET DeptId = 0 WHERE ElyID = 1



/*====================== TABLE: [BD_Finance] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Finance]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Finance]
(
    [FinanceID] [int] IDENTITY(500,1) NOT NULL,
    [FinanceNO] [varchar](50) NOT NULL,
    [FinanceName] [varchar](100) NOT NULL,
    [Path] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Finance_Path] DEFAULT '',
    [ParID] [int] NOT NULL CONSTRAINT [DF_BD_Finance_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_BD_Finance_Lvl] DEFAULT (0),
    [SonNum] [int] NOT NULL CONSTRAINT [DF_BD_Finance_SonNum] DEFAULT (0),
    [LoanStt] [smallint] NOT NULL CONSTRAINT [DF_BD_Finance_LoanStt] DEFAULT (0),
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_BD_Finance_Stt] DEFAULT (1),
    [SysRow] [bit] NOT NULL CONSTRAINT [DF_BD_Finance_SysRow] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_BD_Finance] PRIMARY KEY NONCLUSTERED ([FinanceID])
)
SET IDENTITY_INSERT [BD_Finance] ON
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (1,'','财务项目','',0,0,3,0,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (2,'0001','收支账户','00001',1,1,3,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (3,'0002','收入项目','00002',1,1,3,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (4,'0003','支出项目','00003',1,1,3,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (5,'1001','现金合计','0000100001',2,2,1,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (6,'1002','银行存款合计','0000100002',2,2,1,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (7,'1003','担保交易账户合计','0000100003',2,2,1,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (8,'5101','销售收入','0000200001',3,2,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (9,'5102','商品类收入','0000200002',3,2,4,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (10,'5103','其他收入','0000200003',3,2,2,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (11,'5401','销售成本','0000300001',4,2,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (12,'5405','商品类支出','0000300002',4,2,2,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (13,'5501','费用合计','0000300003',4,2,4,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (14,'100101','默认现金','000010000100001',5,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (15,'100201','默认银行','000010000200001',6,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (16,'100301','支付宝账户','000010000300001',7,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (17,'510201','商品报溢收入','000020000200001',9,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (18,'510202','其他入库收入','000020000200002',9,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (19,'510203','成本调价收入','000020000200003',9,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (20,'510204','进货退货差价','000020000200004',9,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (21,'510205','变价调拨差价','000020000200005',9,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (39,'510206','商品拆装差价','000020000200006',9,3,0,-1,1,1,NULL);
    
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (22,'510301','调账收入','000020000300001',10,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (23,'510302','利息收入','000020000300002',10,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (24,'510303','买家运费收入','000020000300003',10,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (25,'510304','其他','000020000300004',10,3,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (26,'540501','商品报损','000030000200001',12,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (27,'540502','其他出库费用','000030000200002',12,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (28,'550101','调账亏损','000030000300001',13,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (29,'550102','优惠','000030000300002',13,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (30,'550103','运费','000030000300003',13,3,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (31,'550104','网店商城扣费','000030000300004',13,3,0,1,1,1,NULL);
    
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (32,'0004','资产类','00004',1,1,3,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (33,'1131','应收款合计','0000400001',32,2,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (34,'1151','预付账款','0000400002',32,2,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (35,'1243','库存商品','0000400003',32,2,0,1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (40,'1202','在途物资','0000400004',32,2,0,1,1,1,NULL);
    
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (36,'0005','负债类','00005',1,1,3,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (37,'2121','应付款合计','0000500001',36,2,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (38,'2131','预收账款','0000500002',36,2,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (41,'2141','会员储值','0000500003',36,2,0,-1,1,1,NULL);
    INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (42,'100302','微信支付账户','000010000300002',7,3,0,1,1,1,NULL);
SET IDENTITY_INSERT [BD_Finance] OFF
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Finance]') AND name = N'IX_BD_Finance_FinanceIDFinanceName') 
	CREATE  INDEX IX_BD_Finance_FinanceIDFinanceName on BD_Finance ([FinanceID],[FinanceName]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Finance]') AND name = N'IX_BD_Finance_ParID') 
	CREATE  INDEX IX_BD_Finance_ParID on BD_Finance ([ParID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Finance]') AND name = N'IX_BD_Finance_PathLvl') 
	CREATE  INDEX IX_BD_Finance_PathLvl on BD_Finance ([Path],[Lvl]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM [BD_Finance] WHERE FinanceID = 21)
	BEGIN
		SET IDENTITY_INSERT [BD_Finance] ON
			INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (21,'510205','变价调拨差价','000020000200005',9,3,0,-1,1,1,NULL);
		SET IDENTITY_INSERT [BD_Finance] OFF
	END
	
IF NOT EXISTS (SELECT 1 FROM [BD_Finance] WHERE FinanceID = 39)
	BEGIN
		SET IDENTITY_INSERT [BD_Finance] ON
			INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (39,'510206','商品拆装差价','000020000200006',9,3,0,-1,1,1,NULL);
		SET IDENTITY_INSERT [BD_Finance] OFF
	END
	
IF NOT EXISTS (SELECT 1 FROM [BD_Finance] WHERE FinanceID = 40)
	BEGIN
		SET IDENTITY_INSERT [BD_Finance] ON
			INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (40,'1202','在途物资','0000400004',32,2,0,1,1,1,NULL);
		SET IDENTITY_INSERT [BD_Finance] OFF
	END
	
IF NOT EXISTS (SELECT 1 FROM [BD_Finance] WHERE FinanceID = 41)
	BEGIN
		SET IDENTITY_INSERT [BD_Finance] ON
			INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (41,'2141','会员储值','0000500003',36,2,0,-1,1,1,NULL);
		SET IDENTITY_INSERT [BD_Finance] OFF
	END
 	
 IF NOT EXISTS (SELECT 1 FROM [BD_Finance] WHERE FinanceID = 42)
	BEGIN
		SET IDENTITY_INSERT [BD_Finance] ON
			INSERT INTO [BD_Finance] ([FinanceID],[FinanceNO],[FinanceName],[Path],[ParID],[Lvl],[SonNum],[LoanStt],[Stt],[SysRow],[Remark]) values (42,'100302','微信支付账户','000010000300002',7,3,0,1,1,1,NULL);
		SET IDENTITY_INSERT [BD_Finance] OFF
	END
 	




/*====================== TABLE: [BD_Funds] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Funds]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Funds]
(
    [FundsID] [int] IDENTITY(1,1) NOT NULL,
    [FinanceID] [int] NOT NULL,
    [QcBalances] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Funds_QcBalances] DEFAULT (0),
    [QmBalances] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Funds_QmBalances] DEFAULT (0),
    CONSTRAINT [PK_BD_Funds] PRIMARY KEY NONCLUSTERED ([FundsID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Funds]') AND name = N'IX_BD_Funds_FinanceID') 
	CREATE UNIQUE CLUSTERED INDEX IX_BD_Funds_FinanceID on BD_Funds ([FinanceID]) WITH (FILLFACTOR = 90);





/*====================== TABLE: [BD_Goods] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods]
(
    [GoodsID] [bigint] IDENTITY(1,1) NOT NULL,
    [GoodsNo] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_GoodsNo] DEFAULT '',
    [GoodsTypeID] [bigint] NULL CONSTRAINT [DF_BD_Goods_GoodsTypeID] DEFAULT (0),
    [GoodsName] [varchar](100) NOT NULL,
    [GoodsAbbName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_GoodsAbbName] DEFAULT '',
    [Spell] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_Spell] DEFAULT '',
    [Spec] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_Spec] DEFAULT '',
    [Model] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_Model] DEFAULT '',
    [Place] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_Place] DEFAULT '',
    [KG] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_KG] DEFAULT (0),
    [PptGroupID] [int] NULL CONSTRAINT [DF_BD_Goods_PptGroupID] DEFAULT (0),
    [Graph1] [int] NOT NULL CONSTRAINT [DF_BD_Goods_Graph1] DEFAULT (0),
    [Graph2] [int] NOT NULL CONSTRAINT [DF_BD_Goods_Graph2] DEFAULT (0),
    [Graph3] [int] NOT NULL CONSTRAINT [DF_BD_Goods_Graph3] DEFAULT (0),
    [Graph4] [int] NOT NULL CONSTRAINT [DF_BD_Goods_Graph4] DEFAULT (0),
    [Graph5] [int] NOT NULL CONSTRAINT [DF_BD_Goods_Graph5] DEFAULT (0),
    [CreateDate] [datetime] NOT NULL CONSTRAINT [DF_BD_Goods_CreateDate] DEFAULT getdate(),
    [ElyID] [int] NOT NULL CONSTRAINT [DF_BD_Goods_ElyID] DEFAULT (0),
    [UpdateDate] [datetime] NOT NULL CONSTRAINT [DF_BD_Goods_UpdateDate] DEFAULT getdate(),
    [UpdateOprId] [int] NOT NULL CONSTRAINT [DF_BD_Goods_UpdateOprId] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Goods_Stt] DEFAULT (1),
    [Del] [bit] NOT NULL CONSTRAINT [DF_BD_Goods_Del] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [UpdateTag] [int] NOT NULL CONSTRAINT [DF_BD_Goods_UpdateTag] DEFAULT (0),
    [IsUpload][TINYINT]NOT NULL CONSTRAINT [DF_BD_Goods_IsUpload]  DEFAULT(0),
    [UPriceType][TINYINT]NOT NULL CONSTRAINT [DF_BD_Goods_UPriceType]  DEFAULT(1),
    [Brand] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_Brand]  DEFAULT '',  
    [IsOS] BIT NOT NULL CONSTRAINT [DF_BD_Goods_IsOS] DEFAULT(0), 
    [IsSerial] BIT NOT NULL CONSTRAINT [DF_BD_Goods_IsSerial] DEFAULT(0), 
    [PIC] [varchar](50) NULL,
    [CostMethod] [TINYINT] NOT NULL CONSTRAINT [DF_BD_Goods_CostMethod] DEFAULT (1),
    [DateType] [TINYINT] NOT NULL CONSTRAINT [DF_BD_Goods_DateType] DEFAULT (1),
    [ValidDays] [int] NOT NULL CONSTRAINT [DF_BD_Goods_ValidDays]  DEFAULT (0),
    [NearbyDays] [int] NOT NULL CONSTRAINT [DF_BD_Goods_NearbyDays]  DEFAULT (0),
    CONSTRAINT [PK_BD_Goods] PRIMARY KEY CLUSTERED ([GoodsID])
)
END
  
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='Brand')
	ALTER TABLE BD_Goods ADD [Brand] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_Brand]  DEFAULT ''
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='IsOS')
	ALTER TABLE BD_Goods ADD [IsOS] BIT NOT NULL CONSTRAINT [DF_BD_Goods_IsOS] DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='IsSerial')
	ALTER TABLE BD_Goods ADD [IsSerial] BIT NOT NULL CONSTRAINT [DF_BD_Goods_IsSerial] DEFAULT(0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='PIC')
	ALTER TABLE BD_Goods ADD [PIC] VARCHAR(50) NULL

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='CostMethod')
	ALTER TABLE BD_Goods ADD [CostMethod] [TINYINT] NOT NULL CONSTRAINT [DF_BD_Goods_CostMethod] DEFAULT (1)
   
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='DateType')
	ALTER TABLE BD_Goods ADD [DateType] [TINYINT] NOT NULL CONSTRAINT [DF_BD_Goods_DateType] DEFAULT (1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='ValidDays')
	ALTER TABLE BD_Goods ADD [ValidDays] [int] NOT NULL CONSTRAINT [DF_BD_Goods_ValidDays]  DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_Goods' AND a.Name='NearbyDays')
	ALTER TABLE BD_Goods ADD [NearbyDays] [int] NOT NULL CONSTRAINT [DF_BD_Goods_NearbyDays]  DEFAULT (0)
	
	
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods]') AND name = N'IX_BD_Goods_GoodsIDGoodsName') 
	CREATE  INDEX IX_BD_Goods_GoodsIDGoodsName on BD_Goods ([GoodsID],[GoodsName]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods]') AND name = N'IX_BD_Goods_GoodsNoGoodsName') 
	CREATE  INDEX IX_BD_Goods_GoodsNoGoodsName on BD_Goods ([GoodsNo],[GoodsName]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods]') AND name = N'IX_BD_Goods_GoodsTypeID') 
	CREATE  INDEX IX_BD_Goods_GoodsTypeID on BD_Goods ([GoodsTypeID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods]') AND name = N'IX_BD_Goods_Graph') 
	CREATE  INDEX IX_BD_Goods_Graph on BD_Goods ([Graph1],[Graph2],[Graph3],[Graph4],[Graph5]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods]') AND name = N'IX_BD_Goods_PptGroupID') 
	CREATE  INDEX IX_BD_Goods_PptGroupID on BD_Goods ([PptGroupID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BD_Goods_CustomItem]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[BD_Goods_CustomItem]
(
    [CustItemID] [int] NOT NULL,
    [CustItemName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_CustomItem_CustItemName] DEFAULT '',
    [IsShow] [bit] NOT NULL CONSTRAINT [DF_BD_Goods_CustomItem_IsShow] DEFAULT (0),
    [SourceType] [tinyint] NOT NULL CONSTRAINT [DF_BD_Goods_CustomItem_SourceType] DEFAULT (0),
    [Source] [int] NOT NULL CONSTRAINT [DF_BD_Goods_CustomItem_Source] DEFAULT (0),
    CONSTRAINT [PK_BD_Goods_CustomItem] PRIMARY KEY NONCLUSTERED ([CustItemID])
)
INSERT INTO [dbo].[BD_Goods_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (1,'自定义字段1',0,1,0)
INSERT INTO [dbo].[BD_Goods_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (2,'自定义字段2',0,1,0)
INSERT INTO [dbo].[BD_Goods_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (3,'自定义字段3',0,1,0)
INSERT INTO [dbo].[BD_Goods_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (4,'自定义字段4',0,1,0)
INSERT INTO [dbo].[BD_Goods_CustomItem]([CustItemID],[CustItemName],[IsShow],[SourceType],[Source]) VALUES (5,'自定义字段5',0,1,0)
END



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BD_Goods_CustomVal]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[BD_Goods_CustomVal]
(
    [CustValID] [int] IDENTITY(1,1) NOT NULL,
    [BaseID] [int] NOT NULL,
    [CustVal1] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Goods_CustomVal_CustVal1] DEFAULT '',
    [CustVal2] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Goods_CustomVal_CustVal2] DEFAULT '',
    [CustVal3] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Goods_CustomVal_CustVal3] DEFAULT '',
    [CustVal4] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Goods_CustomVal_CustVal4] DEFAULT '',
    [CustVal5] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Goods_CustomVal_CustVal5] DEFAULT '',
    CONSTRAINT [PK_BD_Goods_CustomVal] PRIMARY KEY NONCLUSTERED ([CustValID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_CustomVal]') AND name = N'IX_BD_Goods_CustomVal_BaseID') 
	CREATE UNIQUE CLUSTERED INDEX IX_BD_Goods_CustomVal_BaseID on BD_Goods_CustomVal ([BaseID]) WITH (FILLFACTOR = 90);




/*====================== TABLE: [BD_Goods_DftWhs] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_DftWhs]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_DftWhs]
(
    [GoodsID] [bigint] NOT NULL,
    [WhsID] [int] NOT NULL,
    [WhsPtID] [int] NOT NULL,
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Goods_DftWhs_Stt] DEFAULT (1),
    CONSTRAINT [PK_BD_Goods_DftWhs] PRIMARY KEY NONCLUSTERED ([GoodsID],[WhsID],[WhsPtID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_DftWhs]') AND name = N'IXC_BD_Goods_DftWhs_BTypeID') 
	CREATE CLUSTERED  INDEX IXC_BD_Goods_DftWhs_BTypeID on BD_Goods_DftWhs ([GoodsID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_DftWhs]') AND name = N'IX_BD_Goods_DftWhs_WhsIDWhsPtID') 
	CREATE  INDEX IX_BD_Goods_DftWhs_WhsIDWhsPtID on BD_Goods_DftWhs ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
 




/*====================== TABLE: [BD_Goods_Graph] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_Graph]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_Graph]
(
    [GraphID] [bigint] IDENTITY(1,1) NOT NULL,
    [GraphName] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Goods_Graph_GraphName] DEFAULT '',
    [Graph] [varbinary](MAX) NOT NULL,
    CONSTRAINT [PK_BD_Goods_Graph] PRIMARY KEY CLUSTERED ([GraphID])
)
END





/*====================== TABLE: [BD_Goods_NO] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_NO]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_NO]
(
    [GoodsID] [bigint] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [GoodsNO] [varchar](50) NOT NULL,
    CONSTRAINT [PK_BD_Goods_NO] PRIMARY KEY NONCLUSTERED ([GoodsID],[BTypeID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_NO]') AND name = N'IX_BD_Goods_NO_BTypeID') 
	CREATE  INDEX IX_BD_Goods_NO_BTypeID on BD_Goods_NO ([BTypeID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_NO]') AND name = N'IXC_BD_Goods_NO_GoodsID') 
	CREATE CLUSTERED  INDEX IXC_BD_Goods_NO_GoodsID on BD_Goods_NO ([GoodsID]) WITH (FILLFACTOR = 90);
 




/*====================== TABLE: [BD_Goods_Ppt1] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_Ppt1]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_Ppt1]
(
    [Ppt1ID] [int] IDENTITY(1,1) NOT NULL,
    [PptNO] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Goods_Ppt1_PptNO] DEFAULT '',
    [Value] [varchar](10) NOT NULL,
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_BD_Goods_Ppt1] PRIMARY KEY CLUSTERED ([Ppt1ID])
)
END

 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_Ppt1]') AND name = N'IX_BD_Goods_Ppt1_Value') 
	CREATE  INDEX IX_BD_Goods_Ppt1_Value on BD_Goods_Ppt1 ([Value]) WITH (FILLFACTOR = 90);
 




/*====================== TABLE: [BD_Goods_Ppt2] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_Ppt2]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_Ppt2]
(
    [Ppt2ID] [int] IDENTITY(1,1) NOT NULL,
    [PptNO] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Goods_Ppt2_PptNO] DEFAULT '',
    [Value] [varchar](10) NOT NULL,
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_BD_Goods_Ppt2] PRIMARY KEY CLUSTERED ([Ppt2ID])
)
END

 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_Ppt2]') AND name = N'IX_BD_Goods_Ppt2_Value') 
	CREATE  INDEX IX_BD_Goods_Ppt2_Value on BD_Goods_Ppt2 ([Value]) WITH (FILLFACTOR = 90);
 




/*====================== TABLE: [BD_Goods_PptGroup] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_PptGroup]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_PptGroup]
(
    [PptGroupID] [int] NOT NULL,
    [GroupName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Goods_PptGroup_GroupName] DEFAULT '',
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_BD_Goods_PptGroup_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_BD_Goods_PptGroup_Ppt2ID] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Goods_PptGroup_Stt] DEFAULT (1),
    [RemarkPpt] [varchar](256) NULL,
    [RemarkGroup] [varchar](256) NULL,
    [UsePptGroup] [bit] not null CONSTRAINT [DF_BD_Goods_PptGroup_UsePptGroup] DEFAULT (1),
    CONSTRAINT [PK_BD_Goods_PptGroup] PRIMARY KEY NONCLUSTERED ([PptGroupID],[Ppt1ID],[Ppt2ID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_Goods_PptGroup' AND a.Name='UsePptGroup')
    ALTER TABLE dbo.BD_Goods_PptGroup ADD UsePptGroup INT NOT NULL CONSTRAINT [BD_Goods_PptGroup_UsePptGroup]  DEFAULT(1)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_PptGroup]') AND name = N'IX_BD_Goods_PptGroup_Ppt1IDPpt2ID') 
	CREATE  INDEX IX_BD_Goods_PptGroup_Ppt1IDPpt2ID on BD_Goods_PptGroup ([Ppt1ID],[Ppt2ID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_PptGroup]') AND name = N'IXC_BD_Goods_PptGroup_PptGroupID') 
	CREATE CLUSTERED  INDEX IXC_BD_Goods_PptGroup_PptGroupID on BD_Goods_PptGroup ([PptGroupID]) WITH (FILLFACTOR = 90);
 




/*====================== TABLE: [BD_Goods_Price] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_Price]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_Price]
(
    [GoodsID] [bigint] NOT NULL,
    [UnitID] [tinyint] NOT NULL,
    [Unit] [varchar](10) NOT NULL,
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Convfactor] DEFAULT (1),
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Goods_Price_BarCode] DEFAULT '',
    [Price_Rtl] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price_Rtl] DEFAULT (0),
    [Price1] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price1] DEFAULT (0),
    [Price2] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price2] DEFAULT (0),
    [Price3] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price3] DEFAULT (0),
    [Price4] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price4] DEFAULT (0),
    [Price5] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price5] DEFAULT (0),
    [Price6] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price6] DEFAULT (0),
    [Price7] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price7] DEFAULT (0),
    [Price8] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price8] DEFAULT (0),
    [Price9] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price9] DEFAULT (0),
    [Price10] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price10] DEFAULT (0),
    [Price11] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price11] DEFAULT (0),
    [Price12] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price12] DEFAULT (0),
    [Price13] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price13] DEFAULT (0),
    [Price14] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price14] DEFAULT (0),
    [Price15] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price15] DEFAULT (0),
    [Price16] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price16] DEFAULT (0),
    [Price17] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price17] DEFAULT (0),
    [Price18] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price18] DEFAULT (0),
    [Price19] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price19] DEFAULT (0),
    [Price20] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_Goods_Price_Price20] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Goods_Price_Stt] DEFAULT (1),
    CONSTRAINT [PK_BD_Goods_Price] PRIMARY KEY CLUSTERED ([GoodsID],[UnitID])
)
END


GO

--条形码长度从20变成100 V6.2 谢吉康 2020-2-7
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[BD_Goods_Price]') and  name = 'BarCode' and Length=20)
BEGIN
	 ALTER TABLE BD_Goods_Price
	    ALTER COLUMN BarCode VARCHAR(100)
END
GO



/*====================== TABLE: [BD_Goods_Type] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Goods_Type]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Goods_Type]
(
    [GoodsTypeID] [bigint] IDENTITY(1,1) NOT NULL,
    [TypeCode] [varchar](50) NOT NULL,
    [TypeName] [varchar](100) NOT NULL,
    [Path] [varchar](25) NOT NULL CONSTRAINT [DF_BD_Goods_Type_Path] DEFAULT '',
    [ParID] [bigint] NOT NULL CONSTRAINT [DF_BD_Goods_Type_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_BD_Goods_Type_Lvl] DEFAULT (0),
    [SonNum] [int] NOT NULL CONSTRAINT [DF_BD_Goods_Type_SonNum] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Goods_Type_Stt] DEFAULT (1),
    CONSTRAINT [PK_BD_Goods_Type] PRIMARY KEY CLUSTERED ([GoodsTypeID])
)
SET IDENTITY_INSERT [BD_Goods_Type] ON
    INSERT INTO [BD_Goods_Type] ([GoodsTypeID],[TypeCode],[TypeName],[Path],[ParID],[Lvl],[SonNum],[Stt]) values (1,'ALL','全部商品','',0,0,0,1);
SET IDENTITY_INSERT [BD_Goods_Type] OFF
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_Type]') AND name = N'IX_BD_Goods_Type_Path') 
	CREATE  INDEX IX_BD_Goods_Type_Path on BD_Goods_Type ([Path]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Goods_Type]') AND name = N'IX_BD_Goods_Type_ParID') 
	CREATE  INDEX IX_BD_Goods_Type_ParID on BD_Goods_Type ([ParID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM [BD_Goods_Type] WHERE GoodsTypeID = 1 AND TypeCode = 'ALL') 	
	UPDATE [BD_Goods_Type] SET TypeCode = 'ALL' WHERE GoodsTypeID = 1



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_OpeningSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE BD_OpeningSerial
(
	[ID] INT IDENTITY(1,1) NOT NULL,
	[StockDetailID] INT NOT NULL,
    [Serial] [varchar](50) NULL,
	[Remark] [varchar](256) NULL
    CONSTRAINT [PK_BD_OpeningSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_OpeningSerial]') AND name = N'XC_BD_OpeningSerial_StockDetailID') 
	CREATE INDEX XC_BD_OpeningSerial_StockDetailID on BD_OpeningSerial ([StockDetailID]) WITH (FILLFACTOR = 90);    



/*====================== TABLE: [BD_OpeningStock] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_OpeningStock]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_OpeningStock]
(
    [StockID] [bigint] IDENTITY(1,1) NOT NULL,
    [WhsID] [int] NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Qty] DEFAULT (0),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Price] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Total] DEFAULT (0),
    CONSTRAINT [PK_BD_OpeningStock] PRIMARY KEY CLUSTERED ([StockID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_OpeningStock]') AND name = N'IX_BD_OpeningStock_GoodsID') 
	CREATE  INDEX IX_BD_OpeningStock_GoodsID on BD_OpeningStock ([GoodsID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_OpeningStock]') AND name = N'IX_BD_OpeningStock_WhsID') 
	CREATE  INDEX IX_BD_OpeningStock_WhsID on BD_OpeningStock ([WhsID]) WITH (FILLFACTOR = 90);





/*====================== TABLE: [BD_OpeningStock_Detail] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_OpeningStock_Detail]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_OpeningStock_Detail]
(
    [DetailID] [bigint] IDENTITY(1,1) NOT NULL,
    [StockID] [bigint] NOT NULL,
    [WhsPtID] [int] NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_Ppt2ID] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_Qty] DEFAULT (0),
    [CostPrice]	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_Detail_CostPrice] DEFAULT (0),
    [CostTotal]	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_Detail_CostTotal] DEFAULT (0),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_EndDate]  DEFAULT (''),
    CONSTRAINT [PK_BD_OpeningStock_Detail] PRIMARY KEY NONCLUSTERED ([DetailID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_OpeningStock_Detail' AND a.Name='CostPrice')
    ALTER TABLE BD_OpeningStock_Detail ADD [CostPrice]	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_CostPrice] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_OpeningStock_Detail' AND a.Name='CostTotal')
    ALTER TABLE BD_OpeningStock_Detail ADD [CostTotal]	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_CostTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_OpeningStock_Detail' AND a.Name='BatchNumber')
    ALTER TABLE BD_OpeningStock_Detail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_OpeningStock_Detail' AND a.Name='ProductDate')
    ALTER TABLE BD_OpeningStock_Detail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='BD_OpeningStock_Detail' AND a.Name='EndDate')
    ALTER TABLE BD_OpeningStock_Detail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_BD_OpeningStock_Detail_EndDate]  DEFAULT ('') 



IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_OpeningStock_Detail]') AND name = N'IXC_BD_OpeningStock_Detail_StockID') 
	CREATE CLUSTERED  INDEX IXC_BD_OpeningStock_Detail_StockID on BD_OpeningStock_Detail ([StockID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_OpeningStock_Detail]') AND name = N'IX_BD_OpeningStock_Detail_GoodsID') 
	CREATE  INDEX IX_BD_OpeningStock_Detail_GoodsID on BD_OpeningStock_Detail ([GoodsID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_OpeningStock_Detail]') AND name = N'IX_BD_OpeningStock_Detail_Ppt1IDPpt2ID') 
	CREATE  INDEX IX_BD_OpeningStock_Detail_Ppt1IDPpt2ID on BD_OpeningStock_Detail ([Ppt1ID],[Ppt2ID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_OpeningStock_Detail]') AND name = N'IX_BD_OpeningStock_Detail_WhsPtID') 
	CREATE  INDEX IX_BD_OpeningStock_Detail_WhsPtID on BD_OpeningStock_Detail ([WhsPtID]) WITH (FILLFACTOR = 90);
 




/*====================== TABLE: [BD_Ppt_Name] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Ppt_Name]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Ppt_Name]
(
    [PptID] [int] IDENTITY(1,1) NOT NULL,
    [PptName] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Ppt_Name_PptName] DEFAULT '',
    CONSTRAINT [PK_BD_Ppt_Name] PRIMARY KEY CLUSTERED ([PptID])
)
SET IDENTITY_INSERT [BD_Ppt_Name] ON
    INSERT INTO [BD_Ppt_Name] ([PptID],[PptName]) values (1,'颜色');
    INSERT INTO [BD_Ppt_Name] ([PptID],[PptName]) values (2,'尺码');
SET IDENTITY_INSERT [BD_Ppt_Name] OFF
END

 




/*====================== TABLE: [BD_PriceName] ======================*/
GO

IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_PriceName]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_PriceName]
(
    [PriceID] [int] IDENTITY(1,1) NOT NULL,
    [ColName] [varchar](10) NOT NULL,
    [PriceName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_PriceName_PriceName] DEFAULT '预设价',
    CONSTRAINT [PK_BD_PriceName] PRIMARY KEY CLUSTERED ([PriceID])
)
SET IDENTITY_INSERT [BD_PriceName] ON
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (1,'Price1','预设价1');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (2,'Price2','预设价2');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (3,'Price3','预设价3');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (4,'Price4','预设价4');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (5,'Price5','预设价5');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (6,'Price6','预设价6');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (7,'Price7','预设价7');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (8,'Price8','预设价8');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (9,'Price9','预设价9');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (10,'Price10','预设价10');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (11,'Price11','预设价11');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (12,'Price12','预设价12');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (13,'Price13','预设价13');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (14,'Price14','预设价14');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (15,'Price15','预设价15');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (16,'Price16','预设价16');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (17,'Price17','预设价17');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (18,'Price18','预设价18');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (19,'Price19','预设价19');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (20,'Price20','预设价20');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (21,'Input','手工输入');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (22,'LastIn','最近进价');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (23,'Stock','库存均价');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (24,'Track','价格跟踪');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (25,'Order','订单调用');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (26,'EShop','网店订单');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (27,'Gift','赠品');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (28,'PriceCode','条码扫描');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (29,'MemberDisc','会员折扣');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (30,'Buy','调原采购单');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (31,'Sale','调原销售单');
    INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (32,'ImportBill','单据导入');
SET IDENTITY_INSERT [BD_PriceName] OFF
END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 21)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (21,'Input','手工输入');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 22)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (22,'LastIn','最近进价');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 23)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (23,'Stock','库存均价');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 24)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (24,'Track','价格跟踪');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 25)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (25,'Order','订单调用');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 26)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (26,'EShop','网店订单');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 27)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (27,'Gift','赠品');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END
IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 28)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (28,'PriceCode','条码扫描');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END 

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 29)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (29,'MemberDisc','会员折扣');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 30)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (30,'Buy','调原采购单');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 31)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (31,'Sale','调原销售单');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END
	
GO

IF NOT EXISTS (SELECT 1 FROM BD_PriceName WHERE PriceID = 32)
	BEGIN
		SET IDENTITY_INSERT [BD_PriceName] ON
		INSERT INTO [BD_PriceName] ([PriceID],[ColName],[PriceName]) values (32,'ImportBill','单据导入');
		SET IDENTITY_INSERT [BD_PriceName] OFF
	END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_PriceName' AND a.Name='DisplayName')
	ALTER TABLE dbo.BD_PriceName ADD [DisplayName] [varchar](50) 


IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='BD_PriceName' AND a.Name='IsDisplay')
	ALTER TABLE dbo.BD_PriceName ADD IsDisplay int NOT NULL default (0) 

go

UPDATE BD_PriceName SET DisplayName=PriceName where DisplayName IS NULL 
UPDATE BD_PriceName SET IsDisplay =2 WHERE PriceID<6
UPDATE BD_PriceName SET IsDisplay =2 WHERE PriceID>=21 AND PriceID<=32

GO




/*====================== TABLE: [BD_Whs] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Whs]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Whs]
(
    [WhsID] [int] IDENTITY(1,1) NOT NULL,
    [WhsNO] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Whs_WhsNO] DEFAULT '',
    [WhsName] [varchar](100) NOT NULL,
    [WhsAbbName] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Whs_WhsAbbName] DEFAULT '',
    [Spell] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Whs_Spell] DEFAULT '',
    [WhsTypeID] [int] NOT NULL,
    [AreaID] [int] NOT NULL CONSTRAINT [DF_BD_Whs_AreaID] DEFAULT (0),
    [Responsible] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Whs_Responsible] DEFAULT '',
    [LinkMan] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Whs_LinkMan] DEFAULT (0),
    [Tel] [varchar](20) NOT NULL CONSTRAINT [DF_BD_Whs_Tel] DEFAULT '',
    [Address] [varchar](100) NOT NULL CONSTRAINT [DF_BD_Whs_Address] DEFAULT '',
    [PostCode] [varchar](10) NOT NULL CONSTRAINT [DF_BD_Whs_PostCode] DEFAULT '',
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Whs_Stt]  DEFAULT (1),
    [Remark] [varchar](256) NULL,
    [ElyID] [INT] NULL CONSTRAINT [DF_BD_Whs_ElyID] DEFAULT(0) ,
    [IsUpload][TINYINT]NOT NULL CONSTRAINT [DF_BD_Whs_IsUpload]  DEFAULT(0),
    CONSTRAINT [PK_BD_Whs] PRIMARY KEY CLUSTERED ([WhsID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs]') AND name = N'IX_BD_Whs_WhsIDWhsName') 
	CREATE  INDEX IX_BD_Whs_WhsIDWhsName on BD_Whs ([WhsID],[WhsName]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs]') AND name = N'IX_BD_Whs_AreaID') 
	CREATE  INDEX IX_BD_Whs_AreaID on BD_Whs ([AreaID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs]') AND name = N'IX_BD_Whs_WhsTypeID') 
	CREATE  INDEX IX_BD_Whs_WhsTypeID on BD_Whs ([WhsTypeID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs]') AND name = N'IX_BD_Whs_WhsNO') 
	CREATE  INDEX IX_BD_Whs_WhsNO on BD_Whs ([WhsNO]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs]') AND name = N'IX_BD_Whs_WhsName') 
	CREATE  INDEX IX_BD_Whs_WhsName on BD_Whs ([WhsName]) WITH (FILLFACTOR = 90);



/*====================== TABLE: [BD_Whs_Position] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Whs_Position]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Whs_Position]
(
    [WhsPtID] [int] IDENTITY(1,1) NOT NULL,
    [WhsPtNO] [varchar](50) NOT NULL CONSTRAINT [DF_BD_Whs_Position_WhsPtNO] DEFAULT '',
    [WhsPtName] [varchar](100) NOT NULL,
    [WhsID] [int] NOT NULL,
    [WhsPtType] [tinyint] NOT NULL CONSTRAINT [DF_BD_Whs_Position_WhsPtType] DEFAULT (1),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Whs_Position_Stt] DEFAULT (1),
    [Remark] [varchar](256) NULL,
    [IsUpload][TINYINT]NOT NULL CONSTRAINT [DF_BD_Whs_Position_IsUpload]  DEFAULT(0),
    CONSTRAINT [PK_BD_Whs_Position] PRIMARY KEY CLUSTERED ([WhsPtID],[WhsID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs_Position]') AND name = N'IX_BD_Whs_Position_WhsID') 
	CREATE INDEX IX_BD_Whs_Position_WhsID on BD_Whs_Position ([WhsID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs_Position]') AND name = N'IX_BD_Whs_Position_WhsPtNO') 
	CREATE INDEX IX_BD_Whs_Position_WhsPtNO on BD_Whs_Position ([WhsPtNO]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs_Position]') AND name = N'IX_BD_Whs_Position_WhsPtIDWhsPtName') 
	CREATE INDEX IX_BD_Whs_Position_WhsPtIDWhsPtName on BD_Whs_Position ([WhsPtID],[WhsPtName]) WITH (FILLFACTOR = 90);



/*====================== TABLE: [BD_Whs_Type] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[BD_Whs_Type]') AND type in (N'U'))
BEGIN
CREATE TABLE [BD_Whs_Type]
(
    [WhsTypeID] [int] IDENTITY(1,1) NOT NULL,
    [TypeCode] [varchar](50) NOT NULL,
    [TypeName] [varchar](100) NOT NULL,
    [Path] [varchar](25) NOT NULL CONSTRAINT [DF_BD_Whs_Type_Path] DEFAULT '',
    [ParID] [int] NOT NULL CONSTRAINT [DF_BD_Whs_Type_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_BD_Whs_Type_Lvl] DEFAULT (0),
    [SonNum] [int] NOT NULL CONSTRAINT [DF_BD_Whs_Type_SonNum] DEFAULT (0),
    [Stt] [bit] NOT NULL CONSTRAINT [DF_BD_Whs_Type_Stt] DEFAULT (1),
    CONSTRAINT [PK_BD_Whs_Type] PRIMARY KEY CLUSTERED ([WhsTypeID])
)
SET IDENTITY_INSERT [BD_Whs_Type] ON
    INSERT INTO [BD_Whs_Type] ([WhsTypeID],[TypeCode],[TypeName],[Path],[ParID],[Lvl],[SonNum],[Stt]) values (1,'ALL','全部仓库','',0,0,0,1);
SET IDENTITY_INSERT [BD_Whs_Type] OFF
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs_Type]') AND name = N'IX_BD_Whs_Type_Path') 
	CREATE  INDEX IX_BD_Whs_Type_Path on BD_Whs_Type ([Path]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs_Type]') AND name = N'IX_BD_Whs_Type_TypeCode') 
	CREATE  INDEX IX_BD_Whs_Type_TypeCode on BD_Whs_Type ([TypeCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[BD_Whs_Type]') AND name = N'IX_BD_Whs_Type_TypeName') 
	CREATE  INDEX IX_BD_Whs_Type_TypeName on BD_Whs_Type ([TypeName]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM [BD_Whs_Type] WHERE WhsTypeID = 1 AND TypeCode = 'ALL') 	
	UPDATE [BD_Whs_Type] SET TypeCode = 'ALL' WHERE WhsTypeID = 1



/*====================== TABLE: [D9AgentCustomInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[D9AgentCustomInfo]') AND type in (N'U'))
BEGIN
CREATE TABLE [D9AgentCustomInfo]
(
	[ID] INT IDENTITY(1,1) NOT NULL, 
    [CustomName] [varchar](100)  NULL ,
    [LinkMan] [varchar](50)  NULL,
    [Tel] [varchar](20)  NULL,
    [BusinessMan] [varchar](50)  NULL,
    [Total] DECIMAL(20,8) NULL ,
    [Remark1] [varchar](max)  NULL ,
    [Remark2] [varchar](max)  NULL ,
    [IsServiceOnline] TINYINT NULL,
    [QQType] TINYINT NULL,
    [QQ] VARCHAR(50) NULL,
    [ServiceTel] VARCHAR(20) NULL
    CONSTRAINT [PK_D9AgentCustomInfo] PRIMARY KEY NONCLUSTERED ([ID])
)
INSERT INTO D9AgentCustomInfo(CustomName)VALUES('')
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9AgentCustomInfo' AND a.Name='IsServiceOnline')
    ALTER TABLE D9AgentCustomInfo ADD [IsServiceOnline] TINYINT NULL
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9AgentCustomInfo' AND a.Name='QQType')
    ALTER TABLE D9AgentCustomInfo ADD [QQType] TINYINT NULL

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9AgentCustomInfo' AND a.Name='QQ')
    ALTER TABLE D9AgentCustomInfo ADD [QQ] VARCHAR(50) NULL
    
 IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9AgentCustomInfo' AND a.Name='ServiceTel')
    ALTER TABLE D9AgentCustomInfo ADD [ServiceTel] VARCHAR(20) NULL
	
    
    




/*====================== TABLE: [D9ExtInfo_Ext_Ext] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[D9ExtInfo]') AND type in (N'U'))
BEGIN
CREATE TABLE [D9ExtInfo]
(
    [ID] [int] NOT NULL,
    [CustomID] [int] NOT NULL,
    [ExtType] TINYINT NOT NULL,
    [ExtDate] DATETIME NOT NULL CONSTRAINT [DF_D9ExtInfo_ExtDate] DEFAULT GETDATE(),
    [ExtDesc] [varchar](500) NOT NULL CONSTRAINT [DF_D9ExtInfo_ExtDesc] DEFAULT '',
    CONSTRAINT [PK_D9ExtInfo] PRIMARY KEY CLUSTERED ([ID])
)
END




/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[D9ZTInfo]') AND type in (N'U'))
BEGIN
CREATE TABLE [D9ZTInfo]
(
    [ZTCode] [varchar](100) NOT NULL,
    [ZTName] [varchar](256) NOT NULL,
    [Frozen] [bit] NOT NULL CONSTRAINT [DF_D9ZTInfo_Frozen] DEFAULT (0),
    [Version] [varchar](20) NOT NULL,
    [IsOpen] [bit] NOT NULL CONSTRAINT [DF_D9ZTInfo_IsOpen] DEFAULT (0),
    [ReadOnly] [bit] NOT NULL CONSTRAINT [DF_D9ZTInfo_ReadOnly] DEFAULT (0),
    ZTNumber INT DEFAULT(0) NOT NULL  ,
    ztSecret  [varchar](200) NOT NULL Default(''),
    Authorkey [varchar](200) NOT NULL Default(''),
    Exprtime DATETIME NOT NULL Default(getdate()),
    usercount INT NOT NULL Default(0),
    CreateTime DATETIME NOT NULL Default(getdate()),
    isTryOut   INT NOT NULL Default(0),
    CONSTRAINT [PK_D9ZTInfo] PRIMARY KEY NONCLUSTERED ([ZTCode])
)
	--INSERT INTO [D9ZTInfo] ([ZTCode],[ZTName],[Frozen],[Version],[IsOpen]) values ('D9默认账套440','D9默认账套440',0,'4.4.0_2016.04.18',0);
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='ReadOnly')
    ALTER TABLE D9ZTInfo ADD [ReadOnly] [bit] NOT NULL CONSTRAINT [DF_D9ZTInfo_ReadOnly] DEFAULT (0)
        
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='ZTNumber')
BEGIN
    ALTER TABLE D9ZTInfo ADD ZTNumber  INT  NOT NULL  DEFAULT(0)
END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='ztSecret')
BEGIN
    ALTER TABLE D9ZTInfo ADD ztSecret  [varchar](200)NOT NULL Default('')
END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='Authorkey')
BEGIN 
    ALTER TABLE D9ZTInfo ADD Authorkey  [varchar](200) NOT NULL Default('')
END
       
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='Exprtime')
BEGIN
    ALTER TABLE D9ZTInfo ADD Exprtime   DATETIME  NOT NULL Default(getdate())
END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='usercount')
BEGIN
    ALTER TABLE D9ZTInfo ADD usercount  INT  NOT NULL Default(0)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='CreateTime')
BEGIN
    ALTER TABLE D9ZTInfo ADD CreateTime DATETIME  NOT NULL Default(getdate())
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='isTryOut')
BEGIN
    ALTER TABLE D9ZTInfo ADD isTryOut INT NOT NULL Default(0)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='isStop')
BEGIN
    ALTER TABLE D9ZTInfo ADD isStop BIT NOT Null  DEFAULT(0)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='Pcid')
BEGIN
    ALTER TABLE D9ZTInfo ADD Pcid varchar(50) NOT Null  DEFAULT('')
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='PublicKey')
BEGIN
    ALTER TABLE D9ZTInfo ADD PublicKey varchar(2000) NOT Null  DEFAULT('')
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='D9ZTInfo' AND a.Name='APPID')
BEGIN
    ALTER TABLE D9ZTInfo ADD APPID varchar(256) NOT Null  DEFAULT('')
END




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_ARAPBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_ARAPBill_PaidTotal] DEFAULT (0),
	[Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_ARAPBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_ARAPBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_ARAPBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_ARAPBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_ARAPBill_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_ARAPBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_ARAPBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_ARAPBill_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_MF_ARAPBill_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_ARAPBill_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_ARAPBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_ARAPBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND name = N'IXC_MF_ARAPBill_BillCode') 
	CREATE  INDEX IXC_MF_ARAPBill_BillCode on MF_ARAPBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND name = N'IXC_MF_ARAPBill_BillDate') 
	CREATE  INDEX IXC_MF_ARAPBill_BillDate on MF_ARAPBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND name = N'IXC_MF_ARAPBill_CreateTime') 
	CREATE  INDEX IXC_MF_ARAPBill_CreateTime on MF_ARAPBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND name = N'IXC_MF_ARAPBill_PosTime') 
	CREATE  INDEX IXC_MF_ARAPBill_PosTime on MF_ARAPBill ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND name = N'IX_MF_ARAPBill_BTypeID') 
	CREATE  INDEX IX_MF_ARAPBill_BTypeID on MF_ARAPBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND name = N'IX_MF_ARAPBill_DeptID') 
	CREATE  INDEX IX_MF_ARAPBill_DeptID on MF_ARAPBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill]') AND name = N'IX_MF_ARAPBill_ElyID') 
	CREATE  INDEX IX_MF_ARAPBill_ElyID on MF_ARAPBill ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_ARAPBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_ARAPBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_ARAPBill_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_ARAPBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_PaidTotal] DEFAULT (0),
	[Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_ARAPBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND name = N'IXC_MF_ARAPBill_His_BillCode') 
	CREATE  INDEX IXC_MF_ARAPBill_His_BillCode on MF_ARAPBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND name = N'IXC_MF_ARAPBill_His_BillDate') 
	CREATE  INDEX IXC_MF_ARAPBill_His_BillDate on MF_ARAPBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND name = N'IXC_MF_ARAPBill_His_CreateTime') 
	CREATE  INDEX IXC_MF_ARAPBill_His_CreateTime on MF_ARAPBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND name = N'IXC_MF_ARAPBill_His_PosTime') 
	CREATE  INDEX IXC_MF_ARAPBill_His_PosTime on MF_ARAPBill_His ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND name = N'IX_MF_ARAPBill_His_BTypeID') 
	CREATE  INDEX IX_MF_ARAPBill_His_BTypeID on MF_ARAPBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND name = N'IX_MF_ARAPBill_His_DeptID') 
	CREATE  INDEX IX_MF_ARAPBill_His_DeptID on MF_ARAPBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPBill_His]') AND name = N'IX_MF_ARAPBill_His_ElyID') 
	CREATE  INDEX IX_MF_ARAPBill_His_ElyID on MF_ARAPBill_His ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_ARAPBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_ARAPBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_ARAPBill_His_AuditStatus] DEFAULT (0) 





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_ARAPDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_ARAPDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_ARAPDetail_Total] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_MF_ARAPDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPDetail]') AND name = N'IXC_MF_ARAPDetail_BillNo') 
	CREATE CLUSTERED INDEX IXC_MF_ARAPDetail_BillNo on MF_ARAPDetail ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPDetail]') AND name = N'IXC_MF_ARAPDetail_FinanceID') 
	CREATE INDEX IXC_MF_ARAPDetail_FinanceID on MF_ARAPDetail ([FinanceID]) WITH (FILLFACTOR = 90);


------------------------------------------修改字段区域开始-----------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[MF_ARAPDetail]') and  name = 'Remark' and Length=100)
BEGIN
   ALTER TABLE MF_ARAPDetail
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO


------------------------------------------修改字段区域结束-----------------------------------------------



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_ARAPDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_ARAPDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_ARAPDetail_His_Total] DEFAULT (0),
    [Remark] [varchar](100) NULL,
    CONSTRAINT [PK_MF_ARAPDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END



IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPDetail_His]') AND name = N'IXC_MF_ARAPDetail_His_BillNo') 
	CREATE CLUSTERED INDEX IXC_MF_ARAPDetail_His_BillNo on MF_ARAPDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_ARAPDetail_His]') AND name = N'IXC_MF_ARAPDetail_His_FinanceID') 
	CREATE INDEX IXC_MF_ARAPDetail_His_FinanceID on MF_ARAPDetail_His ([FinanceID]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_FeeRecBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_BTypeID] DEFAULT (0),
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_FinanceID] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_FeeTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_Total] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_MF_FeeRecBill_IsOS] DEFAULT(0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_FeeRecBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_FeeRecBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IXC_MF_FeeRecBill_BillCode') 
	CREATE  INDEX IXC_MF_FeeRecBill_BillCode on MF_FeeRecBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IXC_MF_FeeRecBill_CreateTime') 
	CREATE  INDEX IXC_MF_FeeRecBill_CreateTime on MF_FeeRecBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IXC_MF_FeeRecBill_PosTime') 
	CREATE  INDEX IXC_MF_FeeRecBill_PosTime on MF_FeeRecBill ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IXC_MF_FeeRecBill_BillDate') 
	CREATE  INDEX IXC_MF_FeeRecBill_BillDate on MF_FeeRecBill ([BillDate]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IX_MF_FeeRecBill_BTypeID') 
	CREATE  INDEX IX_MF_FeeRecBill_BTypeID on MF_FeeRecBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IX_MF_FeeRecBill_DeptID') 
	CREATE  INDEX IX_MF_FeeRecBill_DeptID on MF_FeeRecBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IX_MF_FeeRecBill_ElyID') 
	CREATE  INDEX IX_MF_FeeRecBill_ElyID on MF_FeeRecBill ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill]') AND name = N'IX_MF_FeeRecBill_FinanceID') 
	CREATE  INDEX IX_MF_FeeRecBill_FinanceID on MF_FeeRecBill ([FinanceID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_FeeRecBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_FeeRecBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_FeeRecBill_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_FeeRecBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_BTypeID] DEFAULT (0),
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_FinanceID] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_FeeTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_Total] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_IsOS] DEFAULT(0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_FeeRecBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IXC_MF_FeeRecBill_His_BillCode') 
	CREATE  INDEX IXC_MF_FeeRecBill_His_BillCode on MF_FeeRecBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IXC_MF_FeeRecBill_His_BillDate') 
	CREATE  INDEX IXC_MF_FeeRecBill_His_BillDate on MF_FeeRecBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IXC_MF_FeeRecBill_His_CreateTime') 
	CREATE  INDEX IXC_MF_FeeRecBill_His_CreateTime on MF_FeeRecBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IXC_MF_FeeRecBill_His_PosTime') 
	CREATE  INDEX IXC_MF_FeeRecBill_His_PosTime on MF_FeeRecBill_His ([PosTime]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IX_MF_FeeRecBill_His_BTypeID') 
	CREATE  INDEX IX_MF_FeeRecBill_His_BTypeID on MF_FeeRecBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IX_MF_FeeRecBill_His_DeptID') 
	CREATE  INDEX IX_MF_FeeRecBill_His_DeptID on MF_FeeRecBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IX_MF_FeeRecBill_His_ElyID') 
	CREATE  INDEX IX_MF_FeeRecBill_His_ElyID on MF_FeeRecBill_His ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecBill_His]') AND name = N'IX_MF_FeeRecBill_His_FinanceID') 
	CREATE  INDEX IX_MF_FeeRecBill_His_FinanceID on MF_FeeRecBill_His ([FinanceID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_FeeRecBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_FeeRecBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_FeeRecBill_His_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_FeeRecDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_FeeRecDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecDetail_Total] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_MF_FeeRecDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecDetail]') AND name = N'IXC_MF_FeeRecDetail_BillNo') 
	CREATE CLUSTERED INDEX IXC_MF_FeeRecDetail_BillNo on MF_FeeRecDetail ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecDetail]') AND name = N'IXC_MF_FeeRecDetail_FinanceID') 
	CREATE INDEX IXC_MF_FeeRecDetail_FinanceID on MF_FeeRecDetail ([FinanceID]) WITH (FILLFACTOR = 90);


------------------------------------------修改字段区域开始-----------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[MF_FeeRecDetail]') and  name = 'Remark' and Length=100)
BEGIN
   ALTER TABLE MF_FeeRecDetail
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO


------------------------------------------修改字段区域结束-----------------------------------------------





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_FeeRecDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_FeeRecDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_FeeRecDetail_His_Total] DEFAULT (0),
    [Remark] [varchar](100) NULL,
    CONSTRAINT [PK_MF_FeeRecDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecDetail_His]') AND name = N'IXC_MF_FeeRecDetail_His_BillNo') 
	CREATE CLUSTERED INDEX IXC_MF_FeeRecDetail_His_BillNo on MF_FeeRecDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_FeeRecDetail_His]') AND name = N'IXC_MF_FeeRecDetail_His_FinanceID') 
	CREATE INDEX IXC_MF_FeeRecDetail_His_FinanceID on MF_FeeRecDetail_His ([FinanceID]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PayRecBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [BPTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecBill_BPTotal] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecBill_Privilege] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_PayRecBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_PayRecBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_PayRecBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_PayRecBill_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_PayRecBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_PayRecBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_PayRecBill_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_MF_PayRecBill_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_PayRecBill_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_PayRecBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_PayRecBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND name = N'IXC_MF_PayRecBill_BillCode') 
	CREATE  INDEX IXC_MF_PayRecBill_BillCode on MF_PayRecBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND name = N'IXC_MF_PayRecBill_BillDate') 
	CREATE  INDEX IXC_MF_PayRecBill_BillDate on MF_PayRecBill ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND name = N'IXC_MF_PayRecBill_CreateTime') 
	CREATE  INDEX IXC_MF_PayRecBill_CreateTime on MF_PayRecBill ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND name = N'IXC_MF_PayRecBill_PosTime') 
	CREATE  INDEX IXC_MF_PayRecBill_PosTime on MF_PayRecBill ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND name = N'IX_MF_PayRecBill_BTypeID') 
	CREATE  INDEX IX_MF_PayRecBill_BTypeID on MF_PayRecBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND name = N'IX_MF_PayRecBill_DeptID') 
	CREATE  INDEX IX_MF_PayRecBill_DeptID on MF_PayRecBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill]') AND name = N'IX_MF_PayRecBill_ElyID') 
	CREATE  INDEX IX_MF_PayRecBill_ElyID on MF_PayRecBill ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_PayRecBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_PayRecBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_PayRecBill_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PayRecBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [BPTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_BPTotal] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_Privilege] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_PayRecBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND name = N'IXC_MF_PayRecBill_His_BillCode') 
	CREATE  INDEX IXC_MF_PayRecBill_His_BillCode on MF_PayRecBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND name = N'IXC_MF_PayRecBill_His_BillDate') 
	CREATE  INDEX IXC_MF_PayRecBill_His_BillDate on MF_PayRecBill_His ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND name = N'IXC_MF_PayRecBill_His_CreateTime') 
	CREATE  INDEX IXC_MF_PayRecBill_His_CreateTime on MF_PayRecBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND name = N'IXC_MF_PayRecBill_His_PosTime') 
	CREATE  INDEX IXC_MF_PayRecBill_His_PosTime on MF_PayRecBill_His ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND name = N'IX_MF_PayRecBill_His_BTypeID') 
	CREATE  INDEX IX_MF_PayRecBill_His_BTypeID on MF_PayRecBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND name = N'IX_MF_PayRecBill_His_DeptID') 
	CREATE  INDEX IX_MF_PayRecBill_His_DeptID on MF_PayRecBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecBill_His]') AND name = N'IX_MF_PayRecBill_His_ElyID') 
	CREATE  INDEX IX_MF_PayRecBill_His_ElyID on MF_PayRecBill_His ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_PayRecBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_PayRecBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_PayRecBill_His_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PayRecDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PayRecDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecDetail_Total] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_MF_PayRecDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecDetail]') AND name = N'IXC_MF_PayRecDetail_BillNo') 
	CREATE CLUSTERED  INDEX IXC_MF_PayRecDetail_BillNo on MF_PayRecDetail ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecDetail]') AND name = N'IXC_MF_PayRecDetail_FinanceID') 
	CREATE INDEX IXC_MF_PayRecDetail_FinanceID on MF_PayRecDetail ([FinanceID]) WITH (FILLFACTOR = 90);
	
	
------------------------------------------修改字段区域开始-----------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[MF_PayRecDetail]') and  name = 'Remark' and Length=100)
BEGIN
   ALTER TABLE MF_PayRecDetail
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO


------------------------------------------修改字段区域结束-----------------------------------------------





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PayRecDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PayRecDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecDetail_His_Total] DEFAULT (0),
    [Remark] [varchar](100) NULL,
    CONSTRAINT [PK_MF_PayRecDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecDetail_His]') AND name = N'IXC_MF_PayRecDetail_His_BillNo') 
	CREATE CLUSTERED  INDEX IXC_MF_PayRecDetail_His_BillNo on MF_PayRecDetail_His ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecDetail_His]') AND name = N'IXC_MF_PayRecDetail_His_FinanceID') 
	CREATE INDEX IXC_MF_PayRecDetail_His_FinanceID on MF_PayRecDetail_His ([FinanceID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PayRecList]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PayRecList]
(
    [LID] [bigint] IDENTITY(1,1) NOT NULL,
    [PayRecBillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecList_PaidTotal] DEFAULT (0),
    [Tag] [TinyINT] NOT NULL CONSTRAINT [DF_MF_PayRecList_Tag] DEFAULT (0),
    CONSTRAINT [PK_MF_PayRecList] PRIMARY KEY NONCLUSTERED ([LID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecList]') AND name = N'IXC_MF_PayRecList_PayRecBillNo') 
	CREATE CLUSTERED  INDEX IXC_MF_PayRecList_PayRecBillNo on MF_PayRecList ([PayRecBillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecList]') AND name = N'IXC_MF_PayRecList_BillTypeBillNo') 
	CREATE INDEX IXC_MF_PayRecList_BillTypeBillNo on MF_PayRecList ([BillTypeID],[BillNo]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PayRecList_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PayRecList_His]
(
    [LID] [bigint]  NOT NULL,
    [PayRecBillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PayRecList_His_PaidTotal] DEFAULT (0),
    [Tag] [TinyINt] NOT NULL,
    CONSTRAINT [PK_MF_PayRecList_His] PRIMARY KEY NONCLUSTERED ([LID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecList_His]') AND name = N'IXC_MF_PayRecList_His_PayRecBillNo') 
	CREATE CLUSTERED  INDEX IXC_MF_PayRecList_His_PayRecBillNo on MF_PayRecList_His ([PayRecBillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PayRecList_His]') AND name = N'IXC_MF_PayRecList_His_BillTypeBillNo') 
	CREATE INDEX IXC_MF_PayRecList_His_BillTypeBillNo on MF_PayRecList_His ([BillTypeID],[BillNo]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PchInvoiceBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [datetime] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [InvoiceCode] [varchar](100) NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_InvoiceCode] DEFAULT '',
    [InvoiceType] [tinyint] NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_InvoiceType] DEFAULT (0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_InvoiceTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_Description] DEFAULT '',
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_PchInvoiceBill_IsDraft] DEFAULT (1),
    CONSTRAINT [PK_MF_PchInvoiceBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND name = N'IXC_MF_PchInvoiceBill_BillCode') 
	CREATE INDEX IXC_MF_PchInvoiceBill_BillCode on MF_PchInvoiceBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND name = N'IXC_MF_PchInvoiceBill_CreateTime') 
	CREATE INDEX IXC_MF_PchInvoiceBill_CreateTime on MF_PchInvoiceBill ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND name = N'IXC_MF_PchInvoiceBill_PosTime') 
	CREATE INDEX IXC_MF_PchInvoiceBill_PosTime on MF_PchInvoiceBill ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND name = N'IXC_MF_PchInvoiceBill_BillDate') 
	CREATE INDEX IXC_MF_PchInvoiceBill_BillDate on MF_PchInvoiceBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND name = N'IX_MF_PchInvoiceBill_BTypeID') 
	CREATE  INDEX IX_MF_PchInvoiceBill_BTypeID on MF_PchInvoiceBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND name = N'IX_MF_PchInvoiceBill_DeptID') 
	CREATE  INDEX IX_MF_PchInvoiceBill_DeptID on MF_PchInvoiceBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill]') AND name = N'IX_MF_PchInvoiceBill_ElyID') 
	CREATE  INDEX IX_MF_PchInvoiceBill_ElyID on MF_PchInvoiceBill ([ElyID]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PchInvoiceBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [datetime] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [InvoiceCode] [varchar](100) NOT NULL,
    [InvoiceType] [tinyint] NOT NULL,
    [InvoiceMode] [tinyint] NOT NULL,
    [InvoiceTotal] DECIMAL(20,8) NOT NULL,
    [Creator] [int] NOT NULL,
    [CreateTime] [datetime] NOT NULL,
    [PosElyID] [int] NOT NULL,
    [PosTime] [datetime] NOT NULL,
    [Summary] [varchar](256) NOT NULL,
    [Description] [varchar](100) NOT NULL,
    [IsDraft] [bit] NOT NULL,
    CONSTRAINT [PK_MF_PchInvoiceBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND name = N'IXC_MF_PchInvoiceBill_His_BillCode') 
	CREATE INDEX IXC_MF_PchInvoiceBill_His_BillCode on MF_PchInvoiceBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND name = N'IXC_MF_PchInvoiceBill_His_CreateTime') 
	CREATE INDEX IXC_MF_PchInvoiceBill_His_CreateTime on MF_PchInvoiceBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND name = N'IXC_MF_PchInvoiceBill_His_PosTime') 
	CREATE INDEX IXC_MF_PchInvoiceBill_His_PosTime on MF_PchInvoiceBill_His ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND name = N'IXC_MF_PchInvoiceBill_His_BillDate') 
	CREATE INDEX IXC_MF_PchInvoiceBill_His_BillDate on MF_PchInvoiceBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND name = N'IX_MF_PchInvoiceBill_His_BTypeID') 
	CREATE  INDEX IX_MF_PchInvoiceBill_His_BTypeID on MF_PchInvoiceBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND name = N'IX_MF_PchInvoiceBill_His_DeptID') 
	CREATE  INDEX IX_MF_PchInvoiceBill_His_DeptID on MF_PchInvoiceBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceBill_His]') AND name = N'IX_MF_PchInvoiceBill_His_ElyID') 
	CREATE  INDEX IX_MF_PchInvoiceBill_His_ElyID on MF_PchInvoiceBill_His ([ElyID]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceContent]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PchInvoiceContent]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [GoodsMsg] [varchar](100) NOT NULL CONSTRAINT [DF_MF_PchInvoiceContent_GoodsMsg] DEFAULT '',
    [InvoiceTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PchInvoiceContent_InvoiceTotal] DEFAULT (0),
    [Remark] [varchar](256) NOT NULL CONSTRAINT [DF_MF_PchInvoiceContent_Remark] DEFAULT '',
    CONSTRAINT [PK_MF_PchInvoiceContent] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceContent]') AND name = N'IXC_MF_PchInvoiceContent_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_PchInvoiceContent_BillDate on MF_PchInvoiceContent ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceContent]') AND name = N'IXC_MF_PchInvoiceContent_BillNo') 
	CREATE  INDEX IXC_MF_PchInvoiceContent_BillNo on MF_PchInvoiceContent ([BillNo]) WITH (FILLFACTOR = 90);

--修改表结构长度
IF EXISTS(SELECT * FROM syscolumns WHERE id = object_id(N'[dbo].[MF_PchInvoiceContent]') and  name = 'Remark' and length=100)
BEGIN
   ALTER TABLE MF_PchInvoiceContent
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceContent_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PchInvoiceContent_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [GoodsMsg] [varchar](100) NOT NULL,
    [InvoiceTotal] DECIMAL(20,8) NOT NULL,
    [Remark] [varchar](256) NOT NULL,
    CONSTRAINT [PK_MF_PchInvoiceContent_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceContent_His]') AND name = N'IXC_MF_PchInvoiceContent_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_PchInvoiceContent_His_BillDate on MF_PchInvoiceContent_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceContent_His]') AND name = N'IXC_MF_PchInvoiceContent_His_BillNo') 
	CREATE  INDEX IXC_MF_PchInvoiceContent_His_BillNo on MF_PchInvoiceContent_His ([BillNo]) WITH (FILLFACTOR = 90);

--修改表结构长度
IF EXISTS(SELECT * FROM syscolumns WHERE id = object_id(N'[dbo].[MF_PchInvoiceContent_His]') and  name = 'Remark' and length=100)
BEGIN
   ALTER TABLE MF_PchInvoiceContent_His
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PchInvoiceDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [PchBillNo] [bigint] NOT NULL CONSTRAINT [DF_MF_PchInvoiceDetail_PchBillNo] DEFAULT (0),
    [PchDID] [bigint] NOT NULL CONSTRAINT [DF_MF_PchInvoiceDetail_PchDID] DEFAULT (0),
    [BillType] [int] NOT NULL CONSTRAINT [DF_MF_PchInvoiceDetail_BillType] DEFAULT (0),
    [InvoiceQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PchInvoiceDetail_InvoiceQty] DEFAULT (0),
    [InvoiceTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_PchInvoiceDetail_InvoiceTotal] DEFAULT (0),
    [Remark] [varchar](100) NOT NULL CONSTRAINT [DF_MF_PchInvoiceDetail_Remark] DEFAULT '',
    CONSTRAINT [PK_MF_PchInvoiceDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceDetail]') AND name = N'IXC_MF_PchInvoiceDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_PchInvoiceDetail_BillDate on MF_PchInvoiceDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceDetail]') AND name = N'IXC_MF_PchInvoiceDetail_BillNo') 
	CREATE  INDEX IXC_MF_PchInvoiceDetail_BillNo on MF_PchInvoiceDetail ([BillNo]) WITH (FILLFACTOR = 90);


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MF_PchInvoiceDetail' AND a.Name='Remark' AND a.[length] = 100
    )
BEGIN
	ALTER TABLE MF_PchInvoiceDetail 
	ALTER COLUMN Remark VARCHAR(256)
END

GO


       



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_PchInvoiceDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [PchBillNo] [bigint] NOT NULL,
    [PchDID] [bigint] NOT NULL,
    [BillType] [int] NOT NULL,
    [InvoiceQty] DECIMAL(20,8) NOT NULL,
    [InvoiceTotal] DECIMAL(20,8) NOT NULL,
    [Remark] [varchar](100) NOT NULL,
    CONSTRAINT [PK_MF_PchInvoiceDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceDetail_His]') AND name = N'IXC_MF_PchInvoiceDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_PchInvoiceDetail_His_BillDate on MF_PchInvoiceDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_PchInvoiceDetail_His]') AND name = N'IXC_MF_PchInvoiceDetail_His_BillNo') 
	CREATE  INDEX IXC_MF_PchInvoiceDetail_His_BillNo on MF_PchInvoiceDetail_His ([BillNo]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_SellInvoiceBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [datetime] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [InvoiceCode] [varchar](100) NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_InvoiceCode] DEFAULT '',
    [InvoiceType] [tinyint] NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_InvoiceType] DEFAULT (0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_InvoiceTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_Description] DEFAULT '',
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_SellInvoiceBill_IsDraft] DEFAULT (1),
    CONSTRAINT [PK_MF_SellInvoiceBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND name = N'IXC_MF_SellInvoiceBill_BillCode') 
	CREATE INDEX IXC_MF_SellInvoiceBill_BillCode on MF_SellInvoiceBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND name = N'IXC_MF_SellInvoiceBill_CreateTime') 
	CREATE INDEX IXC_MF_SellInvoiceBill_CreateTime on MF_SellInvoiceBill ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND name = N'IXC_MF_SellInvoiceBill_PosTime') 
	CREATE INDEX IXC_MF_SellInvoiceBill_PosTime on MF_SellInvoiceBill ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND name = N'IXC_MF_SellInvoiceBill_BillDate') 
	CREATE INDEX IXC_MF_SellInvoiceBill_BillDate on MF_SellInvoiceBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND name = N'IX_MF_SellInvoiceBill_BTypeID') 
	CREATE  INDEX IX_MF_SellInvoiceBill_BTypeID on MF_SellInvoiceBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND name = N'IX_MF_SellInvoiceBill_DeptID') 
	CREATE  INDEX IX_MF_SellInvoiceBill_DeptID on MF_SellInvoiceBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill]') AND name = N'IX_MF_SellInvoiceBill_ElyID') 
	CREATE  INDEX IX_MF_SellInvoiceBill_ElyID on MF_SellInvoiceBill ([ElyID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_SellInvoiceBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [datetime] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [InvoiceCode] [varchar](100) NOT NULL,
    [InvoiceType] [tinyint] NOT NULL,
    [InvoiceMode] [tinyint] NOT NULL,
    [InvoiceTotal] DECIMAL(20,8) NOT NULL,
    [Creator] [int] NOT NULL,
    [CreateTime] [datetime] NOT NULL,
    [PosElyID] [int] NOT NULL,
    [PosTime] [datetime] NOT NULL,
    [Summary] [varchar](256) NOT NULL,
    [Description] [varchar](100) NOT NULL,
    [IsDraft] [bit] NOT NULL,
    CONSTRAINT [PK_MF_SellInvoiceBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND name = N'IXC_MF_SellInvoiceBill_His_BillCode') 
	CREATE INDEX IXC_MF_SellInvoiceBill_His_BillCode on MF_SellInvoiceBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND name = N'IXC_MF_SellInvoiceBill_His_CreateTime') 
	CREATE INDEX IXC_MF_SellInvoiceBill_His_CreateTime on MF_SellInvoiceBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND name = N'IXC_MF_SellInvoiceBill_His_PosTime') 
	CREATE INDEX IXC_MF_SellInvoiceBill_His_PosTime on MF_SellInvoiceBill_His ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND name = N'IXC_MF_SellInvoiceBill_His_BillDate') 
	CREATE INDEX IXC_MF_SellInvoiceBill_His_BillDate on MF_SellInvoiceBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND name = N'IX_MF_SellInvoiceBill_His_BTypeID') 
	CREATE  INDEX IX_MF_SellInvoiceBill_His_BTypeID on MF_SellInvoiceBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND name = N'IX_MF_SellInvoiceBill_His_DeptID') 
	CREATE  INDEX IX_MF_SellInvoiceBill_His_DeptID on MF_SellInvoiceBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceBill_His]') AND name = N'IX_MF_SellInvoiceBill_His_ElyID') 
	CREATE  INDEX IX_MF_SellInvoiceBill_His_ElyID on MF_SellInvoiceBill_His ([ElyID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceContent]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_SellInvoiceContent]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [GoodsMsg] [varchar](100) NOT NULL CONSTRAINT [DF_MF_SellInvoiceContent_GoodsMsg] DEFAULT '',
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_MF_SellInvoiceContent_InvoiceTotal] DEFAULT (0),
    [Remark] [varchar](256) NOT NULL CONSTRAINT [DF_MF_SellInvoiceContent_Remark] DEFAULT '',
    CONSTRAINT [PK_MF_SellInvoiceContent] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceContent]') AND name = N'IXC_MF_SellInvoiceContent_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_SellInvoiceContent_BillDate on MF_SellInvoiceContent ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceContent]') AND name = N'IXC_MF_SellInvoiceContent_BillNo') 
	CREATE  INDEX IXC_MF_SellInvoiceContent_BillNo on MF_SellInvoiceContent ([BillNo]) WITH (FILLFACTOR = 90);

--修改表结构长度
IF EXISTS(SELECT * FROM syscolumns WHERE id = object_id(N'[dbo].[MF_SellInvoiceContent]') and  name = 'Remark' and length=100)
BEGIN
   ALTER TABLE MF_SellInvoiceContent
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceContent_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_SellInvoiceContent_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [GoodsMsg] [varchar](100) NOT NULL,
    [InvoiceTotal] DECIMAL(20,8) NOT NULL,
    [Remark] [varchar](256) NOT NULL,
    CONSTRAINT [PK_MF_SellInvoiceContent_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceContent_His]') AND name = N'IXC_MF_SellInvoiceContent_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_SellInvoiceContent_His_BillDate on MF_SellInvoiceContent_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceContent_His]') AND name = N'IXC_MF_SellInvoiceContent_His_BillNo') 
	CREATE  INDEX IXC_MF_SellInvoiceContent_His_BillNo on MF_SellInvoiceContent_His ([BillNo]) WITH (FILLFACTOR = 90);
	
--修改表结构长度
IF EXISTS(SELECT * FROM syscolumns WHERE id = object_id(N'[dbo].[MF_SellInvoiceContent_His]') and  name = 'Remark' and length=100)
BEGIN
   ALTER TABLE MF_SellInvoiceContent_His
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_SellInvoiceDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [SellBillNo] [bigint] NOT NULL CONSTRAINT [DF_MF_SellInvoiceDetail_SellBillNo] DEFAULT (0),
    [SellDID] [bigint] NOT NULL CONSTRAINT [DF_MF_SellInvoiceDetail_SellDID] DEFAULT (0),
    [BillType] [int] NOT NULL CONSTRAINT [DF_MF_SellInvoiceDetail_BillType] DEFAULT (0),
    [InvoiceQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_SellInvoiceDetail_InvoiceQty] DEFAULT (0),
    [InvoiceTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_SellInvoiceDetail_InvoiceTotal] DEFAULT (0),
    [Remark] [varchar](100) NOT NULL CONSTRAINT [DF_MF_SellInvoiceDetail_Remark] DEFAULT '',
    CONSTRAINT [PK_MF_SellInvoiceDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceDetail]') AND name = N'IXC_MF_SellInvoiceDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_SellInvoiceDetail_BillDate on MF_SellInvoiceDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceDetail]') AND name = N'IXC_MF_SellInvoiceDetail_BillNo') 
	CREATE  INDEX IXC_MF_SellInvoiceDetail_BillNo on MF_SellInvoiceDetail ([BillNo]) WITH (FILLFACTOR = 90);


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='MF_SellInvoiceDetail' AND a.Name='Remark' AND a.[length] = 100
    )
BEGIN
	ALTER TABLE MF_SellInvoiceDetail 
	ALTER COLUMN Remark VARCHAR(256)
END

GO



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_SellInvoiceDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [SellBillNo] [bigint] NOT NULL,
    [SellDID] [bigint] NOT NULL,
    [BillType] [int] NOT NULL,
    [InvoiceQty] DECIMAL(20,8) NOT NULL,
    [InvoiceTotal] DECIMAL(20,8) NOT NULL,
    [Remark] [varchar](100) NOT NULL,
    CONSTRAINT [PK_MF_SellInvoiceDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceDetail_His]') AND name = N'IXC_MF_SellInvoiceDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_MF_SellInvoiceDetail_His_BillDate on MF_SellInvoiceDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_SellInvoiceDetail_His]') AND name = N'IXC_MF_SellInvoiceDetail_His_BillNo') 
	CREATE  INDEX IXC_MF_SellInvoiceDetail_His_BillNo on MF_SellInvoiceDetail_His ([BillNo]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_TransferBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_FinanceID] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferBill_PayTotal] DEFAULT (0),
    [FeeFinanceID] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_FeeFinanceID] DEFAULT (0),
    [FeeTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferBill_FeeTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_TransferBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_TransferBill_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_TransferBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_TransferBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_TransferBill_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_TransferBill_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_TransferBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_TransferBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND name = N'IXC_MF_TransferBill_BillCode') 
	CREATE  INDEX IXC_MF_TransferBill_BillCode on MF_TransferBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND name = N'IXC_MF_TransferBill_BillDate') 
	CREATE  INDEX IXC_MF_TransferBill_BillDate on MF_TransferBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND name = N'IXC_MF_TransferBill_CreateTime') 
	CREATE  INDEX IXC_MF_TransferBill_CreateTime on MF_TransferBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND name = N'IXC_MF_TransferBill_PosTime') 
	CREATE  INDEX IXC_MF_TransferBill_PosTime on MF_TransferBill ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND name = N'IX_MF_TransferBill_DeptID') 
	CREATE  INDEX IX_MF_TransferBill_DeptID on MF_TransferBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND name = N'IX_MF_TransferBill_ElyID') 
	CREATE  INDEX IX_MF_TransferBill_ElyID on MF_TransferBill ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill]') AND name = N'IX_MF_TransferBill_FinanceID') 
	CREATE  INDEX IX_MF_TransferBill_FinanceID on MF_TransferBill ([FinanceID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_TransferBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_TransferBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_TransferBill_AuditStatus] DEFAULT (0) 





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_TransferBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_FinanceID] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferBill_His_PayTotal] DEFAULT (0),
    [FeeFinanceID] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_FeeFinanceID] DEFAULT (0),
    [FeeTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferBill_His_FeeTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_MF_TransferBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_MF_TransferBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_MF_TransferBill_His_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_MF_TransferBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_MF_TransferBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND name = N'IXC_MF_TransferBill_His_BillCode') 
	CREATE  INDEX IXC_MF_TransferBill_His_BillCode on MF_TransferBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND name = N'IXC_MF_TransferBill_His_BillDate') 
	CREATE  INDEX IXC_MF_TransferBill_His_BillDate on MF_TransferBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND name = N'IXC_MF_TransferBill_His_CreateTime') 
	CREATE  INDEX IXC_MF_TransferBill_His_CreateTime on MF_TransferBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND name = N'IXC_MF_TransferBill_His_PosTime') 
	CREATE  INDEX IXC_MF_TransferBill_His_PosTime on MF_TransferBill_His ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND name = N'IX_MF_TransferBill_His_DeptID') 
	CREATE  INDEX IX_MF_TransferBill_His_DeptID on MF_TransferBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND name = N'IX_MF_TransferBill_His_ElyID') 
	CREATE  INDEX IX_MF_TransferBill_His_ElyID on MF_TransferBill_His ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferBill_His]') AND name = N'IX_MF_TransferBill_His_FinanceID') 
	CREATE  INDEX IX_MF_TransferBill_His_FinanceID on MF_TransferBill_His ([FinanceID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='MF_TransferBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.MF_TransferBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_MF_TransferBill_His_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_TransferDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_TransferDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferDetail_Total] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_MF_TransferDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferDetail]') AND name = N'IX_MF_TransferDetail_BillNo') 
	CREATE CLUSTERED  INDEX IX_MF_TransferDetail_BillNo on MF_TransferDetail ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferDetail]') AND name = N'IX_MF_TransferDetail_FinanceID') 
	CREATE  INDEX IX_MF_TransferDetail_FinanceID on MF_TransferDetail ([FinanceID]) WITH (FILLFACTOR = 90);


------------------------------------------修改字段区域开始-----------------------------------------------
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[MF_TransferDetail]') and  name = 'Remark' and Length=100)
BEGIN
   ALTER TABLE MF_TransferDetail
      ALTER COLUMN Remark VARCHAR(256) NULL
END
GO


------------------------------------------修改字段区域结束-----------------------------------------------





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[MF_TransferDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [MF_TransferDetail_His]
(
    [DID] [bigint]  NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_MF_TransferDetail_His_Total] DEFAULT (0),
    [Remark] [varchar](100) NULL,
    CONSTRAINT [PK_MF_TransferDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferDetail_His]') AND name = N'IX_MF_TransferDetail_His_BillNo') 
	CREATE CLUSTERED  INDEX IX_MF_TransferDetail_His_BillNo on MF_TransferDetail_His ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[MF_TransferDetail_His]') AND name = N'IX_MF_TransferDetail_His_FinanceID') 
	CREATE  INDEX IX_MF_TransferDetail_His_FinanceID on MF_TransferDetail_His ([FinanceID]) WITH (FILLFACTOR = 90);





------------------------店帐通订单与本地单据对应表------------------------

IF NOT EXISTS(select * from sysobjects where id = object_id(N'[OS_BillRelation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	BEGIN
		CREATE TABLE [OS_BillRelation]
		(
			[Id]			int	IDENTITY(1,1) NOT NULL,
			[OSBillNo]		BIGINT NOT NULL,
			[OSOrderType]	TINYINT NOT NULL,
			[BillNo]		NUMERIC(18,0) NOT NULL,
			[BillTypeID]	INT NOT NULL
		) ON [PRIMARY]
	 END
GO




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_Company]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_Company
(
	CompanyName		VARCHAR(50) NOT NULL,
	AppKey			DECIMAL(20,0) NOT NULL,
	AppSecret		VARCHAR(200) NOT NULL,
	LoginFactor		BIGINT NOT NULL CONSTRAINT [DF_OS_Company_LoginFactor] DEFAULT(0)
	CONSTRAINT [PK_OS_Company] PRIMARY KEY NONCLUSTERED ([CompanyName])
)
END
IF  EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_Company' AND a.Name='PassWord')
    ALTER TABLE OS_Company drop COLUMN [PassWord] --4.0之后，去掉password的密码字段
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_FreightBill]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_FreightBill
(
	BillNo			BIGINT NOT NULL,
	BillCode		VARCHAR(50)  NOT NULL,
	BillDate		DATE NOT NULL,
	ElyID			INT NOT NULL,
	Creator			INT NOT NULL,
	LogistBTypeCode	VARCHAR(100) NOT NULL,
	FreightFeeTotal	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_FreightBill_FreightFeeTotal] DEFAULT(0),
	GatherTotal		DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_FreightBill_GatherTotal] DEFAULT(0),
	SettleDate		DATETIME NOT NULL,
	Summary			VARCHAR(256)  NULL  DEFAULT(''),
	Description		VARCHAR(256)  NULL  DEFAULT(''),
	IsCreate		TINYINT NOT NULL CONSTRAINT [DF_OS_FreightBill_IsCreate]  DEFAULT(0),
	HasError		BIT NOT NULL CONSTRAINT [DF_OS_FreightBill_HasError]  DEFAULT(0)
	CONSTRAINT [PK_OS_FreightBill] PRIMARY KEY NONCLUSTERED (BillNo)
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_FreightBill]') AND name = N'IXC_OS_FreightBill_BillDate') 
	CREATE CLUSTERED  INDEX IXC_OS_FreightBill_BillDate on OS_FreightBill (BillDate) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_FreightBillAll]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_FreightBillAll
(
	BillNo			BIGINT NOT NULL,
	BillCode		VARCHAR(50)  NOT NULL,
	BillDate		DATE NOT NULL,
	ElyID			INT NOT NULL,
	Creator			INT NOT NULL,
	LogistBTypeCode	VARCHAR(100) NOT NULL,
	FreightFeeTotal	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_FreightBillAll_FreightFeeTotal] DEFAULT(0),
	GatherTotal		DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_FreightBillOS_FreightBillAll_GatherTotal] DEFAULT(0),
	SettleDate		DATETIME NOT NULL,
	Summary			VARCHAR(256)  NULL  DEFAULT(''),
	Description		VARCHAR(256)  NULL  DEFAULT(''),
	IsCreate		TINYINT NOT NULL CONSTRAINT [DF_OS_FreightBillAll_IsCreate]  DEFAULT(0),
	HasError		BIT NOT NULL CONSTRAINT [DF_OS_FreightBill_His_HasError]  DEFAULT(0)
	CONSTRAINT [PK_OS_FreightBillAll] PRIMARY KEY NONCLUSTERED (BillNo)
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_FreightBillAll]') AND name = N'IXC_OS_FreightBillAll_BillDate') 
	CREATE CLUSTERED  INDEX IXC_OS_FreightBillAll_BillDate on OS_FreightBillAll (BillDate) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_GoodsRelation]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_GoodsRelation
(
	ID				INT IDENTITY(1,1) NOT NULL, 
	MerchantCode	VARCHAR(100) NOT NULL,
	GoodsID			INT NOT NULL,
	UnitID			INT NOT NULL ,
	Ppt1ID			INT NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Ppt1ID] DEFAULT(0),
	Ppt2ID			INT NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Ppt2ID] DEFAULT(0),
	CONSTRAINT [PK_OS_GoodsRelation] PRIMARY KEY NONCLUSTERED ([ID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_GoodsRelation]') AND name = N'IXC_OS_GoodsRelation_MerchantCode') 
	CREATE NONCLUSTERED  INDEX IXC_OS_GoodsRelation_MerchantCode on OS_GoodsRelation (MerchantCode) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_GoodsRelation_Import]') AND type in (N'U'))
BEGIN
CREATE TABLE [OS_GoodsRelation_Import]
(
    [ImportID] [int] IDENTITY(1,1) NOT NULL,
    [OSGoodsName] [varchar](100) NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_OSGoodsName] DEFAULT '',
    [OSGoodsPpt] [varchar](100) NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_OSGoodsPpt] DEFAULT '',
    [GoodsID] [bigint] NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_GoodsID] DEFAULT (0),
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_Ppt2ID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_UnitID] DEFAULT (0),
    [MerchantCode] [varchar](100) NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_MerchantCode] DEFAULT '',
    [ElyID] [int] NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_ElyID] DEFAULT (0),
    [SuiteCode] [varchar](50) NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_SuiteCode] DEFAULT '',
    CONSTRAINT [PK_OS_GoodsRelation_Import] PRIMARY KEY NONCLUSTERED ([ImportID])
)
END

IF NOT EXISTS (SELECT 1 FROM SYS.OBJECTS O INNER JOIN SYS.COLUMNS C ON O.OBJECT_ID = C.OBJECT_ID WHERE O.NAME = 'OS_GoodsRelation_Import' AND C.NAME = 'SuiteCode')
	ALTER TABLE dbo.OS_GoodsRelation_Import ADD [SuiteCode] [varchar](50) NOT NULL CONSTRAINT [DF_OS_GoodsRelation_Import_SuiteCode] DEFAULT ''





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OS_GoodsSuite]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OS_GoodsSuite]
(
    [SuiteID] [int] IDENTITY(1,1) NOT NULL,
    [SuiteCode] [varchar](50) NOT NULL CONSTRAINT [DF_OS_GoodsSuite_SuiteCode] DEFAULT '',
    [SuiteName] [varchar](100) NOT NULL CONSTRAINT [DF_OS_GoodsSuite_SuiteName] DEFAULT '',
    [Remark] [varchar](200) NOT NULL CONSTRAINT [DF_OS_GoodsSuite_Remark] DEFAULT '',
    CONSTRAINT [PK_OS_GoodsSuite] PRIMARY KEY NONCLUSTERED ([SuiteID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_OrderBill]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_OrderBill
(
	BillNo			BIGINT NOT NULL,
	BillType		TINYINT NOT NULL,
	BillCode		VARCHAR(50)  NOT NULL,
	BillDate		DATE NOT NULL,
	ShopID			BIGINT NOT NULL,
	ElyID			INT NOT NULL,
	WhsID			INT NOT NULL,
	Summary			VARCHAR(256) NOT NULL  CONSTRAINT [DF_OS_OrderBill_Summary] DEFAULT(''),
	Description		VARCHAR(256) NOT NULL  CONSTRAINT [DF_OS_OrderBill_Description] DEFAULT(''),
	BillQty			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBill_BillQty] DEFAULT(0),
	Total			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBill_Total] DEFAULT(0),
	MallFee			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBill_MallFee] DEFAULT(0),
	CodFee			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBill_CodFee] DEFAULT(0),
	LogistBTypeCode	VARCHAR(50) NOT NULL CONSTRAINT [DF_OS_OrderBill_LogistBTypeID] DEFAULT(''),
	FreightBillNo	VARCHAR(50) NOT NULL  CONSTRAINT [DF_OS_OrderBill_FreightBillNo] DEFAULT(''),
	Freight			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBill_Freight] DEFAULT(0),
	PaidFreight		DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBill_PaidFreight] DEFAULT(0),
	BuyerAccount	VARCHAR(50) NOT NULL,
	ContactWay		VARCHAR(50) NOT NULL,
	Receiver		VARCHAR(50) NOT NULL,
	Address			VARCHAR(200) NOT NULL,
	BuyerMsg		VARCHAR(800)  NULL,
	SaleComment		VARCHAR(800)  NULL,
	BackReason		VARCHAR(256)  NULL,
	SrcSendBillNo	BIGINT NOT NULL CONSTRAINT [DF_OS_OrderBill_SrcSendBillNo] DEFAULT(0),
	BackType		INT  NULL,
	DestSendBillNo	BIGINT NOT NULL CONSTRAINT [DF_OS_OrderBill_DestSendBillNo] DEFAULT(0),
	IsCreate		TINYINT NOT NULL CONSTRAINT [DF_OS_OrderBill_IsCreate] DEFAULT(0),
	HasError		BIT NOT NULL CONSTRAINT [DF_OS_OrderBill_HasError] DEFAULT(0),
	[CreateTime]    date NOT NULL,
    [ReceiverProvince] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBill_ReceiverProvince] DEFAULT '',
    [ReceiverCity] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBill_ReceiverCity] DEFAULT '',
    [ReceiverDistrict] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBill_ReceiverDistrict] DEFAULT '',
    [Weight] [decimal](18,4) NOT NULL CONSTRAINT [DF_OS_OrderBill_Weight] DEFAULT (0),
	PICID			INT NOT NULL CONSTRAINT [DF_OS_OrderBill_PICID] DEFAULT (0),
    [OSBillCode] [varchar](100) NOT NULL CONSTRAINT [DF_OS_OrderBill_OSBillCode] DEFAULT '',
	CONSTRAINT [PK_OS_OrderBill] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_OrderBill]') AND name = N'IXC_OS_OrderBill_BillDate') 
	CREATE CLUSTERED INDEX IXC_OS_OrderBill_BillDate on OS_OrderBill ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBill' AND a.Name='CreateTime')
	BEGIN
		ALTER TABLE OS_OrderBill ADD CreateTime DATE NULL
		EXEC sp_executesql N'UPDATE OS_OrderBill SET CreateTime = BillDate WHERE CreateTime IS NULL'
		ALTER TABLE OS_OrderBill ALTER COLUMN CreateTime DATE NOT NULL
	END
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBill' AND a.Name='ReceiverProvince')
	ALTER TABLE OS_OrderBill ADD [ReceiverProvince] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBill_ReceiverProvince] DEFAULT ''
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBill' AND a.Name='ReceiverCity')
	ALTER TABLE OS_OrderBill ADD [ReceiverCity] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBill_ReceiverCity] DEFAULT ''
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBill' AND a.Name='ReceiverDistrict')
	ALTER TABLE OS_OrderBill ADD [ReceiverDistrict] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBill_ReceiverDistrict] DEFAULT ''
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBill' AND a.Name='Weight')
	ALTER TABLE OS_OrderBill ADD [Weight] [decimal](18,4) NOT NULL CONSTRAINT [DF_OS_OrderBill_Weight] DEFAULT (0)
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBill' AND a.Name='PICID')
	ALTER TABLE OS_OrderBill ADD PICID INT NOT NULL CONSTRAINT [DF_OS_OrderBill_PICID] DEFAULT (0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBill' AND a.Name='Address' AND c.name = 'VARCHAR' AND a.max_length = 150)
    ALTER TABLE OS_OrderBill ALTER COLUMN [Address] VARCHAR(200) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBill' AND a.Name='BuyerMsg' AND c.name = 'VARCHAR' AND a.max_length = 256)
    ALTER TABLE OS_OrderBill ALTER COLUMN BuyerMsg VARCHAR(800) NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBill' AND a.Name='SaleComment' AND c.name = 'VARCHAR' AND a.max_length = 256)
    ALTER TABLE OS_OrderBill ALTER COLUMN SaleComment VARCHAR(800) NULL
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBill' AND a.Name='OSBillCode')
	ALTER TABLE OS_OrderBill ADD [OSBillCode] [varchar](100) NOT NULL CONSTRAINT [DF_OS_OrderBill_OSBillCode] DEFAULT ''
	
	
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
			INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBill' AND a.Name='OSBillCode' AND c.name = 'VARCHAR' AND a.max_length <> 800)
	ALTER TABLE OS_OrderBill ALTER COLUMN OSBillCode VARCHAR(800) NULL
	



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_OrderBillAll]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_OrderBillAll
(
	BillNo			BIGINT NOT NULL,
	BillType		TINYINT NOT NULL,
	BillCode		VARCHAR(50)  NOT NULL,
	BillDate		DATE NOT NULL,
	ShopID			BIGINT NOT NULL,
	ElyID			INT NOT NULL,
	WhsID			INT NOT NULL,
	Summary			VARCHAR(256) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_Summary] DEFAULT(''),
	Description		VARCHAR(256) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_Description] DEFAULT(''),
	BillQty			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_BillQty] DEFAULT(0),
	Total			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_Total] DEFAULT(0),
	MallFee			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_MallFee] DEFAULT(0),
	CodFee			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_CodFee] DEFAULT(0),
	LogistBTypeCode	VARCHAR(50) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_LogistBTypeID] DEFAULT(''),
	FreightBillNo	VARCHAR(50) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_FreightBillNo] DEFAULT(''),
	Freight			DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_Freight] DEFAULT(0),
	PaidFreight		DECIMAL(20,8) NOT NULL  CONSTRAINT [DF_OS_OrderBillAll_PaidFreight] DEFAULT(0),
	BuyerAccount	VARCHAR(50) NOT NULL,
	ContactWay		VARCHAR(50) NOT NULL,
	Receiver		VARCHAR(50) NOT NULL,
	Address			VARCHAR(200) NOT NULL,
	BuyerMsg		VARCHAR(800)  NULL,
	SaleComment		VARCHAR(800)  NULL,
	BackReason		VARCHAR(256)  NULL,
	SrcSendBillNo	BIGINT NOT NULL CONSTRAINT [DF_OS_OrderBillAll_SrcSendBillNo] DEFAULT(0),
	BackType		INT  NULL,
	DestSendBillNo	BIGINT NOT NULL CONSTRAINT [DF_OS_OrderBillAll_DestSendBillNo] DEFAULT(0),
	IsCreate		TINYINT NOT NULL CONSTRAINT [DF_OS_OrderBillAll_IsCreate] DEFAULT(0),
	HasError		BIT NOT NULL CONSTRAINT [DF_OS_OrderBillAll_HasError] DEFAULT(0),    
	[CreateTime]    date NOT NULL,
    [ReceiverProvince] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_ReceiverProvince] DEFAULT '',
    [ReceiverCity] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_ReceiverCity] DEFAULT '',
    [ReceiverDistrict] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_ReceiverDistrict] DEFAULT '',
    [Weight] [decimal](18,4) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_Weight] DEFAULT (0),
	PICID			INT NOT NULL CONSTRAINT [DF_OS_OrderBillAll_PICID] DEFAULT (0),
    [OSBillCode] [varchar](100) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_OSBillCode] DEFAULT '',
	CONSTRAINT [PK_OS_OrderBillAll] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_OrderBillAll]') AND name = N'IXC_OS_OrderBillAll_BillDate') 
	CREATE CLUSTERED  INDEX IXC_OS_OrderBillAll_BillDate on OS_OrderBillAll ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBillAll' AND a.Name='CreateTime')
	BEGIN
		ALTER TABLE OS_OrderBillAll ADD CreateTime DATE NULL
		EXEC sp_executesql N'UPDATE OS_OrderBillAll SET CreateTime = BillDate WHERE CreateTime IS NULL'
		ALTER TABLE OS_OrderBillAll ALTER COLUMN CreateTime DATE NOT NULL
	END
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBillAll' AND a.Name='ReceiverProvince')
	ALTER TABLE OS_OrderBillAll ADD [ReceiverProvince] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_ReceiverProvince] DEFAULT ''
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBillAll' AND a.Name='ReceiverCity')
	ALTER TABLE OS_OrderBillAll ADD [ReceiverCity] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_ReceiverCity] DEFAULT ''
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBillAll' AND a.Name='ReceiverDistrict')
	ALTER TABLE OS_OrderBillAll ADD [ReceiverDistrict] [varchar](50) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_ReceiverDistrict] DEFAULT ''
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBillAll' AND a.Name='Weight')
	ALTER TABLE OS_OrderBillAll ADD [Weight] [decimal](18,4) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_Weight] DEFAULT (0)
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBillAll' AND a.Name='PICID')
	ALTER TABLE OS_OrderBillALL ADD PICID INT NOT NULL CONSTRAINT [DF_OS_OrderBillAll_PICID] DEFAULT (0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBillALL' AND a.Name='Address' AND c.name = 'VARCHAR' AND a.max_length = 150)
    ALTER TABLE OS_OrderBillALL ALTER COLUMN [Address] VARCHAR(200) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBillALL' AND a.Name='BuyerMsg' AND c.name = 'VARCHAR' AND a.max_length = 256)
    ALTER TABLE OS_OrderBillALL ALTER COLUMN BuyerMsg VARCHAR(800) NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBillALL' AND a.Name='SaleComment' AND c.name = 'VARCHAR' AND a.max_length = 256)
    ALTER TABLE OS_OrderBillALL ALTER COLUMN SaleComment VARCHAR(800) NULL
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OS_OrderBillAll' AND a.Name='OSBillCode')
	ALTER TABLE OS_OrderBillAll ADD [OSBillCode] [varchar](100) NOT NULL CONSTRAINT [DF_OS_OrderBillAll_OSBillCode] DEFAULT ''
	
	
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
			INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OrderBillALL' AND a.Name='OSBillCode' AND c.name = 'VARCHAR' AND a.max_length <> 800)
	ALTER TABLE OS_OrderBillALL ALTER COLUMN OSBillCode VARCHAR(800) NULL
			



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_OrderDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_OrderDetail
(
	DID				BIGINT IDENTITY(1,1) NOT NULL, 
	BillDate		DATE NOT NULL,
	BillNo			BIGINT NOT NULL,
	OSGoodsName		VARCHAR(100) NOT NULL,
	MerchantCode	VARCHAR(100) NOT NULL,
	PropsName		VARCHAR(100) NOT NULL,
	GoodsID			INT,
	Ppt1ID			INT,
	Ppt2ID			INT,
	WhsPtID			INT,
	UnitID			INT,
	Qty				DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetail_Qty] DEFAULT(0),
	Price			DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetail_Price] DEFAULT(0),
	Total			DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetail_Total] DEFAULT(0),
	MallFee			DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetail_MallFee] DEFAULT(0),
	Gift			TINYINT NOT NULL
	CONSTRAINT [PK_OS_OrderDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_OrderDetail]') AND name = N'IXC_OS_OrderDetail_BillDate') 
	CREATE INDEX IXC_OS_OrderDetail_BillDate on OS_OrderDetail (BillDate) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_OrderDetail]') AND name = N'IX_OS_OrderDetail_BillNo') 
	CREATE NONCLUSTERED  INDEX IX_OS_OrderDetail_BillNo on OS_OrderDetail (BillNo) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_OrderDetailAll]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_OrderDetailAll
(
	DID				BIGINT NOT NULL, 
	BillDate		DATE NOT NULL,
	BillNo			BIGINT NOT NULL,
	OSGoodsName		VARCHAR(100) NOT NULL,
	MerchantCode	VARCHAR(100) NOT NULL,
	PropsName		VARCHAR(100) NOT NULL,
	GoodsID			INT,
	Ppt1ID			INT,
	Ppt2ID			INT,
	WhsPtID			INT,
	UnitID			INT,
	Qty				DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetailAll_Qty] DEFAULT(0),
	Price			DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetailAll_Price] DEFAULT(0),
	Total			DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetailAll_Total] DEFAULT(0),
	MallFee			DECIMAL(20,8) NOT NULL CONSTRAINT [DF_OS_OrderDetailAll_MallFee] DEFAULT(0),
	Gift			TINYINT NOT NULL
	CONSTRAINT [PK_OS_OrderDetailAll] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_OrderDetailAll]') AND name = N'IXC_OS_OrderDetailAll_BillDate') 
	CREATE INDEX IXC_OS_OrderDetailAll_BillDate on OS_OrderDetailAll (BillDate) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OS_OrderDetailAll]') AND name = N'IX_OS_OrderDetailAll_BillNo') 
	CREATE NONCLUSTERED  INDEX IX_OS_OrderDetailAll_BillNo on OS_OrderDetailAll (BillNo) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_OtherConfig]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_OtherConfig
(
	ConfigID		INT IDENTITY(1,1) NOT NULL,
	ConfigName		VARCHAR(50) NOT NULL,
	ConfigValue		INT NOT NULL  CONSTRAINT [DF_OS_OtherConfig_ConfigValue] DEFAULT(0),
	Remark			VARCHAR(256) NULL,
	CONSTRAINT [PK_OS_OtherConfig] PRIMARY KEY NONCLUSTERED ([ConfigID])
)
SET IDENTITY_INSERT [OS_OtherConfig] ON  
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(1,'Summary',1,'网店订单单据摘要；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(2,'BuyerMsg',0,'买家留言；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(3,'SellerRemark',0,'卖家备注；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(4,'Address',0,'收货人地址；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(5,'Connect',0,'联系方式；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(6,'Receiver',0,'收货人姓名；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(7,'BuyerAccount',0,'买家账号；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(8,'UpdateStockType',1,'商品数量更新方式；1=实际库存 2=虚拟库存');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(9,'SaveType',1,'生成物流单据处理方式；1=保存草稿 2=直接过账');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(10,'BackToLoss',1,'损坏退货订单自动生成报损单；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
	 VALUES(11,'ElyNameMatch',1,'经手人名称下载条件过滤匹配方式；1=不等于 2=等于 3=包含');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
     VALUES(12,'MerchantCodeRule',0,'商家编码生成规则；0=未选择规则 1=商品编号 2=商品ID+属性ID+计量单位ID');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
	 VALUES(13,'RegUpdateStock',0,'定时更新库存；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
	 VALUES(14,'RegTime',15,'定时更新库存间隔时间；默认为15分钟');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
	 VALUES(15,'AutoSyncBill',0,'自动同步单据；0=不选 1=勾选');
INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
	 VALUES(16,'AutoSyncTime',15,'自动同步单据存间隔时间；默认为15分钟');
SET IDENTITY_INSERT [OS_OtherConfig] OFF  
END

IF NOT EXISTS (SELECT 1 FROM [OS_OtherConfig] WHERE ConfigID = 11)
	BEGIN
		SET IDENTITY_INSERT [OS_OtherConfig] ON  
		INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
			 VALUES(11,'ElyNameMatch',1,'经手人名称下载条件过滤匹配方式；1=不等于 2=等于 3=包含');
		SET IDENTITY_INSERT [OS_OtherConfig] OFF 
	END

IF NOT EXISTS (SELECT 1 FROM [OS_OtherConfig] WHERE ConfigID = 12)
	BEGIN
		SET IDENTITY_INSERT [OS_OtherConfig] ON  
		INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
			 VALUES(12,'MerchantCodeRule',0,'商家编码生成规则；0=未选择规则 1=商品编号 2=商品ID+属性ID+计量单位ID');
		SET IDENTITY_INSERT [OS_OtherConfig] OFF 
	END

IF NOT EXISTS (SELECT 1 FROM [OS_OtherConfig] WHERE ConfigID = 13)
	BEGIN
		SET IDENTITY_INSERT [OS_OtherConfig] ON  
		INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
			 VALUES(13,'RegUpdateStock',0,'定时更新库存；0=不选 1=勾选');
		SET IDENTITY_INSERT [OS_OtherConfig] OFF 
	END

IF NOT EXISTS (SELECT 1 FROM [OS_OtherConfig] WHERE ConfigID = 14)
	BEGIN
		SET IDENTITY_INSERT [OS_OtherConfig] ON  
		INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
			 VALUES(14,'RegTime',15,'定时更新库存间隔时间；默认为15分钟');
		SET IDENTITY_INSERT [OS_OtherConfig] OFF 
	END
	

IF NOT EXISTS (SELECT 1 FROM [OS_OtherConfig] WHERE ConfigID = 15)
	BEGIN
		SET IDENTITY_INSERT [OS_OtherConfig] ON  
		INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
			 VALUES(15,'AutoSyncBill',0,'自动同步单据；0=不选 1=勾选');
		SET IDENTITY_INSERT [OS_OtherConfig] OFF 
	END

IF NOT EXISTS (SELECT 1 FROM [OS_OtherConfig] WHERE ConfigID = 16)
	BEGIN
		SET IDENTITY_INSERT [OS_OtherConfig] ON  
		INSERT INTO [OS_OtherConfig]([ConfigID],[ConfigName],[ConfigValue],[Remark])
			 VALUES(16,'AutoSyncTime',15,'自动同步单据存间隔时间；默认为15分钟');
		SET IDENTITY_INSERT [OS_OtherConfig] OFF 
	END
	
	
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='OS_OtherConfig' AND a.Name='ConfigValue' AND c.name = 'tinyint')
    BEGIN
		DECLARE @sql VARCHAR(max)=''
		select   @sql='alter   table   ['+b.name+']   drop   constraint   ['+d.name+']'   
		 from   syscolumns   a   
		 join   sysobjects   b   on   a.id=b.id   and   a.name= 'ConfigValue'  and   b.name='OS_OtherConfig'
		 join   syscomments   c   on   a.cdefault=c.id   
		 join   sysobjects   d   on   c.id=d.id   

		EXEC(@sql)
		ALTER TABLE OS_OtherConfig ALTER COLUMN ConfigValue INT NOT NULL
		ALTER TABLE OS_OtherConfig ADD CONSTRAINT [DF_OS_OtherConfig_ConfigValue] DEFAULT (0) FOR ConfigValue
    END



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_PostConfig]') AND type in (N'U'))
BEGIN
CREATE TABLE [OS_PostConfig]
(
	ConfigID		INT IDENTITY(1,1) NOT NULL,
	ShopID			BIGINT NOT NULL,
	ConfigName		VARCHAR(50) NOT NULL,
	ConfigValue		VARCHAR(100) NOT NULL
	CONSTRAINT [PK_OS_PostConfig] PRIMARY KEY NONCLUSTERED ([ConfigID])
)
END



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OS_SyncStockError]') AND type in (N'U'))
BEGIN
CREATE TABLE OS_SyncStockError
(
    [ErrorID] [int] IDENTITY(1,1) NOT NULL,
    [WhsID] [int] NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_OS_SyncStockError_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_OS_SyncStockError_Ppt2ID] DEFAULT (0),
    [SyncTime] [datetime] NOT NULL CONSTRAINT [DF_OS_SyncStockError_SyncTime] DEFAULT getdate(),
    [ErrorMsg] [varchar](100) NOT NULL CONSTRAINT [DF_OS_SyncStockError_ErrorMsg] DEFAULT '',
    CONSTRAINT [PK_OS_SyncStockError] PRIMARY KEY NONCLUSTERED ([ErrorID])
)
END



/*====================== TABLE: [OS_SyncStockWhs] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OS_SyncStockWhs]') AND type in (N'U'))
BEGIN
CREATE TABLE [OS_SyncStockWhs]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [WhsID] [int] NOT NULL,
    CONSTRAINT [PK_OS_SyncStockWhs] PRIMARY KEY NONCLUSTERED ([ID])
)
END



/*====================== TABLE: [BD_ARAP] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_DataArchiveTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_DataArchiveTable]
(
   BillName VARCHAR(50)
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_ErrorRecord]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_ErrorRecord]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ErrorMsg] [varchar](2000) NOT NULL CONSTRAINT [DF_OT_ErrorRecord_ErrorMsg] DEFAULT '',
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_OT_ErrorRecord_CreateTime] DEFAULT getdate(),
    [RecordType] [tinyint] NOT NULL CONSTRAINT [DF_OT_ErrorRecord_RecordType] DEFAULT (0),
    CONSTRAINT [PK_OT_ErrorRecord] PRIMARY KEY NONCLUSTERED ([ID])
)
END




/*====================== TABLE: [OT_Ext] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_Ext]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_Ext]
(
    [ExtID] int NOT NULL,
    [ExtName] [varchar](50) NOT NULL CONSTRAINT [DF_OT_Ext_ExtName] DEFAULT '',
    [CreateTime] datetime NOT NULL CONSTRAINT [DF_OT_Ext_CreateTime] DEFAULT GETDATE(),
    [Stt] bit NOT NULL CONSTRAINT [DF_OT_Ext_Stt] DEFAULT 1,
    CONSTRAINT [PK_OT_Ext] PRIMARY KEY NONCLUSTERED ([ExtID])
)
END
    



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_GridColumnConfig]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_GridColumnConfig]
(
	ID INT IDENTITY(1,1),
	[ElyID] [int] NOT NULL,
    [GridID] [varchar](30) NOT NULL,
    [ColumnField] [varchar](30) NOT NULL,
    [ORDER] int  NOT NULL,
    [LockedCount] [tinyint] NULL CONSTRAINT [DF_OT_GridColumnConfig_LockedCount] DEFAULT (0),
    [ColumnVisible] int NOT NULL CONSTRAINT [DF_OT_GridColumnConfig_ColumnVisible] DEFAULT (-1),
    ColumnsWidth DECIMAL(18,4) NOT NULL CONSTRAINT [DF_OT_GridColumnConfig_ColumnsWidth] DEFAULT (-1),
    CONSTRAINT [PK_OT_GridColumnConfig] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OT_GridColumnConfig]') AND name = N'IXC_OT_GridColumnConfig_ElyIDGridID') 
	CREATE NONCLUSTERED  INDEX IXC_OT_GridColumnConfig_ElyIDGridID on OT_GridColumnConfig ([ElyID],[GridID]) WITH (FILLFACTOR = 90);






IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_GridColumnNewName]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_GridColumnNewName]
(
	ID INT IDENTITY(1,1),
	[ElyID] [int] NOT NULL,
    [GridID] [varchar](30) NOT NULL,
    [ColumnField] [varchar](30) NOT NULL,
    [NewName] [varchar](50) NOT NULL,
    CONSTRAINT [PK_OT_GridColumnNewName] PRIMARY KEY NONCLUSTERED ([ID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[OT_GridColumnNewName]') AND name = N'IXC_OT_GridColumnNewName_ElyIDGridID') 
	CREATE NONCLUSTERED  INDEX IXC_OT_GridColumnNewName_ElyIDGridID on OT_GridColumnNewName ([ElyID],[GridID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_LastSelectedBaseInfo]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_LastSelectedBaseInfo]
(
	DID			DECIMAL(18,0) IDENTITY(1,1),
	OperatorID	INT NOT NULL,
	BaseID		INT NOT NULL,
	BaseType	TINYINT,
	CONSTRAINT [PK_OT_LastSelectedBaseInfo] PRIMARY KEY CLUSTERED ([DID])
)
END



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_OtherConfig]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_OtherConfig]
(
    [ConfigID] [int] NOT NULL,
    [ConfigName] [varchar](50) NOT NULL,
    [ConfigValue] [varchar](100) NOT NULL,
    [Remark] [varchar](256) NOT NULL CONSTRAINT [DF_OT_OtherConfig_Remark] DEFAULT '',
    [ConfigBelong] [tinyint] NOT NULL CONSTRAINT [DF_OT_OtherConfig_ConfigBelong] DEFAULT 0,
    CONSTRAINT [PK_OT_OtherConfig] PRIMARY KEY NONCLUSTERED ([ConfigID])
)
 INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (1,'ElyNameKey','','经手人名称下载条件过滤关键字',2);
    
    INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (2,'IDCode','','识别码',3);
END

IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 2)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (2,'IDCode','','识别码',3);

IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 101)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (101,'AppID','wx414b3a630bf6de4f','公众账号ID',4);	
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 102)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (102,'SubAppID','','子商户公众账号ID',4);	
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 103)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (103,'MchID','1315483801','商户号',4);	
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 104)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (104,'SubMchID','','子商户号',4);			
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 105)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (105,'AutoDownLoadWXBill','0','自动下载对账单时间',4);	
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 106)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (106,'DownloadWXBillTime','10:00','自动下载对账单时间',4);	
	
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 107)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (107,'Notity_URL','http://wxpay.myd9.com/ResultNotifyPage.aspx','回调地址',4);		
	
	
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 108)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (108,'ETime','','',5);			

	
IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 109)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (109,'UNumber','','',5);	

IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 110)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (110,'SignData','','',5);	
	

IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 111)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (111,'RTime','','',5);	

IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 112)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (112,'ZTSecret','','',5);	

IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 200)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (200,'Version','','',5);		


IF NOT EXISTS(SELECT 1 FROM dbo.OT_OtherConfig WHERE ConfigID = 201)
	INSERT INTO [OT_OtherConfig] ([ConfigID],[ConfigName],[ConfigValue],[Remark],[ConfigBelong]) values (201,'ZTNumber','','',5);		
							

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='OT_OtherConfig' AND a.Name='Comment')
BEGIN
    ALTER TABLE OT_OtherConfig ADD Comment  VARCHAR(MAX)  NOT NULL DEFAULT('')
END



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_QueryPlan]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_QueryPlan]
(
	PlanID		DECIMAL(18,0) IDENTITY(1,1),
	ElyID		INT NOT NULL,--职员
	MenuID		INT NOT NULL,--报表MenuID
	PlanName	VARCHAR(50),  --方案名称
	IsDefault	BIT default(0),--是否默认方案 
	CONSTRAINT [PK_OT_QueryPlan] PRIMARY KEY CLUSTERED ([PlanId])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[OT_QueryPlanDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [OT_QueryPlanDetail]
(
	DID			DECIMAL(18,0) IDENTITY(1,1),
	PlanID		DECIMAL(18,0) NOT NULL,
	DataField		VARCHAR(50)  NOT NULL,
	DataValue		VARCHAR(MAX),
	CONSTRAINT [PK_OT_QueryPlanDetail] PRIMARY KEY CLUSTERED ([DID])
)
END



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OT_WXBank]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OT_WXBank]
(
    [ID] int IDENTITY(1,1) NOT NULL,
    [BankID] VARCHAR(20) NOT NULL,
	[BankName] VARCHAR(50) NOT NULL,
     CONSTRAINT [PK_OT_WXBank] PRIMARY KEY NONCLUSTERED ([ID])
)
END    

TRUNCATE TABLE dbo.OT_WXBank
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CFT','零钱')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ICBC_DEBIT','工商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ICBC_CREDIT','工商银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ABC_DEBIT','农业银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ABC_CREDIT','农业银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('PSBC_DEBIT','邮政储蓄银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('PSBC_CREDIT','邮政储蓄银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CCB_DEBIT','建设银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CCB_CREDIT','建设银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CMB_DEBIT','招商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CMB_CREDIT','招商银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOC_DEBIT','中国银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOC_CREDIT','中国银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('COMM_DEBIT','交通银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SPDB_DEBIT','浦发银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SPDB_CREDIT','浦发银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GDB_DEBIT','广发银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GDB_CREDIT','广发银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CMBC_DEBIT','民生银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CMBC_CREDIT','民生银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('PAB_DEBIT','平安银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('PAB_CREDIT','平安银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CEB_DEBIT','光大银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CEB_CREDIT','光大银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CIB_DEBIT','兴业银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CIB_CREDIT','兴业银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CITIC_DEBIT','中信银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CITIC_CREDIT','中信银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOSH_DEBIT','上海银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOSH_CREDIT','上海银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CRB_DEBIT','华润银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HZB_DEBIT','杭州银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HZB_CREDIT','杭州银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BSB_DEBIT','包商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BSB_CREDIT','包商银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CQB_DEBIT','重庆银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SDEB_DEBIT','顺德农商行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SZRCB_DEBIT','深圳农商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HRBB_DEBIT','哈尔滨银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOCD_DEBIT','成都银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GDNYB_DEBIT','南粤银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GDNYB_CREDIT','南粤银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GZCB_DEBIT','广州银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GZCB_CREDIT','广州银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JSB_DEBIT','江苏银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JSB_CREDIT','江苏银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('NBCB_DEBIT','宁波银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('NBCB_CREDIT','宁波银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('NJCB_DEBIT','南京银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JZB_DEBIT','晋中银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('KRCB_DEBIT','昆山农商(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('LJB_DEBIT','龙江银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('LNNX_DEBIT','辽宁农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('LZB_DEBIT','兰州银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('WRCB_DEBIT','无锡农商(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ZYB_DEBIT','中原银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ZJRCUB_DEBIT','浙江农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('WZB_DEBIT','温州银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('XAB_DEBIT','西安银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JXNXB_DEBIT','江西农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('NCB_DEBIT','宁波通商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('NYCCB_DEBIT','南阳村镇银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('NMGNX_DEBIT','内蒙古农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SXXH_DEBIT','陕西信合(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SRCB_CREDIT','上海农商银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SJB_DEBIT','盛京银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SDRCU_DEBIT','山东农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SRCB_DEBIT','上海农商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('SCNX_DEBIT','四川农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('QLB_DEBIT','齐鲁银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('QDCCB_DEBIT','青岛银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('PZHCCB_DEBIT','攀枝花银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ZJTLCB_DEBIT','浙江泰隆银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('TJBHB_DEBIT','天津滨海农商行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('WEB_DEBIT','微众银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('YNRCCB_DEBIT','云南农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('WFB_DEBIT','潍坊银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('WHRC_DEBIT','武汉农商行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ORDOSB_DEBIT','鄂尔多斯银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('XJRCCB_DEBIT','新疆农信银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('ORDOSB_CREDIT','鄂尔多斯银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CSRCB_DEBIT','常熟农商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JSNX_DEBIT','江苏农商行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GRCB_CREDIT','广州农商银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GLB_DEBIT','桂林银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GDRCU_DEBIT','广东农信银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GDHX_DEBIT','广东华兴银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('FJNX_DEBIT','福建农信银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('DYCCB_DEBIT','德阳银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('DRCB_DEBIT','东莞农商行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CZCB_DEBIT','稠州银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CZB_DEBIT','浙商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CZB_CREDIT','浙商银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GRCB_DEBIT','广州农商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CSCB_DEBIT','长沙银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CQRCB_DEBIT','重庆农商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('CBHB_DEBIT','渤海银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOIMCB_DEBIT','内蒙古银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOD_DEBIT','东莞银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOD_CREDIT','东莞银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BOB_DEBIT','北京银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BNC_DEBIT','江西银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('BJRCB_DEBIT','北京农商行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('AE_CREDIT','AE(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GYCB_CREDIT','贵阳银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JSHB_DEBIT','晋商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JRCB_DEBIT','江阴农商行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JNRCB_DEBIT','江南农商(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JLNX_DEBIT','吉林农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JLB_DEBIT','吉林银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JJCCB_DEBIT','九江银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HXB_DEBIT','华夏银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HXB_CREDIT','华夏银行(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HUNNX_DEBIT','湖南农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HSB_DEBIT','徽商银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HSBC_DEBIT','恒生银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HRXJB_DEBIT','华融湘江银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HNNX_DEBIT','河南农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HKBEA_DEBIT','东亚银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HEBNX_DEBIT','河北农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HBNX_DEBIT','湖北农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('HBNX_CREDIT','湖北农信(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GYCB_DEBIT','贵阳银行(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('GSNX_DEBIT','甘肃农信(借记卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('JCB_CREDIT','JCB(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('MASTERCARD_CREDIT','MASTERCARD(信用卡)')
INSERT INTO OT_WXBank(BankID,BankName) VALUES('VISA_CREDIT','VISA(信用卡)')




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OT_WXBillCode]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OT_WXBillCode]
(
    [ID] int IDENTITY(1,1) NOT NULL,
    [BillTypeID] INT NOT NULL,
    [BillNo] INT NOT NULL,
    [BillCode1] VARCHAR(32) ,
	[BillCode2] VARCHAR(32) ,
    CONSTRAINT [PK_OT_WXBillCode] PRIMARY KEY NONCLUSTERED ([ID])
)
END    





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[OT_WXStateBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[OT_WXStateBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [TradeTime] [datetime] NOT NULL CONSTRAINT [DF_OT_WXStateBill_TradeTime] DEFAULT '',
    [SubMchID] [varchar](30) NOT NULL CONSTRAINT [DF_OT_WXStateBill_SubMchID] DEFAULT '',
    [DeviceID] [varchar](30) NOT NULL CONSTRAINT [DF_OT_WXStateBill_DeviceID] DEFAULT '',
    [BillCode] [varchar](50) NOT NULL CONSTRAINT [DF_OT_WXStateBill_BillCode] DEFAULT '',
    [MchBillCode] [varchar](50) NOT NULL CONSTRAINT [DF_OT_WXStateBill_MchBillCode] DEFAULT '',
    [UserIdentify] [varchar](50) NOT NULL CONSTRAINT [DF_OT_WXStateBill_UserIdentify] DEFAULT '',
    [TradeType] [varchar](20) NOT NULL CONSTRAINT [DF_OT_WXStateBill_TradeType] DEFAULT '',
    [TradeStatus] [varchar](20) NOT NULL CONSTRAINT [DF_OT_WXStateBill_TradeStatus] DEFAULT (0),
    [TradeBank] [varchar](50) NOT NULL CONSTRAINT [DF_OT_WXStateBill_TradeBank] DEFAULT '',
    [Currency] [varchar](10) NOT NULL CONSTRAINT [DF_OT_WXStateBill_Currency] DEFAULT '',
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_OT_WXStateBill_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_OT_WXStateBill_Privilege] DEFAULT (0),
    [GoodsName] [varchar](100) NOT NULL CONSTRAINT [DF_OT_WXStateBill_GoodsName] DEFAULT '',
    [MchData] [varchar](50) NOT NULL CONSTRAINT [DF_OT_WXStateBill_MchData] DEFAULT '',
    [Poundage] [decimal](20,8) NOT NULL CONSTRAINT [DF_OT_WXStateBill_Poundage] DEFAULT (0),
    [Rate] [varchar](10) NOT NULL CONSTRAINT [DF_OT_WXStateBill_Rate] DEFAULT (''),
    [RetBillCode] [varchar](50) NOT NULL CONSTRAINT [DF_OT_WXStateBill_RetBillCode] DEFAULT '',
    [MchRetBillCode] [varchar](50) NOT NULL CONSTRAINT [DF_OT_WXStateBill_MchRetBillCode] DEFAULT '',
    [RetTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_OT_WXStateBill_RetTotal] DEFAULT (0),
    [RetPrivilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_OT_WXStateBill_RetPrivilege] DEFAULT (0),
    [RetType] [varchar](20) NOT NULL CONSTRAINT [DF_OT_WXStateBill_RetType] DEFAULT '',
    [RetStatus] [varchar](20) NOT NULL CONSTRAINT [DF_OT_WXStateBill_RetStatus] DEFAULT '',
    [RetCreateTime] [datetime],
    [RetSuccessTime] [datetime],
	CONSTRAINT [PK_OT_WXStateBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END    

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='Rate' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'OT_WXStateBill' AND so.xtype = 'D' AND so.name = 'DF_OT_WXStateBill_Rate')
			ALTER TABLE dbo.OT_WXStateBill DROP CONSTRAINT [DF_OT_WXStateBill_Rate]
		ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN Rate [varchar](10) NOT NULL
		ALTER TABLE dbo.OT_WXStateBill ADD CONSTRAINT [DF_OT_WXStateBill_Rate] DEFAULT('') FOR Rate
    END 

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='RetCreateTime' AND c.name = 'datetime')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'OT_WXStateBill' AND so.xtype = 'D' AND so.name = 'DF_OT_WXStateBill_RetCreateTime')
		BEGIN
			ALTER TABLE dbo.OT_WXStateBill DROP CONSTRAINT [DF_OT_WXStateBill_RetCreateTime]
			ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN RetCreateTime [datetime]
		END
    END 
    
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='RetSuccessTime' AND c.name = 'datetime')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'OT_WXStateBill' AND so.xtype = 'D' AND so.name = 'DF_OT_WXStateBill_RetSuccessTime')
		BEGIN
			ALTER TABLE dbo.OT_WXStateBill DROP CONSTRAINT [DF_OT_WXStateBill_RetSuccessTime]
			ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN RetSuccessTime [datetime]
		END
    END

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='BillCode' AND c.name = 'varchar' AND a.max_length = 30)
	ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN BillCode [varchar](50) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='MchBillCode' AND c.name = 'varchar' AND a.max_length = 30)
	ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN MchBillCode [varchar](50) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='RetBillCode' AND c.name = 'varchar' AND a.max_length = 30)
	ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN RetBillCode [varchar](50) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='MchRetBillCode' AND c.name = 'varchar' AND a.max_length = 30)
	ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN MchRetBillCode [varchar](50) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='UserIdentify' AND c.name = 'varchar' AND a.max_length = 30)
	ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN UserIdentify [varchar](50) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='TradeBank' AND c.name = 'varchar' AND a.max_length = 10)
	ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN TradeBank [varchar](50) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='GoodsName' AND c.name = 'varchar' AND a.max_length = 50)
	ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN GoodsName [varchar](100) NOT NULL

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='OT_WXStateBill' AND a.Name='Rate' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'OT_WXStateBill' AND so.xtype = 'D' AND so.name = 'DF_OT_WXStateBill_Rate')
			ALTER TABLE dbo.OT_WXStateBill DROP CONSTRAINT [DF_OT_WXStateBill_Rate]
		ALTER TABLE dbo.OT_WXStateBill ALTER COLUMN Rate [varchar](10) NOT NULL
		ALTER TABLE dbo.OT_WXStateBill ADD CONSTRAINT [DF_OT_WXStateBill_Rate] DEFAULT('') FOR Rate
    END
    
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'OT_WXStateBill' AND so.xtype = 'PK' AND so.name = 'PK_OT_WXStateBill')
	ALTER TABLE dbo.OT_WXStateBill ADD CONSTRAINT [PK_OT_WXStateBill] PRIMARY KEY CLUSTERED ([BillNo])



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AdjPriceBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [WhsID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_IsDraft] DEFAULT (1),
    AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_AdjPriceBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND name = N'IXC_PD_AdjPriceBill_BillCode') 
	CREATE  INDEX IXC_PD_AdjPriceBill_BillCode on PD_AdjPriceBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND name = N'IXC_PD_AdjPriceBill_BillDate') 
	CREATE  INDEX IXC_PD_AdjPriceBill_BillDate on PD_AdjPriceBill ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND name = N'IXC_PD_AdjPriceBill_CreateTime') 
	CREATE  INDEX IXC_PD_AdjPriceBill_CreateTime on PD_AdjPriceBill ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND name = N'IXC_PD_AdjPriceBill_PosTime') 
	CREATE  INDEX IXC_PD_AdjPriceBill_PosTime on PD_AdjPriceBill ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND name = N'IX_PD_AdjPriceBill_WhsID') 
	CREATE  INDEX IX_PD_AdjPriceBill_WhsID on PD_AdjPriceBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND name = N'IX_PD_AdjPriceBill_DeptID') 
	CREATE  INDEX IX_PD_AdjPriceBill_DeptID on PD_AdjPriceBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill]') AND name = N'IX_PD_AdjPriceBill_ElyID') 
	CREATE  INDEX IX_PD_AdjPriceBill_ElyID on PD_AdjPriceBill ([ElyID]) WITH (FILLFACTOR = 90);	
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AdjPriceBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_AuditStatus] DEFAULT (0)  



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AdjPriceBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [WhsID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_IsDraft] DEFAULT (1),
    AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_AdjPriceBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END
IF NOT  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND name = N'IXC_PD_AdjPriceBill_His_BillCode') 
	CREATE  INDEX IXC_PD_AdjPriceBill_His_BillCode on PD_AdjPriceBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND name = N'IXC_PD_AdjPriceBill_His_BillDate') 
	CREATE  INDEX IXC_PD_AdjPriceBill_His_BillDate on PD_AdjPriceBill_His ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND name = N'IXC_PD_AdjPriceBill_His_CreateTime') 
	CREATE  INDEX IXC_PD_AdjPriceBill_His_CreateTime on PD_AdjPriceBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND name = N'IXC_PD_AdjPriceBill_His_PosTime') 
	CREATE  INDEX IXC_PD_AdjPriceBill_His_PosTime on PD_AdjPriceBill_His ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND name = N'IX_PD_AdjPriceBill_His_WhsID') 
	CREATE  INDEX IX_PD_AdjPriceBill_His_WhsID on PD_AdjPriceBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND name = N'IX_PD_AdjPriceBill_His_DeptID') 
	CREATE  INDEX IX_PD_AdjPriceBill_His_DeptID on PD_AdjPriceBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceBill_His]') AND name = N'IX_PD_AdjPriceBill_His_ElyID') 
	CREATE  INDEX IX_PD_AdjPriceBill_His_ElyID on PD_AdjPriceBill_His ([ElyID]) WITH (FILLFACTOR = 90);  
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AdjPriceBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AdjPriceBill_His_AuditStatus] DEFAULT (0)  



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AdjPriceDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate][date] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_BSQty] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_CostPrice] DEFAULT (0),
    [AdjPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_AdjPrice] DEFAULT (0),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_GoodsCostTotal] DEFAULT (0),
    [AdjTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_AdjTotal] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_InPutPrice]  DEFAULT(1),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_EndDate]  DEFAULT (''),
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_AdjPriceDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_AdjPriceDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_InPutPrice]  DEFAULT(1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_AdjPriceDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_AdjPriceDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail' AND a.Name='EndDate')
    ALTER TABLE PD_AdjPriceDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_EndDate]  DEFAULT ('') 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_AdjPriceDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_IsSelectBatch]  DEFAULT (0)
       
    

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail]') AND name = N'IXC_PD_AdjPriceDetail_BillDate') 
	CREATE CLUSTERED INDEX IXC_PD_AdjPriceDetail_BillDate on PD_AdjPriceDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail]') AND name = N'IXC_PD_AdjPriceDetail_BillNo') 
	CREATE  INDEX IXC_PD_AdjPriceDetail_BillNo on PD_AdjPriceDetail ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail]') AND name = N'IX_PD_AdjPriceDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AdjPriceDetail_GoodsIDPpt12ID on PD_AdjPriceDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);

IF NOT  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail]') AND name = N'IX_PD_AdjPriceDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AdjPriceDetail_WhsIDWhsPtID on PD_AdjPriceDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_AdjPriceDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_AdjPriceDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO
UPDATE PD_AdjPriceDetail SET Remark = '' WHERE Remark IS NULL
GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AdjPriceDetail_His]
(
    [DID] [bigint]  NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL ,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_BSQty] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_CostPrice] DEFAULT (0),
    [AdjPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_AdjPrice] DEFAULT (0),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_GoodsCostTotal] DEFAULT (0),
    [AdjTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_AdjTotal] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_InPutPrice]  DEFAULT(1),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_EndDate]  DEFAULT (''),
	[IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_IsSelectBatch]  DEFAULT (0) 
    CONSTRAINT [PK_PD_AdjPriceDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail_His' AND a.Name='InPutPrice')
    ALTER TABLE PD_AdjPriceDetail_His ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_InPutPrice]  DEFAULT(1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_AdjPriceDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_AdjPriceDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_AdjPriceDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_EndDate]  DEFAULT ('') 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AdjPriceDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_AdjPriceDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AdjPriceDetail_His_IsSelectBatch]  DEFAULT (0) 
    

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail_His]') AND name = N'IXC_PD_AdjPriceDetail_His_BillDate') 
	CREATE CLUSTERED INDEX IXC_PD_AdjPriceDetail_His_BillDate on PD_AdjPriceDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail_His]') AND name = N'IXC_PD_AdjPriceDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_AdjPriceDetail_His_BillNo on PD_AdjPriceDetail_His ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail_His]') AND name = N'IX_PD_AdjPriceDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AdjPriceDetail_His_GoodsIDPpt12ID on PD_AdjPriceDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceDetail_His]') AND name = N'IX_PD_AdjPriceDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AdjPriceDetail_His_WhsIDWhsPtID on PD_AdjPriceDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_AdjPriceDetail_His]') and  name = 'Remark' and length=100) 
BEGIN
	 ALTER TABLE PD_AdjPriceDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO
UPDATE PD_AdjPriceDetail_His SET Remark = '' WHERE Remark IS NULL
GO	

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



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AdjPriceSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_AdjPriceSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[AdjPrice] [decimal](20,8) NULL ,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_AdjPriceSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceSerial]') AND name = N'XC_PD_AdjPriceSerial_BillDID') 
	CREATE INDEX XC_PD_AdjPriceSerial_BillDID on PD_AdjPriceSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AdjPriceSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_AdjPriceSerial_His
(
	[ID] BIGINT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[AdjPrice] [decimal](20,8) NULL ,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_AdjPriceSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AdjPriceSerial_His]') AND name = N'XC_PD_AdjPriceSerial_His_BillDID') 
	CREATE INDEX XC_PD_AdjPriceSerial_His_BillDID on PD_AdjPriceSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [InWhsID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotBill_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_AllotBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AllotBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_AllotBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AllotBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AllotBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AllotBill_Description] DEFAULT '',
	[Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_AllotBill_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AllotBill_IsDraft] DEFAULT (1),
    [BillTypeID] [int] NOT NULL,
    [InspectTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_AllotBill_InspectTag] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_AllotBill_AuditStatus] DEFAULT (0)    ,
    VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_AllotBill_VerifyElyID] DEFAULT (0),
    VerifyDate VARCHAR(20)  NULL
    CONSTRAINT [PK_PD_AllotBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill' AND a.Name='InspectTag')
	ALTER TABLE PD_AllotBill ADD InspectTag TINYINT NOT NULL CONSTRAINT [DF_PD_AllotBill_InspectTag] DEFAULT (0)

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill' AND a.Name='BillTypeID')
BEGIN
	ALTER TABLE PD_AllotBill ADD BillTypeID INT NULL
	EXEC sp_executesql N'UPDATE PD_AllotBill SET BillTypeID = 301 WHERE BillTypeID IS NULL'
	ALTER TABLE PD_AllotBill ALTER COLUMN BillTypeID INT NOT NULL
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AllotBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AllotBill_AuditStatus] DEFAULT (0) 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill' AND a.Name='VerifyElyID')
    ALTER TABLE dbo.PD_AllotBill ADD VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_AllotBill_VerifyElyID] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill' AND a.Name='VerifyDate')
    ALTER TABLE dbo.PD_AllotBill ADD VerifyDate VARCHAR(20)  NULL 



IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND name = N'IXC_PD_AllotBill_BillCode') 
	CREATE  INDEX IXC_PD_AllotBill_BillCode on PD_AllotBill ([BillCode]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND name = N'IXC_PD_AllotBill_BillDate') 
	CREATE  INDEX IXC_PD_AllotBill_BillDate on PD_AllotBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND name = N'IXC_PD_AllotBill_CreateTime') 
	CREATE  INDEX IXC_PD_AllotBill_CreateTime on PD_AllotBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND name = N'IXC_PD_AllotBill_PosTime') 
	CREATE  INDEX IXC_PD_AllotBill_PosTime on PD_AllotBill ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND name = N'IX_PD_AllotBill_WhsID') 
	CREATE  INDEX IX_PD_AllotBill_WhsID on PD_AllotBill ([OutWhsID],[InWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND name = N'IX_PD_AllotBill_DeptID') 
	CREATE  INDEX IX_PD_AllotBill_DeptID on PD_AllotBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill]') AND name = N'IX_PD_AllotBill_ElyID') 
	CREATE  INDEX IX_PD_AllotBill_ElyID on PD_AllotBill ([ElyID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [InWhsID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotBill_His_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AllotBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AllotBill_His_Description] DEFAULT '',
	[Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_IsDraft] DEFAULT (1),
    [BillTypeID] [int] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_BillTypeID] DEFAULT (0),    
    [InspectTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_AllotBill_His_InspectTag] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_AllotBill_His_AuditStatus] DEFAULT (0)    ,
    VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_AllotBill_His_VerifyElyID] DEFAULT (0),
    VerifyDate VARCHAR(20)  NULL
    CONSTRAINT [PK_PD_AllotBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill_His' AND a.Name='InspectTag')
	ALTER TABLE PD_AllotBill_His ADD InspectTag TINYINT NOT NULL CONSTRAINT [DF_PD_AllotBill_His_InspectTag] DEFAULT (0)
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AllotBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AllotBill_His_InspectTag')
	ALTER TABLE PD_AllotBill_His ADD CONSTRAINT [DF_PD_AllotBill_His_InspectTag] DEFAULT(0) FOR InspectTag
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill_His' AND a.Name='BillTypeID')
BEGIN
	ALTER TABLE PD_AllotBill_His ADD BillTypeID INT NOT NULL CONSTRAINT [DF_PD_AllotBill_His_BillTypeID] DEFAULT (0)
	EXEC sp_executesql N'UPDATE PD_AllotBill_His SET BillTypeID = 301 WHERE BillTypeID = 0 '
END
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AllotBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AllotBill_His_BillTypeID')
	ALTER TABLE PD_AllotBill_His ADD CONSTRAINT [DF_PD_AllotBill_His_BillTypeID] DEFAULT(0) FOR BillTypeID

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AllotBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AllotBill_His_AuditStatus] DEFAULT (0) 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill_His' AND a.Name='VerifyElyID')
    ALTER TABLE dbo.PD_AllotBill_His ADD VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_AllotBill_His_VerifyElyID] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotBill_His' AND a.Name='VerifyDate')
    ALTER TABLE dbo.PD_AllotBill_His ADD VerifyDate VARCHAR(20)  NULL 
    


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND name = N'IXC_PD_AllotBill_His_BillCode') 
	CREATE  INDEX IXC_PD_AllotBill_His_BillCode on PD_AllotBill_His ([BillCode]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND name = N'IXC_PD_AllotBill_His_BillDate') 
	CREATE  INDEX IXC_PD_AllotBill_His_BillDate on PD_AllotBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND name = N'IXC_PD_AllotBill_His_CreateTime') 
	CREATE  INDEX IXC_PD_AllotBill_His_CreateTime on PD_AllotBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND name = N'IXC_PD_AllotBill_His_PosTime') 
	CREATE  INDEX IXC_PD_AllotBill_His_PosTime on PD_AllotBill_His ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND name = N'IX_PD_AllotBill_His_WhsID') 
	CREATE  INDEX IX_PD_AllotBill_His_WhsID on PD_AllotBill_His ([OutWhsID],[InWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND name = N'IX_PD_AllotBill_His_DeptID') 
	CREATE  INDEX IX_PD_AllotBill_His_DeptID on PD_AllotBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotBill_His]') AND name = N'IX_PD_AllotBill_His_ElyID') 
	CREATE  INDEX IX_PD_AllotBill_His_ElyID on PD_AllotBill_His ([ElyID]) WITH (FILLFACTOR = 90);
    

    



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [ReqDID] [bigint] NOT NULL CONSTRAINT [DF_PD_AllotDetail_ReqDID] DEFAULT (0),
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AllotDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_Ppt2ID] DEFAULT (0),
    [InWhsID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_InWhsID] DEFAULT (0),
    [InWhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_InWhsPtID] DEFAULT (0),
    [OutWhsID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_OutWhsID] DEFAULT (0),
    [OutWhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_OutWhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_BSQty] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_CostPrice] DEFAULT (-1),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_GoodsCostTotal] DEFAULT (-1),
    [AllotPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_AllotPrice] DEFAULT (0),
    [AllotTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_AllotTotal] DEFAULT (0),
    [Remark] [varchar](256) NULL,    
    [InspectQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_InspectQty] DEFAULT (0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_AllotDetail_InPutPrice]  DEFAULT(1),
    [VerifyQty] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_VerifyQty] DEFAULT (0),  
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AllotDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AllotDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AllotDetail_EndDate]  DEFAULT (''), 
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AllotDetail_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_AllotDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_AllotDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_AllotDetail_InPutPrice]  DEFAULT(1)
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='InspectQty')
	ALTER TABLE PD_AllotDetail ADD InspectQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_InspectQty]  DEFAULT(0)

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='ReqDID')
	ALTER TABLE PD_AllotDetail ADD ReqDID BIGINT NOT NULL CONSTRAINT [DF_PD_AllotDetail_ReqDID] DEFAULT (0)

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='AllotPrice')
	ALTER TABLE PD_AllotDetail ADD AllotPrice decimal(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_AllotPrice] DEFAULT (0)
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='AllotTotal')
	ALTER TABLE PD_AllotDetail ADD AllotTotal decimal(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_AllotTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='VerifyQty')
    ALTER TABLE dbo.PD_AllotDetail ADD VerifyQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_VerifyQty] DEFAULT (0)      
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_AllotDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AllotDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_AllotDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AllotDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='EndDate')
    ALTER TABLE PD_AllotDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AllotDetail_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_AllotDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AllotDetail_IsSelectBatch]  DEFAULT (0)
    

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail]') AND name = N'IXC_PD_AllotDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_AllotDetail_BillDate on PD_AllotDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail]') AND name = N'IXC_PD_AllotDetail_BillNo') 
	CREATE  INDEX IXC_PD_AllotDetail_BillNo on PD_AllotDetail ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail]') AND name = N'IX_PD_AllotDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AllotDetail_GoodsIDPpt12ID on PD_AllotDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail]') AND name = N'IX_PD_AllotDetail_InWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotDetail_InWhsIDWhsPtID on PD_AllotDetail ([InWhsID],[InWhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail]') AND name = N'IX_PD_AllotDetail_OutWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotDetail_OutWhsIDWhsPtID on PD_AllotDetail ([OutWhsID],[OutWhsPtID]) WITH (FILLFACTOR = 90);
	
IF  EXISTS(
  SELECT a.Name FROM syscolumns a
  INNER JOIN sysobjects  b
  ON a.ID=b.ID
  WHERE b.Name='PD_AllotDetail' AND a.Name='Remark' AND a.[length] = 100
    )
BEGIN
  ALTER TABLE PD_AllotDetail 
  ALTER COLUMN Remark VARCHAR(256)
END

GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotDetail_His]
(
    [DID] [bigint] NOT NULL,
    [ReqDID] [bigint] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_ReqDID] DEFAULT (0),
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_Ppt2ID] DEFAULT (0),
    [InWhsID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_InWhsID] DEFAULT (0),
    [InWhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_InWhsPtID] DEFAULT (0),
    [OutWhsID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_OutWhsID] DEFAULT (0),
    [OutWhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_OutWhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_BSQty] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_CostPrice] DEFAULT (-1),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_GoodsCostTotal] DEFAULT (-1),
    [AllotPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_AllotPrice] DEFAULT (0),
    [AllotTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_AllotTotal] DEFAULT (0),
    [Remark] [varchar](256) NULL,    
    [InspectQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_InspectQty]  DEFAULT(0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_InPutPrice]  DEFAULT(1),
    [VerifyQty] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_VerifyQty] DEFAULT (0) ,
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_EndDate]  DEFAULT (''), 
	[IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_IsSelectBatch]  DEFAULT (0)
    CONSTRAINT [PK_PD_AllotDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='InPutPrice')
    ALTER TABLE PD_AllotDetail_His ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_InPutPrice]  DEFAULT(1)
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='InspectQty')
	ALTER TABLE PD_AllotDetail_His ADD InspectQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_InspectQty]  DEFAULT(0)
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AllotDetail_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AllotDetail_His_InspectQty')
	ALTER TABLE PD_AllotDetail_His ADD CONSTRAINT [DF_PD_AllotDetail_His_InspectQty] DEFAULT(0) FOR InspectQty

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='ReqDID')
	ALTER TABLE PD_AllotDetail_His ADD ReqDID BIGINT NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_ReqDID] DEFAULT (0)

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='AllotPrice')
	ALTER TABLE PD_AllotDetail_His ADD AllotPrice decimal(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_AllotPrice] DEFAULT (0)
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='AllotTotal')
	ALTER TABLE PD_AllotDetail_His ADD AllotTotal decimal(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_AllotTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='VerifyQty')
    ALTER TABLE dbo.PD_AllotDetail_His ADD VerifyQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_VerifyQty] DEFAULT (0)      
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_AllotDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_AllotDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_AllotDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_AllotDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AllotDetail_His_IsSelectBatch]  DEFAULT (0)


	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail_His]') AND name = N'IXC_PD_AllotDetail_His_BillDate') 
	CREATE CLUSTERED INDEX IXC_PD_AllotDetail_His_BillDate on PD_AllotDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail_His]') AND name = N'IXC_PD_AllotDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_AllotDetail_His_BillNo on PD_AllotDetail_His ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail_His]') AND name = N'IX_PD_AllotDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AllotDetail_His_GoodsIDPpt12ID on PD_AllotDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail_His]') AND name = N'IX_PD_AllotDetail_His_InWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotDetail_His_InWhsIDWhsPtID on PD_AllotDetail_His ([InWhsID],[InWhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotDetail_His]') AND name = N'IX_PD_AllotDetail_His_OutWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotDetail_His_OutWhsIDWhsPtID on PD_AllotDetail_His ([OutWhsID],[OutWhsPtID]) WITH (FILLFACTOR = 90);
	
	--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_AllotDetail_His]') and  name = 'Remark' and length=100) 
BEGIN
	 ALTER TABLE PD_AllotDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotReqBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [datetime] NOT NULL,
    [InWhsID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [DlvDate] [datetime] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AllotReqBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AllotReqBill_Description] DEFAULT '',
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotReqBill_BillQty] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_AllotReqBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AllotReqBill_CreateTime] DEFAULT getdate(),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_AllotReqBill_StopTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AllotReqBill_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_AllotReqBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_AllotReqBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill]') AND name = N'PK_PD_AllotReqBill' AND type_desc = 'NONCLUSTERED') 
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AllotReqBill' AND so.xtype = 'PK' AND so.name = 'PK_PD_AllotReqBill')
			ALTER TABLE PD_AllotReqBill DROP CONSTRAINT [PK_PD_AllotReqBill]
		ALTER TABLE PD_AllotReqBill ADD CONSTRAINT [PK_PD_AllotReqBill] PRIMARY KEY CLUSTERED ([BillNo])
	END
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqBill' AND a.Name='IsDraft')
BEGIN
    ALTER TABLE dbo.PD_AllotReqBill ADD [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AllotReqBill_IsDraft] DEFAULT (1)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill]') AND name = N'IXC_PD_AllotReqBill_BillDate') 
	CREATE  INDEX IXC_PD_AllotReqBill_BillDate on PD_AllotReqBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill]') AND name = N'IX_PD_AllotReqBill_WhsID') 
	CREATE  INDEX IX_PD_AllotReqBill_WhsID on PD_AllotReqBill ([OutWhsID],[InWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill]') AND name = N'IX_PD_AllotReqBill_DeptID') 
	CREATE  INDEX IX_PD_AllotReqBill_DeptID on PD_AllotReqBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill]') AND name = N'IX_PD_AllotReqBill_ElyID') 
	CREATE  INDEX IX_PD_AllotReqBill_ElyID on PD_AllotReqBill ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AllotReqBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AllotReqBill_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotReqBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [datetime] NOT NULL,
    [InWhsID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [DlvDate] [datetime] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [Summary] [varchar](256) NOT NULL,
    [Description] [varchar](100) NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL,
    [Creator] [int] NOT NULL,
    [CreateTime] [datetime] NOT NULL,
    [StopTag] [tinyint] NOT NULL,
    [IsDraft] [bit] NOT NULL,
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_AllotReqBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_AllotReqBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill_His]') AND name = N'PK_PD_AllotReqBill_His' AND type_desc = 'NONCLUSTERED') 
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AllotReqBill_His' AND so.xtype = 'PK' AND so.name = 'PK_PD_AllotReqBill_His')
			ALTER TABLE PD_AllotReqBill_His DROP CONSTRAINT [PK_PD_AllotReqBill_His]
		ALTER TABLE PD_AllotReqBill_His ADD CONSTRAINT [PK_PD_AllotReqBill_His] PRIMARY KEY CLUSTERED ([BillNo])
	END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqBill_His' AND a.Name='IsDraft')
BEGIN
    ALTER TABLE dbo.PD_AllotReqBill_His ADD [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AllotReqBill_His_IsDraft] DEFAULT (1) 
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill_His]') AND name = N'IXC_PD_AllotReqBill_His_BillDate') 
	CREATE  INDEX IXC_PD_AllotReqBill_His_BillDate on PD_AllotReqBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill_His]') AND name = N'IX_PD_AllotReqBill_His_WhsID') 
	CREATE  INDEX IX_PD_AllotReqBill_His_WhsID on PD_AllotReqBill_His ([OutWhsID],[InWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill_His]') AND name = N'IX_PD_AllotReqBill_His_DeptID') 
	CREATE  INDEX IX_PD_AllotReqBill_His_DeptID on PD_AllotReqBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqBill_His]') AND name = N'IX_PD_AllotReqBill_His_ElyID') 
	CREATE  INDEX IX_PD_AllotReqBill_His_ElyID on PD_AllotReqBill_His ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AllotReqBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AllotReqBill_His_AuditStatus] DEFAULT (0) 





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotReqDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [GoodsID] [int] NOT NULL,
    [BarCode] [varchar](100) NOT NULL,
    [Ppt1ID] [int] NOT NULL,
    [Ppt2ID] [int] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [OutWhsPtID] [int] NOT NULL,
    [InWhsID] [int] NOT NULL,
    [InWhsPtID] [int] NOT NULL,
    [UnitID] [int] NOT NULL,
    [Convfactor] [decimal](20,8) NOT NULL,
    [Qty] [decimal](20,8) NOT NULL,
    [BSQty] [decimal](20,8) NOT NULL,
    [Remark] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_Remark] DEFAULT '',
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_StopTag] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_ComTotal] DEFAULT (0),
    [InspectQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_InspectQty] DEFAULT (0),
    CONSTRAINT [PK_PD_AllotReqDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqDetail' AND a.Name='BillDate')
	BEGIN
		ALTER TABLE PD_AllotReqDetail ADD BillDate DATE NULL
		EXEC sp_executesql N'UPDATE a SET a.BillDate = b.BillDate FROM PD_AllotReqDetail a INNER JOIN PD_AllotReqBill b ON a.BillNo = b.BillNo'
		ALTER TABLE PD_AllotReqDetail ALTER COLUMN BillDate DATE NOT NULL
	END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqDetail' AND a.Name='InspectQty')
    ALTER TABLE PD_AllotReqDetail ADD InspectQty [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_InspectQty] DEFAULT (0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail]') AND name = N'IXC_PD_AllotReqDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_AllotReqDetail_BillDate on PD_AllotReqDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail]') AND name = N'IXC_PD_AllotReqDetail_BillNo') 
	CREATE  INDEX IXC_PD_AllotReqDetail_BillNo on PD_AllotReqDetail ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail]') AND name = N'IX_PD_AllotReqDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AllotReqDetail_GoodsIDPpt12ID on PD_AllotReqDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail]') AND name = N'IX_PD_AllotReqDetail_InWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotReqDetail_InWhsIDWhsPtID on PD_AllotReqDetail ([InWhsID],[InWhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail]') AND name = N'IX_PD_AllotReqDetail_OutWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotReqDetail_OutWhsIDWhsPtID on PD_AllotReqDetail ([OutWhsID],[OutWhsPtID]) WITH (FILLFACTOR = 90);
	
	
--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_AllotReqDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_AllotReqDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AllotReqDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [GoodsID] [int] NOT NULL,
    [BarCode] [varchar](100) NOT NULL,
    [Ppt1ID] [int] NOT NULL,
    [Ppt2ID] [int] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [OutWhsPtID] [int] NOT NULL,
    [InWhsID] [int] NOT NULL,
    [InWhsPtID] [int] NOT NULL,
    [UnitID] [int] NOT NULL,
    [Convfactor] [decimal](20,8) NOT NULL,
    [Qty] [decimal](20,8) NOT NULL,
    [BSQty] [decimal](20,8) NOT NULL,
    [Remark] [varchar](256) NOT NULL,
    [StopTag] [tinyint] NOT NULL,
    [ComQty] [decimal](20,8) NOT NULL,
    [ComTotal] [decimal](20,8) NOT NULL,
    [InspectQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_His_InspectQty]  DEFAULT(0),
    CONSTRAINT [PK_PD_AllotReqDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqDetail_His' AND a.Name='BillDate')
	BEGIN
		ALTER TABLE PD_AllotReqDetail_His ADD BillDate DATE NULL
		EXEC sp_executesql N'UPDATE a SET a.BillDate = b.BillDate FROM PD_AllotReqDetail_His a INNER JOIN PD_AllotReqBill_His b ON a.BillNo = b.BillNo'
		ALTER TABLE PD_AllotReqDetail_His ALTER COLUMN BillDate DATE NOT NULL
	END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AllotReqDetail_His' AND a.Name='InspectQty')
    ALTER TABLE PD_AllotReqDetail_His ADD InspectQty [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AllotReqDetail_His_InspectQty]  DEFAULT(0)
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AllotReqDetail_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AllotReqDetail_His_InspectQty')
	ALTER TABLE PD_AllotReqDetail_His ADD CONSTRAINT [DF_PD_AllotReqDetail_His_InspectQty] DEFAULT(0) FOR InspectQty

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail_His]') AND name = N'IXC_PD_AllotReqDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_AllotReqDetail_His_BillDate on PD_AllotReqDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail_His]') AND name = N'IXC_PD_AllotReqDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_AllotReqDetail_His_BillNo on PD_AllotReqDetail_His ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail_His]') AND name = N'IX_PD_AllotReqDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AllotReqDetail_His_GoodsIDPpt12ID on PD_AllotReqDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail_His]') AND name = N'IX_PD_AllotReqDetail_His_InWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotReqDetail_His_InWhsIDWhsPtID on PD_AllotReqDetail_His ([InWhsID],[InWhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotReqDetail_His]') AND name = N'IX_PD_AllotReqDetail_His_OutWhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AllotReqDetail_His_OutWhsIDWhsPtID on PD_AllotReqDetail_His ([OutWhsID],[OutWhsPtID]) WITH (FILLFACTOR = 90);

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_AllotReqDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_AllotReqDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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




/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_AllotSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
	[BillTypeID] INT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[AllotPrice] DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_AllotSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotSerial]') AND name = N'XC_PD_AllotSerial_BillDID') 
	CREATE INDEX XC_PD_AllotSerial_BillDID on PD_AllotSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AllotSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_AllotSerial_His
(
	[ID] BIGINT NOT NULL,
	[BillTypeID] INT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[AllotPrice] DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_AllotSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AllotSerial_His]') AND name = N'XC_PD_AllotSerial_His_BillDID') 
	CREATE INDEX XC_PD_AllotSerial_His_BillDID on PD_AllotSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AssemblyBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [OutBillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyBill_OutBillQty] DEFAULT (0),
    [OutTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyBill_OutTotal] DEFAULT (0),
    [InWhsID] [int] NOT NULL,
    [InBillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyBill_InBillQty] DEFAULT (0),
    [InTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyBill_InTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AssemblyBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AssemblyBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_IsDraft] DEFAULT (1),
    [AssemblyCalcCost] BIT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_AssemblyCalcCost] DEFAULT (0),
    [AssemblyType] [tinyint] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_AssemblyType] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_AssemblyBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill' AND a.Name='AssemblyCalcCost')
    ALTER TABLE PD_AssemblyBill ADD AssemblyCalcCost BIT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_AssemblyCalcCost] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill' AND a.Name='AssemblyType')
    ALTER TABLE PD_AssemblyBill ADD AssemblyType TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_AssemblyType] DEFAULT (0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IXC_PD_AssemblyBill_BillCode') 
	CREATE INDEX IXC_PD_AssemblyBill_BillCode on PD_AssemblyBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IXC_PD_AssemblyBill_CreateTime') 
	CREATE INDEX IXC_PD_AssemblyBill_CreateTime on PD_AssemblyBill ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IXC_PD_AssemblyBill_PosTime') 
	CREATE INDEX IXC_PD_AssemblyBill_PosTime on PD_AssemblyBill ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IXC_PD_AssemblyBill_BillDate') 
	CREATE INDEX IXC_PD_AssemblyBill_BillDate on PD_AssemblyBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IX_PD_AssemblyBill_OutWhsID') 
	CREATE  INDEX IX_PD_AssemblyBill_OutWhsID on PD_AssemblyBill ([OutWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IX_PD_AssemblyBill_InWhsID') 
	CREATE  INDEX IX_PD_AssemblyBill_InWhsID on PD_AssemblyBill ([InWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IX_PD_AssemblyBill_DeptID') 
	CREATE  INDEX IX_PD_AssemblyBill_DeptID on PD_AssemblyBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'IX_PD_AssemblyBill_ElyID') 
	CREATE  INDEX IX_PD_AssemblyBill_ElyID on PD_AssemblyBill ([ElyID]) WITH (FILLFACTOR = 90);

IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill]') AND name = N'PK_PD_AssemblyBill' AND type_desc = 'NONCLUSTERED') 
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyBill' AND so.xtype = 'PK' AND so.name = 'PK_PD_AssemblyBill')
			ALTER TABLE PD_AssemblyBill DROP CONSTRAINT [PK_PD_AssemblyBill]
		ALTER TABLE PD_AssemblyBill ADD CONSTRAINT [PK_PD_AssemblyBill] PRIMARY KEY CLUSTERED ([BillNo])
	END

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill' AND a.Name='PosElyID')
   AND NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyBill' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyBill_PosElyID')
    ALTER TABLE PD_AssemblyBill ADD CONSTRAINT [DF_PD_AssemblyBill_PosElyID] DEFAULT (0) for PosElyID

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill' AND a.Name='PosTime')
   AND NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyBill' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyBill_PosTime')
    ALTER TABLE PD_AssemblyBill ADD CONSTRAINT [DF_PD_AssemblyBill_PosTime] DEFAULT '' for PosTime   
    
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='PD_AssemblyBill' AND a.Name='AssemblyCalcCost' AND c.name = 'tinyint')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyBill' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyBill_AssemblyCalcCost')
			ALTER TABLE PD_AssemblyBill DROP CONSTRAINT [DF_PD_AssemblyBill_AssemblyCalcCost]
		ALTER TABLE PD_AssemblyBill ALTER COLUMN AssemblyCalcCost BIT NOT NULL
		ALTER TABLE PD_AssemblyBill ADD CONSTRAINT [DF_PD_AssemblyBill_AssemblyCalcCost] DEFAULT(0) FOR AssemblyCalcCost
    END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AssemblyBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AssemblyBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [OutWhsID] [int] NOT NULL,
    [OutBillQty] [decimal](20,8) NOT NULL,
    [OutTotal] [decimal](20,8) NOT NULL,
    [InWhsID] [int] NOT NULL,
    [InBillQty] [decimal](20,8) NOT NULL,
    [InTotal] [decimal](20,8) NOT NULL,
    [Creator] [int] NOT NULL,
    [CreateTime] [datetime] NOT NULL,
    [PosElyID] [int] NOT NULL,
    [PosTime] [datetime] NOT NULL,
    [Summary] [varchar](256) NOT NULL,
    [Description] [varchar](100) NOT NULL,
    [Red] [tinyint] NOT NULL,
    [IsDraft] [bit] NOT NULL,    
    [AssemblyCalcCost] BIT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_His_AssemblyCalcCost] DEFAULT (0),
    [AssemblyType] [tinyint] NOT NULL CONSTRAINT [DF_PD_AssemblyBill_His_AssemblyType] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_AssemblyBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill_His' AND a.Name='AssemblyCalcCost')
    ALTER TABLE PD_AssemblyBill_His ADD AssemblyCalcCost BIT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_His_AssemblyCalcCost] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill_His' AND a.Name='AssemblyType')
    ALTER TABLE PD_AssemblyBill_His ADD AssemblyType TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_His_AssemblyType] DEFAULT (0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IXC_PD_AssemblyBill_His_BillCode') 
	CREATE INDEX IXC_PD_AssemblyBill_His_BillCode on PD_AssemblyBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IXC_PD_AssemblyBill_His_CreateTime') 
	CREATE INDEX IXC_PD_AssemblyBill_His_CreateTime on PD_AssemblyBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IXC_PD_AssemblyBill_His_PosTime') 
	CREATE INDEX IXC_PD_AssemblyBill_His_PosTime on PD_AssemblyBill_His ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IXC_PD_AssemblyBill_His_BillDate') 
	CREATE INDEX IXC_PD_AssemblyBill_His_BillDate on PD_AssemblyBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IX_PD_AssemblyBill_His_OutWhsID') 
	CREATE  INDEX IX_PD_AssemblyBill_His_OutWhsID on PD_AssemblyBill_His ([OutWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IX_PD_AssemblyBill_His_InWhsID') 
	CREATE  INDEX IX_PD_AssemblyBill_His_InWhsID on PD_AssemblyBill_His ([InWhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IX_PD_AssemblyBill_His_DeptID') 
	CREATE  INDEX IX_PD_AssemblyBill_His_DeptID on PD_AssemblyBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'IX_PD_AssemblyBill_His_ElyID') 
	CREATE  INDEX IX_PD_AssemblyBill_His_ElyID on PD_AssemblyBill_His ([ElyID]) WITH (FILLFACTOR = 90);

IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyBill_His]') AND name = N'PK_PD_AssemblyBill_His' AND type_desc = 'NONCLUSTERED') 
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyBill_His' AND so.xtype = 'PK' AND so.name = 'PK_PD_AssemblyBill_His')
			ALTER TABLE PD_AssemblyBill_His DROP CONSTRAINT [PK_PD_AssemblyBill_His]
		ALTER TABLE PD_AssemblyBill_His ADD CONSTRAINT [PK_PD_AssemblyBill_His] PRIMARY KEY CLUSTERED ([BillNo])
	END
	
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
             INNER JOIN sys.types c ON a.system_type_id = c.system_type_id 
            WHERE b.Name='PD_AssemblyBill_His' AND a.Name='AssemblyCalcCost' AND c.name = 'tinyint')
		ALTER TABLE PD_AssemblyBill_His ALTER COLUMN AssemblyCalcCost BIT NOT NULL
			
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyBill_His_AssemblyCalcCost')
	ALTER TABLE PD_AssemblyBill_His ADD CONSTRAINT [DF_PD_AssemblyBill_His_AssemblyCalcCost] DEFAULT(0) FOR AssemblyCalcCost
			
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyBill_His_AssemblyType')
	ALTER TABLE PD_AssemblyBill_His ADD CONSTRAINT [DF_PD_AssemblyBill_His_AssemblyType] DEFAULT(0) FOR AssemblyType
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_AssemblyBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyBill_His_AuditStatus] DEFAULT (0) 





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AssemblyDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_BSQty] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_CostPrice] DEFAULT (0),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_Price] DEFAULT (0),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_GoodsCostTotal] DEFAULT (0),
    [Remark] [varchar](256) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_Remark] DEFAULT (0),
    [DetailType] [tinyint] NOT NULL,    
    [GroupID] [smallint] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_GroupID] DEFAULT (0),
    [AssemblyCost] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_AssemblyCost] DEFAULT (0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_InPutPrice]  DEFAULT(1),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_EndDate]  DEFAULT (''), 
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_AssemblyDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_AssemblyDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_InPutPrice]  DEFAULT(1)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='AssemblyCost')
    ALTER TABLE PD_AssemblyDetail ADD AssemblyCost [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_AssemblyCost] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='GroupID')
    ALTER TABLE PD_AssemblyDetail ADD GroupID SMALLINT NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_GroupID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='BillDate')
	BEGIN
		ALTER TABLE PD_AssemblyDetail ADD BillDate DATE NULL
		EXEC sp_executesql N'UPDATE a SET a.BillDate = b.BillDate FROM PD_AssemblyDetail a INNER JOIN PD_AssemblyBill b ON a.BillNo = b.BillNo'
		ALTER TABLE PD_AssemblyDetail ALTER COLUMN BillDate DATE NOT NULL
	END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_AssemblyDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_AssemblyDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='EndDate')
    ALTER TABLE PD_AssemblyDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_AssemblyDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_IsSelectBatch]  DEFAULT (0)
    

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail]') AND name = N'IXC_PD_AssemblyDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_AssemblyDetail_BillDate on PD_AssemblyDetail ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail]') AND name = N'IXC_PD_AssemblyDetail_BillNo') 
	CREATE  INDEX IXC_PD_AssemblyDetail_BillNo on PD_AssemblyDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail]') AND name = N'IX_PD_AssemblyDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AssemblyDetail_GoodsIDPpt12ID on PD_AssemblyDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail]') AND name = N'IX_PD_AssemblyDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AssemblyDetail_WhsIDWhsPtID on PD_AssemblyDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_AssemblyDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_AssemblyDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AssemblyDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL,
    [Ppt2ID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [WhsPtID] [int] NOT NULL,
    [UnitID] [int] NOT NULL,
    [Convfactor] [int] NOT NULL,
    [Qty] [decimal](20,8) NOT NULL,
    [BSQty] [decimal](20,8) NOT NULL,
    [CostPrice] [decimal](20,8) NOT NULL,
    [Price] [decimal](20,8) NOT NULL,
    [GoodsCostTotal] [decimal](20,8) NOT NULL,
    [Remark] [varchar](256) NOT NULL,
    [DetailType] [tinyint] NOT NULL,    
    [GroupID] [smallint] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_GroupID] DEFAULT (0),
    [AssemblyCost] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_AssemblyCost] DEFAULT (0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_InPutPrice]  DEFAULT(1),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_EndDate]  DEFAULT (''), 
	[IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_IsSelectBatch]  DEFAULT (0)
    CONSTRAINT [PK_PD_AssemblyDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='InPutPrice')
    ALTER TABLE PD_AssemblyDetail_His ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_InPutPrice]  DEFAULT(1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='AssemblyCost')
    ALTER TABLE PD_AssemblyDetail_His ADD AssemblyCost [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_AssemblyCost] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='GroupID')
    ALTER TABLE PD_AssemblyDetail_His ADD GroupID SMALLINT NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_GroupID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='BillDate')
    BEGIN
		ALTER TABLE PD_AssemblyDetail_His ADD BillDate DATE NULL
		EXEC sp_executesql N'UPDATE a SET a.BillDate = b.BillDate FROM PD_AssemblyDetail_His a INNER JOIN PD_AssemblyBill_His b ON a.BillNo = b.BillNo'
		ALTER TABLE PD_AssemblyDetail_His ALTER COLUMN BillDate DATE NOT NULL
    END
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyDetail_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyDetail_His_InPutPrice')
	ALTER TABLE PD_AssemblyDetail_His ADD CONSTRAINT [DF_PD_AssemblyDetail_His_InPutPrice] DEFAULT(1) FOR InPutPrice
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyDetail_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyDetail_His_AssemblyCost')
	ALTER TABLE PD_AssemblyDetail_His ADD CONSTRAINT [DF_PD_AssemblyDetail_His_AssemblyCost] DEFAULT(0) FOR AssemblyCost
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_AssemblyDetail_His' AND so.xtype = 'D' AND so.name = 'DF_PD_AssemblyDetail_His_GroupID')
	ALTER TABLE PD_AssemblyDetail_His ADD CONSTRAINT [DF_PD_AssemblyDetail_His_GroupID] DEFAULT(0) FOR GroupID
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_AssemblyDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_AssemblyDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_AssemblyDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_EndDate]  DEFAULT ('') 
    	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_AssemblyDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_AssemblyDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_AssemblyDetail_His_IsSelectBatch]  DEFAULT (0)
    	
	

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail_His]') AND name = N'IXC_PD_AssemblyDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_AssemblyDetail_His_BillDate on PD_AssemblyDetail_His ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail_His]') AND name = N'IXC_PD_AssemblyDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_AssemblyDetail_His_BillNo on PD_AssemblyDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail_His]') AND name = N'IX_PD_AssemblyDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_AssemblyDetail_His_GoodsIDPpt12ID on PD_AssemblyDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblyDetail_His]') AND name = N'IX_PD_AssemblyDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_AssemblyDetail_His_WhsIDWhsPtID on PD_AssemblyDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_AssemblyDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_AssemblyDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AssemblySerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_AssemblySerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_AssemblySerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblySerial]') AND name = N'XC_PD_AssemblySerial_BillDID') 
	CREATE INDEX XC_PD_AssemblySerial_BillDID on PD_AssemblySerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AssemblySerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_AssemblySerial_His
(
	[ID] BIGINT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_AssemblySerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_AssemblySerial_His]') AND name = N'XC_PD_AssemblySerial_His_BillDID') 
	CREATE INDEX XC_PD_AssemblySerial_His_BillDID on PD_AssemblySerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AuditingBill]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_AuditingBill
(
    [ID] INT IDENTITY(1,1) NOT NULL,
	[BillNo] BIGINT NOT NULL,
	[BillTypeID] INT NOT NULL,
	[AuditSetID] INT,
	[AuditingLevels] [varchar](5) NOT NULL,
	[IfAudit] TINYINT NOT NULL CONSTRAINT [DF_PD_AuditingBill_IfAudit]  DEFAULT(0),
	[SignElyID] INT NULL,
	[SignStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_AuditingBill_SignStatus]  DEFAULT(0),
	[SpecElyID] INT,
    CONSTRAINT [PK_PD_AuditingBill] PRIMARY KEY NONCLUSTERED ([ID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_BillAuditEly]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_BillAuditEly
(
    [ID] INT IDENTITY(1,1) NOT NULL,
    [AuditStepID] INT NOT NULL,
	[ElyID] INT NOT NULL,
    CONSTRAINT [PK_PD_BillAuditEly] PRIMARY KEY NONCLUSTERED ([ID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_BillAuditStep]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_BillAuditStep
(
    [ID] INT IDENTITY(1,1) NOT NULL,
    [AuditingID] INT NOT NULL,
	[StepID] INT NOT NULL,
	[SetpName] [varchar](50)NOT NULL,
	[Type] TINYINT,
	[Level] TINYINT,
	[AuditType] TINYINT NULL,
	[AuditElyID] INT NOT NULL CONSTRAINT [DF_PD_BillAuditStep_AuditElyID] DEFAULT(0),
	[StepReason] VARCHAR(2000) NOT NULL,
	[AuditDate] DATE NULL,
	[Status] TINYINT NOT NULL CONSTRAINT [DF_PD_BillAuditStep_Status] DEFAULT(0),
	[Explain] VARCHAR(200) NULL,
    CONSTRAINT [PK_PD_BillAuditStep] PRIMARY KEY NONCLUSTERED ([ID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_BillNoSeed]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_BillNoSeed]
(
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillType] [int] NOT NULL,
    [Seed] [int] NOT NULL,
    [CDate] [date] NOT NULL,
    CONSTRAINT [PK_PD_BillNoSeed] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_BillNoSeed]') AND name = N'IXC_PD_BillNoSeed_BillTypeCDate') 
	CREATE UNIQUE CLUSTERED  INDEX IXC_PD_BillNoSeed_BillTypeCDate on PD_BillNoSeed ([BillType],[CDate]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_BillType]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_BillType]
(
    [BillTypeID] [int] NOT NULL,
    [BillName] [varchar](50) NOT NULL,
    [BillCode] [varchar](5) NOT NULL,
    [BillTable] [varchar](50) NOT NULL CONSTRAINT [DF_PD_BillType_BillTable] DEFAULT '',
    [BillDetail] [varchar](50) NOT NULL CONSTRAINT [DF_PD_BillType_BillDetail] DEFAULT '',
    [CanPost] [TINYINT] NOT NULL,
    [SettleType] [TINYINT] NOT NULL,
    [InOutType] [TINYINT] NOT NULL,
    [BillSerial] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_BillType_BillSerial] 	DEFAULT('')
    CONSTRAINT [PK_PD_BillType] PRIMARY KEY CLUSTERED ([BillTypeID])
)

END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PD_BillType' AND a.Name='SortId'
)
BEGIN
	ALTER TABLE PD_BillType ADD SortId int DEFAULT 0 NOT NULL	
END

IF NOT EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PD_BillType' AND a.Name='BillSerial'
)
BEGIN
	ALTER TABLE PD_BillType ADD BillSerial VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_BillType_BillSerial] 	DEFAULT('')
END

go

TRUNCATE table  [PD_BillType]
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (100,'采购订单','CD','PD_PchOrdBill','PD_PchOrdDetail',0,0,0,10);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (101,'采购入库单','CR','PD_PchBill','PD_PchDetail',1,2,1,20,'PD_PchSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (102,'采购退货单','CT','PD_PchRetBill','PD_PchRetDetail',1,2,2,30,'PD_PchRetSerial');

INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (200,'销售订单','XD','PD_SellOrdBill','PD_SellOrdDetail',0,0,0,40);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (201,'销售出库单','XC','PD_SellBill','PD_SellDetail',1,1,2,50,'PD_SellSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (202,'销售退货单','XT','PD_SellRetBill','PD_SellRetDetail',1,1,1,60,'PD_SellRetSerial');


INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (308,'调拨申请单','DS','PD_AllotReqBill','PD_AllotReqDetail',0,0,0,70);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (301,'同价调拨单','DB','PD_AllotBill','PD_AllotDetail',1,0,3,80,'PD_AllotSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (309,'变价调拨单','CB','PD_AllotBill','PD_AllotDetail',1,0,3,90,'PD_AllotSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (302,'调价单','TJ','PD_AdjPriceBill','PD_AdjPriceDetail',1,0,3,100,'PD_AdjPriceSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (303,'其他入库单','QR','PD_InOutWhsBill','PD_InOutWhsDetail',1,0,1,110,'PD_InOutWhsSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (304,'其他出库单','QC','PD_InOutWhsBill','PD_InOutWhsDetail',1,0,2,120,'PD_InOutWhsSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (310,'生产拆装单','CZ','PD_AssemblyBill','PD_AssemblyDetail',1,0,3,125,'PD_AssemblySerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (305,'报损单','BS','PD_LossSpillBill','PD_LossSpillDetail',1,0,2,130,'PD_LossSpillSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (306,'报溢单','BY','PD_LossSpillBill','PD_LossSpillDetail',1,0,1,140,'PD_LossSpillSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (307,'库存盘点','PD','PD_StockBill','PD_StockDetail',0,0,0,150,'PD_StockSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (311,'生产模板','CM','PD_ProduceModelBill','PD_ProduceModelDetail',0,0,0,160);

INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (401,'付款单','FK','MF_PayRecBill','MF_PayRecDetail',1,0,0,160);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (402,'收款单','SK','MF_PayRecBill','MF_PayRecDetail',1,0,0,170);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (403,'现金费用单','XF','MF_FeeRecBill','MF_FeeRecDetail',1,0,0,180);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (404,'一般费用单','FY','MF_FeeRecBill','MF_FeeRecDetail',1,2,0,190);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (405,'其他收入单','QS','MF_FeeRecBill','MF_FeeRecDetail',1,1,0,200);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (406,'转款单','ZK','MF_TransferBill','MF_TransferDetail',1,0,0,210);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (501,'应收增加单','FK','MF_ARAPBill','MF_ARAPDetail',1,1,0,220);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (502,'应收减少单','SK','MF_ARAPBill','MF_ARAPDetail',1,1,0,230);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (503,'应付增加单','XF','MF_ARAPBill','MF_ARAPDetail',1,2,0,240);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (504,'应付减少单','FY','MF_ARAPBill','MF_ARAPDetail',1,2,0,250);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (507,'采购发票','CP','MF_PchInvoiceBill','MF_PchInvoiceDetail',0,0,0,260);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (508,'销售发票','XP','MF_SellInvoiceBill','MF_SellInvoiceDetail',0,0,0,270);

INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId,BillSerial) values (600,'积分兑换单','EC','PD_InOutWhsBill','PD_InOutWhsDetail',1,0,2,280,'PD_InOutWhsSerial');
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (602,'会员充值单','HC','VS_VipChargeBill','VS_VipChargeDetail',1,0,0,290);

INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (998,'期初应收单','','','',0,1,0,998);
INSERT INTO [PD_BillType] ([BillTypeID],[BillName],[BillCode],[BillTable],[BillDetail],[CanPost],[SettleType],[InOutType],SortId) values (999,'期初应付单','','','',0,2,0,999);

GO




/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_GoodsSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[WhsID] INT NOT NULL,
	[WhsPtID] INT NOT NULL,
	[GoodsID] INT NOT NULL,
	[Ppt1ID] INT NOT NULL CONSTRAINT [DF_PD_GoodsSerial_Ppt1ID] DEFAULT(0),
	[Ppt2ID] INT NOT NULL CONSTRAINT [DF_PD_GoodsSerial_Ppt2ID] DEFAULT(0),
	[CostPrice]	DECIMAL(20,8) NULL,
	[InBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_InBTypeID]  DEFAULT (0),
	[OutBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_OutBTypeID]  DEFAULT (0),
	[InTime] [datetime] NULL,
	[OutTime] [datetime] NULL,
	[Remark] [varchar](256) NULL,
	[Flag] [TINYINT] NOT NULL CONSTRAINT [DF_PD_GoodsSerial_Flag]  DEFAULT (1),
	[IsOpening] [bit] NOT NULL CONSTRAINT [DF_PD_GoodsSerial_IsOpening]  DEFAULT (0),
	[BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_GoodsSerial_EndDate]  DEFAULT (''),
    CONSTRAINT [PK_PD_GoodsSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

--=============================================修改表结构===============================================================

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial' AND a.Name='CostPrice')
    ALTER TABLE PD_GoodsSerial ADD CostPrice DECIMAL(20,8)  NULL  
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial' AND a.Name='IsOpening')
    ALTER TABLE PD_GoodsSerial ADD [IsOpening] [bit] NOT NULL CONSTRAINT [DF_PD_GoodsSerial_IsOpening]  DEFAULT (0)   
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial' AND a.Name='InBTypeID')
    ALTER TABLE PD_GoodsSerial ADD [InBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_InBTypeID]  DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial' AND a.Name='OutBTypeID')
    ALTER TABLE PD_GoodsSerial ADD [OutBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_OutBTypeID]  DEFAULT (0)        

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial' AND a.Name='BatchNumber')
    ALTER TABLE PD_GoodsSerial ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial' AND a.Name='ProductDate')
    ALTER TABLE PD_GoodsSerial ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial' AND a.Name='EndDate')
    ALTER TABLE PD_GoodsSerial ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_GoodsSerial_EndDate]  DEFAULT ('') 

IF EXISTS (
	SELECT a.Name 
	FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
	INNER JOIN sys.types c ON  a.system_type_id = c.system_type_id
	 WHERE b.Name='PD_GoodsSerial' AND a.Name='IsOpening' AND c.name<>'tinyint')
BEGIN
	ALTER TABLE PD_GoodsSerial DROP CONSTRAINT DF_PD_GoodsSerial_Flag
    ALTER TABLE PD_GoodsSerial ALTER COLUMN [Flag] [TINYINT] NOT NULL
    ALTER TABLE PD_GoodsSerial ADD CONSTRAINT [DF_PD_GoodsSerial_Flag] DEFAULT (1) FOR Flag
END
    
--=============================================创建索引开始===============================================================
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial]') AND name = N'XC_PD_GoodsSerial_SerialFlag') 
	CREATE INDEX XC_PD_GoodsSerial_SerialFlag on PD_GoodsSerial ([Serial],[Flag]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial]') AND name = N'IXC_PD_GoodsSerial_WhsID') 
	CREATE CLUSTERED INDEX IXC_PD_GoodsSerial_WhsID on PD_GoodsSerial ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial]') AND name = N'XC_PD_GoodsSerial_WhsPtID') 
	CREATE INDEX XC_PD_GoodsSerial_WhsPtID on PD_GoodsSerial ([WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial]') AND name = N'XC_PD_GoodsSerial_GoodsPptID') 
	CREATE INDEX XC_PD_GoodsSerial_GoodsPptID on PD_GoodsSerial ([GoodsID],[Ppt1ID],[Ppt2ID]) WITH (FILLFACTOR = 90);
	



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_GoodsSerial_His
(
	[ID] BIGINT  NOT NULL,
    [Serial] [varchar](50) NULL,
	[WhsID] INT NOT NULL,
	[WhsPtID] INT NOT NULL,
	[GoodsID] INT NOT NULL,
	[Ppt1ID] INT NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_Ppt1ID] DEFAULT(0),
	[Ppt2ID] INT NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_Ppt2ID] DEFAULT(0),
	[CostPrice]	DECIMAL(20,8) NULL,
	[InBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_His_InBTypeID]  DEFAULT (0),
	[OutBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_His_OutBTypeID]  DEFAULT (0),
	[InTime] [datetime] NULL,
	[OutTime] [datetime] NULL,
	[Remark] [varchar](256) NULL,
	[Flag] [bit] NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_Flag]  DEFAULT (1),
	[IsOpening] [bit] NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_IsOpening]  DEFAULT (0),
   	[BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_EndDate]  DEFAULT (''),
    CONSTRAINT [PK_PD_GoodsSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

--=============================================修改表结构===============================================================

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial_His' AND a.Name='CostPrice')
    ALTER TABLE PD_GoodsSerial_His ADD CostPrice DECIMAL(20,8)  NULL  
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial_His' AND a.Name='IsOpening')
    ALTER TABLE PD_GoodsSerial_His ADD [IsOpening] [bit] NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_IsOpening]  DEFAULT (0)   
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial_His' AND a.Name='InBTypeID')
    ALTER TABLE PD_GoodsSerial_His ADD [InBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_His_InBTypeID]  DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial_His' AND a.Name='OutBTypeID')
    ALTER TABLE PD_GoodsSerial_His ADD [OutBTypeID] INT NULL CONSTRAINT [DF_PD_GoodsSerial_His_OutBTypeID]  DEFAULT (0)        

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_GoodsSerial_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial_His' AND a.Name='ProductDate')
    ALTER TABLE PD_GoodsSerial_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsSerial_His' AND a.Name='EndDate')
    ALTER TABLE PD_GoodsSerial_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_GoodsSerial_His_EndDate]  DEFAULT ('') 
    
--=============================================创建索引开始===============================================================
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial_His]') AND name = N'XC_PD_GoodsSerial_His_SerialFlag') 
	CREATE INDEX XC_PD_GoodsSerial_His_SerialFlag on PD_GoodsSerial_His ([Serial],[Flag]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial_His]') AND name = N'IXC_PD_GoodsSerial_His_WhsID') 
	CREATE CLUSTERED INDEX IXC_PD_GoodsSerial_His_WhsID on PD_GoodsSerial_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial_His]') AND name = N'XC_PD_GoodsSerial_His_WhsPtID') 
	CREATE INDEX XC_PD_GoodsSerial_His_WhsPtID on PD_GoodsSerial_His ([WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsSerial_His]') AND name = N'XC_PD_GoodsSerial_His_GoodsPptID') 
	CREATE INDEX XC_PD_GoodsSerial_His_GoodsPptID on PD_GoodsSerial_His ([GoodsID],[Ppt1ID],[Ppt2ID]) WITH (FILLFACTOR = 90);
	



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_GoodsStock]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_GoodsStock]
(
    [StockID] [bigint] IDENTITY(1,1) NOT NULL,
    [WhsID] [int] NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Qty] DEFAULT (0),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Price] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Total] DEFAULT (0),
    CONSTRAINT [PK_PD_GoodsStock] PRIMARY KEY NONCLUSTERED ([StockID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsStock]') AND name = N'IX_PD_GoodsStock_WhsIDGoodsID') 
	CREATE UNIQUE CLUSTERED INDEX IX_PD_GoodsStock_WhsIDGoodsID on PD_GoodsStock ([WhsID],[GoodsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsStock]') AND name = N'IX_PD_GoodsStock_GoodsID') 
	CREATE  INDEX IX_PD_GoodsStock_GoodsID on PD_GoodsStock ([GoodsID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_GoodsStock_Bound]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_GoodsStock_Bound]
(
    [BoundID] [bigint] IDENTITY(1,1) NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [WhsID] [int] NOT NULL,
    [UpperBound] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Bound_UpperBound] DEFAULT (0),
    [LowerBound] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Bound_LowerBound] DEFAULT (0),
    CONSTRAINT [PK_PD_GoodsStock_Bound] PRIMARY KEY NONCLUSTERED ([BoundID])
)
END




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_GoodsStock_Detail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_GoodsStock_Detail]
(
    [DetailID] [bigint] IDENTITY(1,1) NOT NULL,
    [StockID] [bigint] NOT NULL,
    [WhsPtID] [int] NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_Ppt2ID] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_Qty] DEFAULT (0),
    [CostPrice]	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_CostPrice] DEFAULT (0),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_EndDate]  DEFAULT (''),
    CONSTRAINT [PK_PD_GoodsStock_Detail] PRIMARY KEY NONCLUSTERED ([DetailID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsStock_Detail' AND a.Name='CostPrice')
    ALTER TABLE PD_GoodsStock_Detail ADD [CostPrice]	DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_CostPrice] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsStock_Detail' AND a.Name='BatchNumber')
    ALTER TABLE PD_GoodsStock_Detail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsStock_Detail' AND a.Name='ProductDate')
    ALTER TABLE PD_GoodsStock_Detail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_GoodsStock_Detail' AND a.Name='EndDate')
    ALTER TABLE PD_GoodsStock_Detail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_GoodsStock_Detail_EndDate]  DEFAULT ('') 


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsStock_Detail]') AND name = N'IXC_PD_GoodsStock_Detail_StockID') 
	CREATE CLUSTERED  INDEX IXC_PD_GoodsStock_Detail_StockID on PD_GoodsStock_Detail ([StockID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsStock_Detail]') AND name = N'IX_PD_GoodsStock_Detail_WhsPtID') 
	CREATE  INDEX IX_PD_GoodsStock_Detail_WhsPtID on PD_GoodsStock_Detail ([WhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_GoodsStock_Detail]') AND name = N'IX_PD_GoodsStock_Detail_GoodsIDPptID') 
	CREATE  INDEX IX_PD_GoodsStock_Detail_GoodsIDPptID on PD_GoodsStock_Detail ([GoodsID],[Ppt1ID],[Ppt2ID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_InOutWhsBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_AuditStatus] DEFAULT (0)    ,
    VipCardID INT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_VipCardID]  DEFAULT(0),
    ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_ExchangeCent]  DEFAULT(0),
    CONSTRAINT [PK_PD_InOutWhsBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_InOutWhsBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_AuditStatus] DEFAULT (0) 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsBill' AND a.Name='VipCardID')
    ALTER TABLE PD_InOutWhsBill ADD VipCardID INT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_VipCardID]  DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsBill' AND a.Name='ExchangeCent')
    ALTER TABLE PD_InOutWhsBill ADD ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_ExchangeCent]  DEFAULT(0)
    
    
    
    
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IXC_PD_InOutWhsBill_BillCode') 
	CREATE INDEX IXC_PD_InOutWhsBill_BillCode on PD_InOutWhsBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IXC_PD_InOutWhsBill_BillDate') 
	CREATE  INDEX IXC_PD_InOutWhsBill_BillDate on PD_InOutWhsBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IXC_PD_InOutWhsBill_CreateTime') 
	CREATE  INDEX IXC_PD_InOutWhsBill_CreateTime on PD_InOutWhsBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IXC_PD_InOutWhsBill_PosTime') 
	CREATE  INDEX IXC_PD_InOutWhsBill_PosTime on PD_InOutWhsBill ([PosTime]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IX_PD_InOutWhsBill_BillTypeID') 
	CREATE  INDEX IX_PD_InOutWhsBill_BillTypeID on PD_InOutWhsBill ([BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IX_PD_InOutWhsBill_BTypeID') 
	CREATE  INDEX IX_PD_InOutWhsBill_BTypeID on PD_InOutWhsBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IX_PD_InOutWhsBill_WhsID') 
	CREATE  INDEX IX_PD_InOutWhsBill_WhsID on PD_InOutWhsBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IX_PD_InOutWhsBill_DeptID') 
	CREATE  INDEX IX_PD_InOutWhsBill_DeptID on PD_InOutWhsBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IX_PD_InOutWhsBill_ElyID') 
	CREATE  INDEX IX_PD_InOutWhsBill_ElyID on PD_InOutWhsBill ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill]') AND name = N'IX_PD_InOutWhsBill_VipCardID') 
	CREATE  INDEX IX_PD_InOutWhsBill_VipCardID on PD_InOutWhsBill ([VipCardID]) WITH (FILLFACTOR = 90);
		
	




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_InOutWhsBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_AuditStatus] DEFAULT (0)    ,
    VipCardID INT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_VipCardID]  DEFAULT(0),
    ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_ExchangeCent]  DEFAULT(0),
    CONSTRAINT [PK_PD_InOutWhsBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_InOutWhsBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_AuditStatus] DEFAULT (0) 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsBill_His' AND a.Name='VipCardID')
    ALTER TABLE PD_InOutWhsBill_His ADD VipCardID INT NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_VipCardID]  DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsBill_His' AND a.Name='ExchangeCent')
    ALTER TABLE PD_InOutWhsBill_His ADD ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_InOutWhsBill_His_ExchangeCent]  DEFAULT(0)


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IXC_PD_InOutWhsBill_His_BillCode') 
	CREATE INDEX IXC_PD_InOutWhsBill_His_BillCode on PD_InOutWhsBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IXC_PD_InOutWhsBill_His_BillDate') 
	CREATE  INDEX IXC_PD_InOutWhsBill_His_BillDate on PD_InOutWhsBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IXC_PD_InOutWhsBill_His_CreateTime') 
	CREATE  INDEX IXC_PD_InOutWhsBill_His_CreateTime on PD_InOutWhsBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IXC_PD_InOutWhsBill_His_PosTime') 
	CREATE  INDEX IXC_PD_InOutWhsBill_His_PosTime on PD_InOutWhsBill_His ([PosTime]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IX_PD_InOutWhsBill_His_BillTypeID') 
	CREATE  INDEX IX_PD_InOutWhsBill_His_BillTypeID on PD_InOutWhsBill_His ([BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IX_PD_InOutWhsBill_His_BTypeID') 
	CREATE  INDEX IX_PD_InOutWhsBill_His_BTypeID on PD_InOutWhsBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IX_PD_InOutWhsBill_His_WhsID') 
	CREATE  INDEX IX_PD_InOutWhsBill_His_WhsID on PD_InOutWhsBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IX_PD_InOutWhsBill_His_DeptID') 
	CREATE  INDEX IX_PD_InOutWhsBill_His_DeptID on PD_InOutWhsBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IX_PD_InOutWhsBill_His_ElyID') 
	CREATE  INDEX IX_PD_InOutWhsBill_His_ElyID on PD_InOutWhsBill_His ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsBill_His]') AND name = N'IX_PD_InOutWhsBill_His_VipCardID') 
	CREATE  INDEX IX_PD_InOutWhsBill_His_VipCardID on PD_InOutWhsBill_His ([VipCardID]) WITH (FILLFACTOR = 90);	



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_InOutWhsDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_BSQty] DEFAULT (0),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_CostPrice] DEFAULT (0),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_GoodsCostTotal] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_InPutPrice]  DEFAULT(1),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_EndDate]  DEFAULT (''), 
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_InOutWhsDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_InOutWhsDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_InPutPrice]  DEFAULT(1)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_InOutWhsDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_InOutWhsDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail' AND a.Name='EndDate')
    ALTER TABLE PD_InOutWhsDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_InOutWhsDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_IsSelectBatch]  DEFAULT (0) 
    
        
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail]') AND name = N'IXC_PD_InOutWhsDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_InOutWhsDetail_BillDate on PD_InOutWhsDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail]') AND name = N'IXC_PD_InOutWhsDetail_BillNo') 
	CREATE  INDEX IXC_PD_InOutWhsDetail_BillNo on PD_InOutWhsDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail]') AND name = N'IX_PD_InOutWhsDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_InOutWhsDetail_GoodsIDPpt12ID on PD_InOutWhsDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail]') AND name = N'IX_PD_InOutWhsDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_InOutWhsDetail_WhsIDWhsPtID on PD_InOutWhsDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	

IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='PD_InOutWhsDetail' AND a.Name='Remark' AND a.[length] = 100
    )
BEGIN
	ALTER TABLE PD_InOutWhsDetail 
	ALTER COLUMN Remark VARCHAR(256)
END

GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_InOutWhsDetail_His]
(
    [DID] [bigint]  NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_BSQty] DEFAULT (0),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_CostPrice] DEFAULT (0),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_GoodsCostTotal] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_InPutPrice]  DEFAULT(1),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_EndDate]  DEFAULT (''), 
	[IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_IsSelectBatch]  DEFAULT (0)    
    CONSTRAINT [PK_PD_InOutWhsDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_InOutWhsDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_InPutPrice]  DEFAULT(1)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_InOutWhsDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_InOutWhsDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_InOutWhsDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_InOutWhsDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_InOutWhsDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_InOutWhsDetail_His_IsSelectBatch]  DEFAULT (0)    
    
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail_His]') AND name = N'IXC_PD_InOutWhsDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_InOutWhsDetail_His_BillDate on PD_InOutWhsDetail_His ([BillDate]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail_His]') AND name = N'IXC_PD_InOutWhsDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_InOutWhsDetail_His_BillNo on PD_InOutWhsDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail_His]') AND name = N'IX_PD_InOutWhsDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_InOutWhsDetail_His_GoodsIDPpt12ID on PD_InOutWhsDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsDetail_His]') AND name = N'IX_PD_InOutWhsDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_InOutWhsDetail_His_WhsIDWhsPtID on PD_InOutWhsDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
		--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_InOutWhsDetail_His]') and  name = 'Remark' and length=100) 
BEGIN
	 ALTER TABLE PD_InOutWhsDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_InOutWhsSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_InOutWhsSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
	[BillTypeID] INT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_InOutWhsSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsSerial]') AND name = N'XC_PD_InOutWhsSerial_BillDID') 
	CREATE INDEX XC_PD_InOutWhsSerial_BillDID on PD_InOutWhsSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_InOutWhsSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_InOutWhsSerial_His
(
	[ID] BIGINT  NOT NULL,
	[BillTypeID] INT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_InOutWhsSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_InOutWhsSerial_His]') AND name = N'XC_PD_InOutWhsSerial_His_BillDID') 
	CREATE INDEX XC_PD_InOutWhsSerial_His_BillDID on PD_InOutWhsSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_ListTable]
(
    [LID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillDate] [date] NOT NULL,
    [Red] [TINYINT] NOT  NULL CONSTRAINT [DF_PD_ListTable_Red]  DEFAULT(0),
    [FinanceID] [int] NOT NULL,
    [BtypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [JTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_ListTable_JTotal] DEFAULT (0),
	[DTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_ListTable_DTotal] DEFAULT (0),
	[Order] [TINYINT] NOT NULL CONSTRAINT [DF_PD_ListTable_Order]  DEFAULT(0),
	[ExPay] [TINYINT] NOT NULL CONSTRAINT [DF_PD_ListTable_ExPay]  DEFAULT(0),
	[IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_ListTable_IsReconciled]  DEFAULT(0),
    CONSTRAINT [PK_PD_ListTable] PRIMARY KEY NONCLUSTERED ([LID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND name = N'IXC_PD_ListTable_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_ListTable_BillDate on PD_ListTable ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND name = N'IX_PD_ListTable_BillTypeID') 
	CREATE  INDEX IX_PD_ListTable_BillTypeID on PD_ListTable ([BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND name = N'IX_PD_ListTable_BillNoBillTypeID') 
	CREATE  INDEX IX_PD_ListTable_BillNoBillTypeID on PD_ListTable ([BillNo],[BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND name = N'IX_PD_ListTable_FinanceID') 
	CREATE  INDEX IX_PD_ListTable_FinanceID on PD_ListTable ([FinanceID]) WITH (FILLFACTOR = 90);

IF NOT  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND name = N'IX_PD_ListTable_BtypeID') 
	CREATE  INDEX IX_PD_ListTable_BtypeID on PD_ListTable ([BtypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND name = N'IX_PD_ListTable_DeptID') 
	CREATE  INDEX IX_PD_ListTable_DeptID on PD_ListTable ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable]') AND name = N'IX_PD_ListTable_ElyID') 
	CREATE  INDEX IX_PD_ListTable_ElyID on PD_ListTable ([ElyID]) WITH (FILLFACTOR = 90);





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_ListTable_His]
(
    [LID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillTypeID] [int] NOT NULL,
    [BillDate] [date] NOT NULL,
    [Red] [TINYINT] NOT  NULL CONSTRAINT [DF_PD_ListTable_His_Red]  DEFAULT(0),
    [FinanceID] [int] NOT NULL,
    [BtypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [JTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_ListTable_His_JTotal] DEFAULT (0),
	[DTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_ListTable_His_DTotal] DEFAULT (0),
	[Order] [TINYINT] NOT NULL CONSTRAINT [DF_PD_ListTable_His_Order]  DEFAULT(0),
	[ExPay] [TINYINT] NOT NULL CONSTRAINT [DF_PD_ListTable_His_ExPay]  DEFAULT(0),
	[IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_ListTable_His_IsReconciled]  DEFAULT(0),
    CONSTRAINT [PK_PD_ListTable_His] PRIMARY KEY NONCLUSTERED ([LID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND name = N'IXC_PD_ListTable_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_ListTable_His_BillDate on PD_ListTable_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND name = N'IX_PD_ListTable_His_BillTypeID') 
	CREATE  INDEX IX_PD_ListTable_His_BillTypeID on PD_ListTable_His ([BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND name = N'IX_PD_ListTable_His_BillNoBillTypeID') 
	CREATE  INDEX IX_PD_ListTable_His_BillNoBillTypeID on PD_ListTable_His ([BillNo],[BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND name = N'IX_PD_ListTable_His_FinanceID') 
	CREATE  INDEX IX_PD_ListTable_His_FinanceID on PD_ListTable_His ([FinanceID]) WITH (FILLFACTOR = 90);

IF NOT  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND name = N'IX_PD_ListTable_His_BtypeID') 
	CREATE  INDEX IX_PD_ListTable_His_BtypeID on PD_ListTable_His ([BtypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND name = N'IX_PD_ListTable_His_DeptID') 
	CREATE  INDEX IX_PD_ListTable_His_DeptID on PD_ListTable_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_ListTable_His]') AND name = N'IX_PD_ListTable_His_ElyID') 
	CREATE  INDEX IX_PD_ListTable_His_ElyID on PD_ListTable_His ([ElyID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_LossSpillBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [StockBillNo] [bigint] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_StockBillNo] DEFAULT(0),
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_CreateTime] DEFAULT getdate(),
    [InPutPrice] TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_InPutPrice] DEFAULT (1),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_IsOS] DEFAULT(0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_AuditStatus] DEFAULT (0),
    CONSTRAINT [PK_PD_LossSpillBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IXC_PD_LossSpillBill_BillCode') 
	CREATE  INDEX IXC_PD_LossSpillBill_BillCode on PD_LossSpillBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IXC_PD_LossSpillBill_CreateTime') 
	CREATE  INDEX IXC_PD_LossSpillBill_CreateTime on PD_LossSpillBill ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IXC_PD_LossSpillBill_PosTime') 
	CREATE  INDEX IXC_PD_LossSpillBill_PosTime on PD_LossSpillBill ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IXC_PD_LossSpillBill_BillDate') 
	CREATE  INDEX IXC_PD_LossSpillBill_BillDate on PD_LossSpillBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IX_PD_LossSpillBill_BillTypeID') 
	CREATE  INDEX IX_PD_LossSpillBill_BillTypeID on PD_LossSpillBill ([BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IX_PD_LossSpillBill_StockBillNo') 
	CREATE  INDEX IX_PD_LossSpillBill_StockBillNo on PD_LossSpillBill ([StockBillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IX_PD_LossSpillBill_WhsID') 
	CREATE  INDEX IX_PD_LossSpillBill_WhsID on PD_LossSpillBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IX_PD_LossSpillBill_DeptID') 
	CREATE  INDEX IX_PD_LossSpillBill_DeptID on PD_LossSpillBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill]') AND name = N'IX_PD_LossSpillBill_ElyID') 
	CREATE  INDEX IX_PD_LossSpillBill_ElyID on PD_LossSpillBill ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_LossSpillBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_LossSpillBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [StockBillNo] [bigint] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_StockBillNo] DEFAULT(0),
    [BillTypeID] [int] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_CreateTime] DEFAULT getdate(),
    [InPutPrice] TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_InPutPrice] DEFAULT (1),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_IsOS] DEFAULT(0) ,
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_AuditStatus] DEFAULT (0),
    CONSTRAINT [PK_PD_LossSpillBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IXC_PD_LossSpillBill_His_BillCode') 
	CREATE  INDEX IXC_PD_LossSpillBill_His_BillCode on PD_LossSpillBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IXC_PD_LossSpillBill_His_CreateTime') 
	CREATE  INDEX IXC_PD_LossSpillBill_His_CreateTime on PD_LossSpillBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IXC_PD_LossSpillBill_His_PosTime') 
	CREATE  INDEX IXC_PD_LossSpillBill_His_PosTime on PD_LossSpillBill_His ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IXC_PD_LossSpillBill_His_BillDate') 
	CREATE  INDEX IXC_PD_LossSpillBill_His_BillDate on PD_LossSpillBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IX_PD_LossSpillBill_His_BillTypeID') 
	CREATE  INDEX IX_PD_LossSpillBill_His_BillTypeID on PD_LossSpillBill_His ([BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IX_PD_LossSpillBill_His_StockBillNo') 
	CREATE  INDEX IX_PD_LossSpillBill_His_StockBillNo on PD_LossSpillBill_His ([StockBillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IX_PD_LossSpillBill_His_WhsID') 
	CREATE  INDEX IX_PD_LossSpillBill_His_WhsID on PD_LossSpillBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IX_PD_LossSpillBill_His_DeptID') 
	CREATE  INDEX IX_PD_LossSpillBill_His_DeptID on PD_LossSpillBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillBill_His]') AND name = N'IX_PD_LossSpillBill_His_ElyID') 
	CREATE  INDEX IX_PD_LossSpillBill_His_ElyID on PD_LossSpillBill_His ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_LossSpillBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_LossSpillBill_His_AuditStatus] DEFAULT (0) 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_LossSpillDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_BSQty] DEFAULT (0),
	[CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_CostPrice] DEFAULT (0),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_GoodsCostTotal] DEFAULT (0),
	[InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_InPutPrice] DEFAULT (1),
    [Remark] [varchar](100) NULL,
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_EndDate]  DEFAULT (''), 
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_LossSpillDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_LossSpillDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_LossSpillDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail' AND a.Name='EndDate')
    ALTER TABLE PD_LossSpillDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_LossSpillDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_IsSelectBatch]  DEFAULT (0)
    
    
    
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail]') AND name = N'IXC_PD_LossSpillDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_LossSpillDetail_BillDate on PD_LossSpillDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail]') AND name = N'IXC_PD_LossSpillDetail_BillNo') 
	CREATE  INDEX IXC_PD_LossSpillDetail_BillNo on PD_LossSpillDetail ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail]') AND name = N'IX_PD_LossSpillDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_LossSpillDetail_GoodsIDPpt12ID on PD_LossSpillDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail]') AND name = N'IX_PD_LossSpillDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_LossSpillDetail_WhsIDWhsPtID on PD_LossSpillDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
				--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_LossSpillDetail]') and  name = 'Remark' and length=100) 
BEGIN
	 ALTER TABLE PD_LossSpillDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_LossSpillDetail_His]
(
    [DID] [bigint]  NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_Convfactor] DEFAULT (1),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_BSQty] DEFAULT (0),
	[CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_CostPrice] DEFAULT (0),
    [GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_GoodsCostTotal] DEFAULT (0),
	[InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_InPutPrice] DEFAULT (1),
    [Remark] [varchar](100) NULL,
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_EndDate]  DEFAULT (''), 
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_LossSpillDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_LossSpillDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_LossSpillDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_LossSpillDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_EndDate]  DEFAULT ('') 
  
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_LossSpillDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_LossSpillDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_LossSpillDetail_His_IsSelectBatch]  DEFAULT (0)
   
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail_His]') AND name = N'IXC_PD_LossSpillDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_LossSpillDetail_His_BillDate on PD_LossSpillDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail_His]') AND name = N'IXC_PD_LossSpillDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_LossSpillDetail_His_BillNo on PD_LossSpillDetail_His ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail_His]') AND name = N'IX_PD_LossSpillDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_LossSpillDetail_His_GoodsIDPpt12ID on PD_LossSpillDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillDetail_His]') AND name = N'IX_PD_LossSpillDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_LossSpillDetail_His_WhsIDWhsPtID on PD_LossSpillDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
			--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_LossSpillDetail_His]') and  name = 'Remark' and length=100) 
BEGIN
	 ALTER TABLE PD_LossSpillDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_LossSpillSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_LossSpillSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
	[BillTypeID] INT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_LossSpillSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillSerial]') AND name = N'XC_PD_LossSpillSerial_BillDID') 
	CREATE INDEX XC_PD_LossSpillSerial_BillDID on PD_LossSpillSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_LossSpillSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_LossSpillSerial_His
(
	[ID] BIGINT NOT NULL,
	[BillTypeID] INT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_LossSpillSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_LossSpillSerial_His]') AND name = N'XC_PD_LossSpillSerial_His_BillDID') 
	CREATE INDEX XC_PD_LossSpillSerial_His_BillDID on PD_LossSpillSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PD_MulAccounts]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_MulAccounts]
(
	[ID] INT IDENTITY(1,1) NOT NULL,
	[BillTypeID] INT NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_MulAccounts_Total] DEFAULT (0),
    CONSTRAINT [PK_PD_MulAccounts] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF EXISTS(SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts]') AND name = N'PK_PD_MulAccounts' AND type_desc='CLUSTERED')
BEGIN
	ALTER TABLE [dbo].[PD_MulAccounts] DROP CONSTRAINT [PK_PD_MulAccounts]
	ALTER TABLE [dbo].[PD_MulAccounts] ADD CONSTRAINT [PK_PD_MulAccounts] PRIMARY KEY NONCLUSTERED ([ID] ASC) ON [PRIMARY]
END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts]') AND name = N'IXC_PD_MulAccounts_BillTypeID') 
	CREATE CLUSTERED INDEX IXC_PD_MulAccounts_BillTypeID on PD_MulAccounts ([BillTypeID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts]') AND name = N'IX_PD_MulAccounts_BillNo') 
	CREATE INDEX IX_PD_MulAccounts_BillNo on PD_MulAccounts ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts]') AND name = N'IX_PD_MulAccounts_FinanceID') 
	CREATE INDEX IX_PD_MulAccounts_FinanceID on PD_MulAccounts ([FinanceID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PD_MulAccounts_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_MulAccounts_His
(
	[ID] INT IDENTITY(1,1) NOT NULL,
	[BillTypeID] INT NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_MulAccounts_His_Total] DEFAULT (0),
    CONSTRAINT [PK_PD_MulAccounts_His] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF EXISTS(SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts_His]') AND name = N'PK_PD_MulAccounts_His' AND type_desc='CLUSTERED')
BEGIN
	ALTER TABLE [dbo].[PD_MulAccounts_His] DROP CONSTRAINT [PK_PD_MulAccounts_His]
	ALTER TABLE [dbo].[PD_MulAccounts_His] ADD CONSTRAINT [PK_PD_MulAccounts_His] PRIMARY KEY NONCLUSTERED ([ID] ASC) ON [PRIMARY]
END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts_His]') AND name = N'IXC_PD_MulAccounts_His_BillTypeID') 
	CREATE CLUSTERED INDEX IXC_PD_MulAccounts_His_BillTypeID on PD_MulAccounts_His ([BillTypeID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts_His]') AND name = N'IX_PD_MulAccounts_His_BillNo') 
	CREATE INDEX IX_PD_MulAccounts_His_BillNo on PD_MulAccounts_His ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_MulAccounts_His]') AND name = N'IX_PD_MulAccounts_His_FinanceID') 
	CREATE INDEX IX_PD_MulAccounts_His_FinanceID on PD_MulAccounts_His ([FinanceID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchAccounts]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchAccounts]
(
    [BillNo] [int] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [PayDate] [date] NOT NULL CONSTRAINT [DF_PD_PchAccounts_PayDate] DEFAULT getdate(),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchAccounts_Total] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchAccounts_PayRecTotal] DEFAULT (0),
    CONSTRAINT [PK_PD_PchAccounts] PRIMARY KEY CLUSTERED ([BillNo],[FinanceID])
)
END

--IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchAccounts]') AND name = N'IXC_PD_PchAccounts_BillNo') 
--	CREATE CLUSTERED  INDEX IXC_PD_PchAccounts_BillNo on PD_PchAccounts ([BillNo]) WITH (FILLFACTOR = 90);
	
--IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchAccounts]') AND name = N'IXC_PD_PchAccounts_FinanceID') 
--	CREATE INDEX IXC_PD_PchAccounts_FinanceID on PD_PchAccounts ([FinanceID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_PchBill_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_PchBill_IsAccounts] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_PchBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchBill_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_PchBill_IsDraft] DEFAULT (1),    
    [LogistBtypeID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_LogistBtypeID] DEFAULT (0),
    [FreightFinanceID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_FreightFinanceID] DEFAULT (0),
    [Freight] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_Freight] DEFAULT (0),
    [FreightTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_FreightTotal] DEFAULT (0),
    [FreightPaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_FreightPaidTotal] DEFAULT (0),
    [FreightStlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_FreightStlTag] DEFAULT (0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_InvoiceTotal] DEFAULT (0),
    AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchBill_AuditStatus] DEFAULT (0)    ,
    VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_PchBill_VerifyElyID] DEFAULT (0),
    VerifyDate VARCHAR(20)  NULL, 
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchBill_IsInvoice] DEFAULT (1),
      BeforeAPTotal [decimal](20,8) NOT  NULL DEFAULT(0), --此前应付
    CONSTRAINT [PK_PD_PchBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='InvoiceMode')
    ALTER TABLE PD_PchBill ADD [InvoiceMode] tinyint NOT NULL CONSTRAINT [DF_PD_PchBill_InvoiceMode] DEFAULT (0)
 
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchBill' AND so.xtype = 'D' AND so.name = 'DF_PD_PchBill_InvoiceMode')
			ALTER TABLE PD_PchBill DROP CONSTRAINT [DF_PD_PchBill_InvoiceMode]
		ALTER TABLE PD_PchBill ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_PchBill ADD CONSTRAINT [DF_PD_PchBill_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_PchBill ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_InvoiceTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='LogistBtypeID')
    ALTER TABLE PD_PchBill ADD LogistBtypeID INT NOT NULL CONSTRAINT [DF_PD_PchBill_LogistBtypeID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='FreightFinanceID')
    ALTER TABLE PD_PchBill ADD FreightFinanceID INT NOT NULL CONSTRAINT [DF_PD_PchBill_FreightFinanceID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='Freight')
    ALTER TABLE PD_PchBill ADD Freight DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_Freight] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='FreightTotal')
    ALTER TABLE PD_PchBill ADD FreightTotal DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_FreightTotal] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='FreightPaidTotal')
    ALTER TABLE PD_PchBill ADD FreightPaidTotal DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_FreightPaidTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='FreightStlTag')
    ALTER TABLE PD_PchBill ADD FreightStlTag TINYINT NOT NULL CONSTRAINT [DF_PD_PchBill_FreightStlTag] DEFAULT (0)    
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_PchBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchBill_AuditStatus] DEFAULT (0)    
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='VerifyElyID')
    ALTER TABLE dbo.PD_PchBill ADD VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_PchBill_VerifyElyID] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='VerifyDate')
    ALTER TABLE dbo.PD_PchBill ADD VerifyDate VARCHAR(20)  NULL 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_PchBill ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchBill_IsInvoice] DEFAULT (1)
    
 IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill' AND a.Name='BeforeAPTotal')
    ALTER TABLE PD_PchBill ADD BeforeAPTotal [decimal](20,8) NOT  NULL DEFAULT(0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IXC_PD_PchBill_BillCode') 
	CREATE INDEX IXC_PD_PchBill_BillCode on PD_PchBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IXC_PD_PchBill_CreateTime') 
	CREATE INDEX IXC_PD_PchBill_CreateTime on PD_PchBill ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IXC_PD_PchBill_PosTime') 
	CREATE INDEX IXC_PD_PchBill_PosTime on PD_PchBill ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IXC_PD_PchBill_BillDate') 
	CREATE INDEX IXC_PD_PchBill_BillDate on PD_PchBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IX_PD_PchBill_FinanceID') 
	CREATE  INDEX IX_PD_PchBill_FinanceID on PD_PchBill ([FinanceID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IX_PD_PchBill_BTypeID') 
	CREATE  INDEX IX_PD_PchBill_BTypeID on PD_PchBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IX_PD_PchBill_WhsID') 
	CREATE  INDEX IX_PD_PchBill_WhsID on PD_PchBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IX_PD_PchBill_DeptID') 
	CREATE  INDEX IX_PD_PchBill_DeptID on PD_PchBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill]') AND name = N'IX_PD_PchBill_ElyID') 
	CREATE  INDEX IX_PD_PchBill_ElyID on PD_PchBill ([ElyID]) WITH (FILLFACTOR = 90);
	




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_PchBill_His_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_His_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_PchBill_His_IsAccounts] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_PchBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchBill_His_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_His_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_His_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_His_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_PchBill_His_IsDraft] DEFAULT (1),
    [LogistBtypeID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_His_LogistBtypeID] DEFAULT (0),
    [FreightFinanceID] [int] NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightFinanceID] DEFAULT (0),
    [Freight] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_Freight] DEFAULT (0),
    [FreightTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightTotal] DEFAULT (0),
    [FreightPaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightPaidTotal] DEFAULT (0),
    [FreightStlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightStlTag] DEFAULT (0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchBill_His_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_InvoiceTotal] DEFAULT (0),
    AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchBill_His_AuditStatus] DEFAULT (0),   
    VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_PchBill_His_VerifyElyID] DEFAULT (0),
    VerifyDate VARCHAR(20)  NULL, 
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchBill_His_IsInvoice] DEFAULT (1),
    CONSTRAINT [PK_PD_PchBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='InvoiceMode')
    ALTER TABLE PD_PchBill_His ADD [InvoiceMode] tinyint NOT NULL CONSTRAINT [DF_PD_PchBill_His_InvoiceMode] DEFAULT (0)
 
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill_His' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_PchBill_His_InvoiceMode')
			ALTER TABLE PD_PchBill_His DROP CONSTRAINT [DF_PD_PchBill_His_InvoiceMode]
		ALTER TABLE PD_PchBill_His ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_PchBill_His ADD CONSTRAINT [DF_PD_PchBill_His_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_PchBill_His ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_InvoiceTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='LogistBtypeID')
    ALTER TABLE PD_PchBill_His ADD LogistBtypeID INT NOT NULL CONSTRAINT [DF_PD_PchBill_His_LogistBtypeID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='FreightFinanceID')
    ALTER TABLE PD_PchBill_His ADD FreightFinanceID INT NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightFinanceID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='Freight')
    ALTER TABLE PD_PchBill_His ADD Freight DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_Freight] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='FreightTotal')
    ALTER TABLE PD_PchBill_His ADD FreightTotal DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightTotal] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='FreightPaidTotal')
    ALTER TABLE PD_PchBill_His ADD FreightPaidTotal DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightPaidTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='FreightStlTag')
    ALTER TABLE PD_PchBill_His ADD FreightStlTag TINYINT NOT NULL CONSTRAINT [DF_PD_PchBill_His_FreightStlTag] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_PchBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchBill_His_AuditStatus] DEFAULT (0)    
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='VerifyElyID')
    ALTER TABLE dbo.PD_PchBill_His ADD VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_PchBill_His_VerifyElyID] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='VerifyDate')
    ALTER TABLE dbo.PD_PchBill_His ADD VerifyDate VARCHAR(20)  NULL 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchBill_His' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_PchBill_His ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchBill_His_IsInvoice] DEFAULT (1)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IXC_PD_PchBill_His_BillCode') 
	CREATE INDEX IXC_PD_PchBill_His_BillCode on PD_PchBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IXC_PD_PchBill_His_CreateTime') 
	CREATE INDEX IXC_PD_PchBill_His_CreateTime on PD_PchBill_His ([CreateTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IXC_PD_PchBill_His_PosTime') 
	CREATE INDEX IXC_PD_PchBill_His_PosTime on PD_PchBill_His ([PosTime]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IXC_PD_PchBill_His_BillDate') 
	CREATE INDEX IXC_PD_PchBill_His_BillDate on PD_PchBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IX_PD_PchBill_His_FinanceID') 
	CREATE  INDEX IX_PD_PchBill_His_FinanceID on PD_PchBill_His ([FinanceID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IX_PD_PchBill_His_BTypeID') 
	CREATE  INDEX IX_PD_PchBill_His_BTypeID on PD_PchBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IX_PD_PchBill_His_WhsID') 
	CREATE  INDEX IX_PD_PchBill_His_WhsID on PD_PchBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IX_PD_PchBill_His_DeptID') 
	CREATE  INDEX IX_PD_PchBill_His_DeptID on PD_PchBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchBill_His]') AND name = N'IX_PD_PchBill_His_ElyID') 
	CREATE  INDEX IX_PD_PchBill_His_ElyID on PD_PchBill_His ([ElyID]) WITH (FILLFACTOR = 90);
	



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
	[OrdDID] [bigint] NOT NULL CONSTRAINT [DF_PD_PchDetail_OrdDID] DEFAULT (0),
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_GoodsCostTotal] DEFAULT (-1),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchDetail_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_PchDetail_IsReconciled]  DEFAULT(0),    
    [Freight] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Freight] DEFAULT (0),
    [InPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_InPrice] DEFAULT (0),
    [InTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_InTotal] DEFAULT (0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_PriceID]  DEFAULT(0),
    InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_InPutPrice]  DEFAULT(1),
    [VerifyQty] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_VerifyQty] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_ComTotal] DEFAULT (0),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchDetail_EndDate]  DEFAULT (''), 
	 [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_PchDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='Freight')
    ALTER TABLE PD_PchDetail ADD Freight DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_Freight] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='InPrice')
    ALTER TABLE PD_PchDetail ADD InPrice DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_InPrice] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='InTotal')
    ALTER TABLE PD_PchDetail ADD InTotal DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_InTotal] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_PchDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_InPutPrice]  DEFAULT(1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='PriceID')
    ALTER TABLE PD_PchDetail ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='VerifyQty')
    ALTER TABLE dbo.PD_PchDetail ADD VerifyQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_VerifyQty] DEFAULT (0)      
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='ComQty')
    ALTER TABLE PD_PchDetail ADD [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_ComQty] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='ComTotal')
    ALTER TABLE PD_PchDetail ADD  [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_ComTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_PchDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_PchDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='EndDate')
    ALTER TABLE PD_PchDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchDetail_EndDate]  DEFAULT ('') 
    


  
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail]') AND name = N'IXC_PD_PchDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchDetail_BillDate on PD_PchDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail]') AND name = N'IXC_PD_PchDetail_BillNo') 
	CREATE  INDEX IXC_PD_PchDetail_BillNo on PD_PchDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail]') AND name = N'IX_PD_PchDetail_OrdDID') 
	CREATE  INDEX IX_PD_PchDetail_OrdDID on PD_PchDetail ([OrdDID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail]') AND name = N'IX_PD_PchDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_PchDetail_GoodsIDPpt12ID on PD_PchDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail]') AND name = N'IX_PD_PchDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_PchDetail_WhsIDWhsPtID on PD_PchDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail' AND a.Name='GoodsNO')
    ALTER TABLE PD_PchDetail ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO
	
--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_PchDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
	[OrdDID] [bigint] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_OrdDID] DEFAULT (0),
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_GoodsCostTotal] DEFAULT (-1),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_PchDetail_His_IsReconciled]  DEFAULT(0),
    [Freight] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Freight] DEFAULT (0),
    [InPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_InPrice] DEFAULT (0),
    [InTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_InTotal] DEFAULT (0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_His_PriceID]  DEFAULT(0),
    InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_His_InPutPrice]  DEFAULT(1),
    [VerifyQty] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_VerifyQty] DEFAULT (0) ,
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_ComTotal] DEFAULT (0),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchDetail_His_EndDate]  DEFAULT (''), 
    [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_PchDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='Freight')
    ALTER TABLE PD_PchDetail_His ADD Freight DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_Freight] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='InPrice')
    ALTER TABLE PD_PchDetail_His ADD InPrice DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_InPrice] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='InTotal')
    ALTER TABLE PD_PchDetail_His ADD InTotal DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_InTotal] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='InPutPrice')
    ALTER TABLE PD_PchDetail_His ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_His_InPutPrice]  DEFAULT(1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='PriceID')
    ALTER TABLE PD_PchDetail_His ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_PchDetail_His_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='VerifyQty')
    ALTER TABLE dbo.PD_PchDetail_His ADD VerifyQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_VerifyQty] DEFAULT (0)      
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='ComQty')
    ALTER TABLE PD_PchDetail_His ADD [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_ComQty] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='ComTotal')
    ALTER TABLE PD_PchDetail_His ADD  [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_ComTotal] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_PchDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_PchDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_PchDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchDetail_His_EndDate]  DEFAULT ('') 
     
 
 
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail_His]') AND name = N'IXC_PD_PchDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchDetail_His_BillDate on PD_PchDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail_His]') AND name = N'IXC_PD_PchDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_PchDetail_His_BillNo on PD_PchDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail_His]') AND name = N'IX_PD_PchDetail_His_OrdDID') 
	CREATE  INDEX IX_PD_PchDetail_His_OrdDID on PD_PchDetail_His ([OrdDID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail_His]') AND name = N'IX_PD_PchDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_PchDetail_His_GoodsIDPpt12ID on PD_PchDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchDetail_His]') AND name = N'IX_PD_PchDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_PchDetail_His_WhsIDWhsPtID on PD_PchDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchDetail_His' AND a.Name='GoodsNO')
    ALTER TABLE PD_PchDetail_His ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO
	
--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_PchDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchOrdBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_CreateTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_Stt] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_StopTag] DEFAULT (0),
    AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdBill_AuditStatus] DEFAULT (0),  
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_IsDraft] DEFAULT (1),    
    CONSTRAINT [PK_PD_PchOrdBill] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_PchOrdBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdBill_AuditStatus] DEFAULT (0)    

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdBill' AND a.Name='IsDraft')
BEGIN
    ALTER TABLE dbo.PD_PchOrdBill ADD [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_IsDraft] DEFAULT (1)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill]') AND name = N'IXC_PD_PchOrdBill_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchOrdBill_BillDate on PD_PchOrdBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill]') AND name = N'IX_PD_PchOrdBill_BTypeID') 
	CREATE  INDEX IX_PD_PchOrdBill_BTypeID on PD_PchOrdBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill]') AND name = N'IX_PD_PchOrdBill_WhsID') 
	CREATE  INDEX IX_PD_PchOrdBill_WhsID on PD_PchOrdBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill]') AND name = N'IX_PD_PchOrdBill_DeptID') 
	CREATE  INDEX IX_PD_PchOrdBill_DeptID on PD_PchOrdBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill]') AND name = N'IX_PD_PchOrdBill_ElyID') 
	CREATE  INDEX IX_PD_PchOrdBill_ElyID on PD_PchOrdBill ([ElyID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchOrdBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_CreateTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_Stt] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_StopTag] DEFAULT (0),
    AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_AuditStatus] DEFAULT (0),
    [IsDraft] [bit] NOT NULL,
    CONSTRAINT [PK_PD_PchOrdBill_His] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_PchOrdBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_AuditStatus] DEFAULT (0) 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdBill_His' AND a.Name='IsDraft')
BEGIN
    ALTER TABLE dbo.PD_PchOrdBill_His ADD [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_PchOrdBill_His_IsDraft] DEFAULT (1) 
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill_His]') AND name = N'IXC_PD_PchOrdBill_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchOrdBill_His_BillDate on PD_PchOrdBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill_His]') AND name = N'IX_PD_PchOrdBill_His_BTypeID') 
	CREATE  INDEX IX_PD_PchOrdBill_His_BTypeID on PD_PchOrdBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill_His]') AND name = N'IX_PD_PchOrdBill_His_WhsID') 
	CREATE  INDEX IX_PD_PchOrdBill_His_WhsID on PD_PchOrdBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill_His]') AND name = N'IX_PD_PchOrdBill_His_DeptID') 
	CREATE  INDEX IX_PD_PchOrdBill_His_DeptID on PD_PchOrdBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdBill_His]') AND name = N'IX_PD_PchOrdBill_His_ElyID') 
	CREATE  INDEX IX_PD_PchOrdBill_His_ElyID on PD_PchOrdBill_His ([ElyID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchOrdDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Price] DEFAULT (0),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Discount] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Tax] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_ComTotal] DEFAULT (0),
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Stt] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_Gift] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_StopTag] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_PriceID]  DEFAULT(0),
    [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_PchOrdDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdDetail' AND a.Name='PriceID')
    ALTER TABLE PD_PchOrdDetail ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail]') AND name = N'IXC_PD_PchOrdDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchOrdDetail_BillDate on PD_PchOrdDetail ([BillDate]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail]') AND name = N'IXC_PD_PchOrdDetail_BillNo') 
	CREATE  INDEX IXC_PD_PchOrdDetail_BillNo on PD_PchOrdDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail]') AND name = N'IX_PD_PchOrdDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_PchOrdDetail_GoodsIDPpt12ID on PD_PchOrdDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail]') AND name = N'IX_PD_PchOrdDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_PchOrdDetail_WhsIDWhsPtID on PD_PchOrdDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdDetail' AND a.Name='GoodsNO')
    ALTER TABLE PD_PchOrdDetail ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchOrdDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_PchOrdDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

--条形码长度从20变成100 V6.2 谢吉康 2020-2-7
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchOrdDetail]') and  name = 'BarCode' and Length=30)
BEGIN
	 ALTER TABLE PD_PchOrdDetail
	    ALTER COLUMN BarCode VARCHAR(100)
END
GO





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchOrdDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Price] DEFAULT (0),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Discount] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Tax] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_ComTotal] DEFAULT (0),
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Stt] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_Gift] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_StopTag] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_PriceID]  DEFAULT(0),
     [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_PchOrdDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdDetail_His' AND a.Name='PriceID')
    ALTER TABLE PD_PchOrdDetail_His ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_PchOrdDetail_His_PriceID]  DEFAULT(0)
    
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail_His]') AND name = N'IXC_PD_PchOrdDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchOrdDetail_His_BillDate on PD_PchOrdDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail_His]') AND name = N'IXC_PD_PchOrdDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_PchOrdDetail_His_BillNo on PD_PchOrdDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail_His]') AND name = N'IX_PD_PchOrdDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_PchOrdDetail_His_GoodsIDPpt12ID on PD_PchOrdDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchOrdDetail_His]') AND name = N'IX_PD_PchOrdDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_PchOrdDetail_His_WhsIDWhsPtID on PD_PchOrdDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchOrdDetail_His' AND a.Name='GoodsNO')
    ALTER TABLE PD_PchOrdDetail_His  ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchOrdDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_PchOrdDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

--条形码长度从20变成100 V6.2 谢吉康 2020-2-7
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchOrdDetail_His]') and  name = 'BarCode' and Length=30)
BEGIN
	 ALTER TABLE PD_PchOrdDetail_His
	    ALTER COLUMN BarCode VARCHAR(100)
END
GO



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchRetBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_PchRetBill_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetBill_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_PchRetBill_IsAccounts] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_PchRetBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchRetBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchRetBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_PchRetBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchRetBill_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_PchRetBill_IsDraft] DEFAULT (1),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_InvoiceTotal] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetBill_AuditStatus] DEFAULT (0)    ,
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchRetBill_IsInvoice] DEFAULT (1),
    BeforeAPTotal [decimal](20,8) NOT  NULL DEFAULT(0), --此前应付
    CONSTRAINT [PK_PD_PchRetBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill' AND a.Name='InvoiceMode')
    ALTER TABLE PD_PchRetBill ADD [InvoiceMode] TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetBill_InvoiceMode] DEFAULT (0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchRetBill' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchRetBill' AND so.xtype = 'D' AND so.name = 'DF_PD_PchRetBill_InvoiceMode')
			ALTER TABLE PD_PchRetBill DROP CONSTRAINT [DF_PD_PchRetBill_InvoiceMode]
		ALTER TABLE PD_PchRetBill ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_PchRetBill ADD CONSTRAINT [DF_PD_PchRetBill_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_PchRetBill ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_InvoiceTotal] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_PchRetBill ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchRetBill_IsInvoice] DEFAULT (1)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IXC_PD_PchRetBill_BillCode') 
	CREATE  INDEX IXC_PD_PchRetBill_BillCode on PD_PchRetBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IXC_PD_PchRetBill_BillDate') 
	CREATE  INDEX IXC_PD_PchRetBill_BillDate on PD_PchRetBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IXC_PD_PchRetBill_CreateTime') 
	CREATE  INDEX IXC_PD_PchRetBill_CreateTime on PD_PchRetBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IXC_PD_PchRetBill_PosTime') 
	CREATE  INDEX IXC_PD_PchRetBill_PosTime on PD_PchRetBill ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IX_PD_PchRetBill_BTypeID') 
	CREATE  INDEX IX_PD_PchRetBill_BTypeID on PD_PchRetBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IX_PD_PchRetBill_WhsID') 
	CREATE  INDEX IX_PD_PchRetBill_WhsID on PD_PchRetBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IX_PD_PchRetBill_DeptID') 
	CREATE  INDEX IX_PD_PchRetBill_DeptID on PD_PchRetBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IX_PD_PchRetBill_ElyID') 
	CREATE  INDEX IX_PD_PchRetBill_ElyID on PD_PchRetBill ([ElyID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill]') AND name = N'IX_PD_PchRetBill_FinanceID') 
	CREATE  INDEX IX_PD_PchRetBill_FinanceID on PD_PchRetBill ([FinanceID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_PchRetBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetBill_AuditStatus] DEFAULT (0)  
    
     IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill' AND a.Name='BeforeAPTotal')
    ALTER TABLE PD_PchRetBill ADD BeforeAPTotal [decimal](20,8) NOT  NULL DEFAULT(0)



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchRetBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_IsAccounts] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_IsDraft] DEFAULT (1),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_InvoiceTotal] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_AuditStatus] DEFAULT (0)    ,
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_IsInvoice] DEFAULT (1),
    CONSTRAINT [PK_PD_PchRetBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill_His' AND a.Name='InvoiceMode')
    ALTER TABLE PD_PchRetBill_His ADD [InvoiceMode] TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_InvoiceMode] DEFAULT (0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchRetBill_His' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchRetBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_PchRetBill_His_InvoiceMode')
			ALTER TABLE PD_PchRetBill_His DROP CONSTRAINT [DF_PD_PchRetBill_His_InvoiceMode]
		ALTER TABLE PD_PchRetBill_His ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_PchRetBill_His ADD CONSTRAINT [DF_PD_PchRetBill_His_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill_His' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_PchRetBill_His ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_InvoiceTotal] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill_His' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_PchRetBill_His ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_IsInvoice] DEFAULT (1)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IXC_PD_PchRetBill_His_BillCode') 
	CREATE  INDEX IXC_PD_PchRetBill_His_BillCode on PD_PchRetBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IXC_PD_PchRetBill_His_BillDate') 
	CREATE  INDEX IXC_PD_PchRetBill_His_BillDate on PD_PchRetBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IXC_PD_PchRetBill_His_CreateTime') 
	CREATE  INDEX IXC_PD_PchRetBill_His_CreateTime on PD_PchRetBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IXC_PD_PchRetBill_His_PosTime') 
	CREATE  INDEX IXC_PD_PchRetBill_His_PosTime on PD_PchRetBill_His ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IX_PD_PchRetBill_His_BTypeID') 
	CREATE  INDEX IX_PD_PchRetBill_His_BTypeID on PD_PchRetBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IX_PD_PchRetBill_His_WhsID') 
	CREATE  INDEX IX_PD_PchRetBill_His_WhsID on PD_PchRetBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IX_PD_PchRetBill_His_DeptID') 
	CREATE  INDEX IX_PD_PchRetBill_His_DeptID on PD_PchRetBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IX_PD_PchRetBill_His_ElyID') 
	CREATE  INDEX IX_PD_PchRetBill_His_ElyID on PD_PchRetBill_His ([ElyID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetBill_His]') AND name = N'IX_PD_PchRetBill_His_FinanceID') 
	CREATE  INDEX IX_PD_PchRetBill_His_FinanceID on PD_PchRetBill_His ([FinanceID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_PchRetBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetBill_His_AuditStatus] DEFAULT (0)  



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchRetDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_GoodsCostTotal] DEFAULT (-1),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_IsReconciled]  DEFAULT(0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetDetail_PriceID]  DEFAULT(0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_InPutPrice]  DEFAULT(1),
    [PchDID] [bigint] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_PchDID] DEFAULT (0), 
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_EndDate]  DEFAULT (''), 
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_IsSelectBatch]  DEFAULT (0), 
    [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_PchRetDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_PchRetDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetDetail_InPutPrice]  DEFAULT(1)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='PriceID')
    ALTER TABLE PD_PchRetDetail ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetDetail_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='PchDID')
    ALTER TABLE dbo.PD_PchRetDetail ADD [PchDID] [bigint] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_PchDID] DEFAULT (0)   

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_PchRetDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_PchRetDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='EndDate')
    ALTER TABLE PD_PchRetDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_PchRetDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_IsSelectBatch]  DEFAULT (0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail]') AND name = N'IXC_PD_PchRetDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchRetDetail_BillDate on PD_PchRetDetail ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail]') AND name = N'IXC_PD_PchRetDetail_BillNo') 
	CREATE  INDEX IXC_PD_PchRetDetail_BillNo on PD_PchRetDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail]') AND name = N'IX_PD_PchRetDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_PchRetDetail_GoodsIDPpt12ID on PD_PchRetDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail]') AND name = N'IX_PD_PchRetDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_PchRetDetail_WhsIDWhsPtID on PD_PchRetDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail]') AND name = N'IX_PD_PchRetDetail_PchDID') 
	CREATE  INDEX IX_PD_PchRetDetail_PchDID on PD_PchRetDetail ([PchDID]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail' AND a.Name='GoodsNO')
    ALTER TABLE PD_PchRetDetail ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchRetDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_PchRetDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PchRetDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_GoodsCostTotal] DEFAULT (-1),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_IsReconciled]  DEFAULT(0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_PriceID]  DEFAULT(0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_InPutPrice]  DEFAULT(1),
    [PchDID] [bigint] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_PchDID] DEFAULT (0), 
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_EndDate]  DEFAULT (''), 
	[IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_IsSelectBatch]  DEFAULT (0),
	[GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_PchRetDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='InPutPrice')
    ALTER TABLE PD_PchRetDetail_His ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_InPutPrice]  DEFAULT(1)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='PriceID')
    ALTER TABLE PD_PchRetDetail_His ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='PchDID')
    ALTER TABLE dbo.PD_PchRetDetail_His ADD [PchDID] [bigint] NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_PchDID] DEFAULT (0)   

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_PchRetDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_PchRetDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_PchRetDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_EndDate]  DEFAULT ('') 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_PchRetDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_PchRetDetail_His_IsSelectBatch]  DEFAULT (0)  
    


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail_His]') AND name = N'IXC_PD_PchRetDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_PchRetDetail_His_BillDate on PD_PchRetDetail_His ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail_His]') AND name = N'IXC_PD_PchRetDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_PchRetDetail_His_BillNo on PD_PchRetDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail_His]') AND name = N'IX_PD_PchRetDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_PchRetDetail_His_GoodsIDPpt12ID on PD_PchRetDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail_His]') AND name = N'IX_PD_PchRetDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_PchRetDetail_His_WhsIDWhsPtID on PD_PchRetDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetDetail_His]') AND name = N'IX_PD_PchRetDetail_His_PchDID') 
	CREATE  INDEX IX_PD_PchRetDetail_His_PchDID on PD_PchRetDetail_His ([PchDID]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PchRetDetail_His' AND a.Name='GoodsNO')
    ALTER TABLE PD_PchRetDetail_His ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_PchRetDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_PchRetDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchRetSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_PchRetSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_PchRetSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetSerial]') AND name = N'XC_PD_PchRetSerial_BillDID') 
	CREATE INDEX XC_PD_PchRetSerial_BillDID on PD_PchRetSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchRetSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_PchRetSerial_His
(
	[ID] BIGINT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_PchRetSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchRetSerial_His]') AND name = N'XC_PD_PchRetSerial_His_BillDID') 
	CREATE INDEX XC_PD_PchRetSerial_His_BillDID on PD_PchRetSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_PchSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PchSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchSerial]') AND name = N'XC_PD_PchSerial_BillDID') 
	CREATE INDEX XC_PD_PchSerial_BillDID on PD_PchSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PchSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_PchSerial_His
(
	[ID] BIGINT  NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PchSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PchSerial_His]') AND name = N'XC_PD_PchSerial_His_BillDID') 
	CREATE INDEX XC_PD_PchSerial_His_BillDID on PD_PchSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PricePlan]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PricePlan]
(
    [PlanID] DECIMAL(18,0) IDENTITY(1,1),
    [TargetPriceID] [int] NOT NULL CONSTRAINT [DF_PD_PricePlan_TargetPriceID] DEFAULT (0),
    [SourcePriceID] [int] NOT NULL CONSTRAINT [DF_PD_PricePlan_SourcePriceID] DEFAULT (0),
    [SignMark] [int] NOT NULL CONSTRAINT [DF_PD_PricePlan_SignMark] DEFAULT (0),
    [SianValue] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_PricePlan_SianValue] DEFAULT (0),
    [Precision] [tinyint] NOT NULL CONSTRAINT [DF_PD_PricePlan_Precision] DEFAULT (4),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_PricePlan_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_PricePlan_CreateTime] DEFAULT getdate(),
    [GoodsTypeID] [BIGINT] NOT NULL CONSTRAINT [DF_PD_PricePlan_GoodsTypeID] DEFAULT (0),
    CONSTRAINT [PK_PD_PricePlan] PRIMARY KEY NONCLUSTERED ([PlanID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PricePlan' AND a.Name='GoodsTypeID')
    ALTER TABLE PD_PricePlan ADD GoodsTypeID BIGINT NOT NULL CONSTRAINT [DF_PD_PricePlan_GoodsTypeID] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PricePlan' AND a.Name='PlanID')
    ALTER TABLE PD_PricePlan ADD PlanID DECIMAL(18,0) NOT NULL IDENTITY(1,1)
  
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_PricePlan' AND a.Name='PID')
	BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PricePlan' AND so.xtype = 'PK' AND so.name = 'PK_PD_PricePlan')
			ALTER TABLE PD_PricePlan DROP CONSTRAINT [PK_PD_PricePlan]		
		ALTER TABLE PD_PricePlan DROP COLUMN PID
	END
	
IF NOT EXISTS (SELECT  b.column_name FROM information_schema.table_constraints a INNER JOIN information_schema.constraint_column_usage b ON a.constraint_name = b.constraint_name
 WHERE a.constraint_type = 'PRIMARY KEY' AND a.table_name = 'PD_PricePlan' AND b.COLUMN_NAME = 'PlanID')
	BEGIN
		ALTER TABLE PD_PricePlan DROP COLUMN PlanID
		ALTER TABLE PD_PricePlan ADD PlanID DECIMAL(18,0) NOT NULL IDENTITY(1,1)
	END
	
IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PricePlan' AND so.xtype = 'PK' AND so.name = 'PK_PD_PricePlan')
	ALTER TABLE PD_PricePlan ADD CONSTRAINT [PK_PD_PricePlan] PRIMARY KEY NONCLUSTERED ([PlanID])




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_PriceTrail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_PriceTrail]
(
    [TID] bigint IDENTITY(1,1) NOT NULL,
    [BtypeID] [int] NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [UnitID] [int] NOT NULL,
    [PchPrice] [decimal](20,8) NULL,
    [SellPrice] [decimal](20,8) NULL ,
    [PchDis] [decimal](20,8) NULL,
    [SellDis] [decimal](20,8) NULL,
    [PchDate] datetime  NULL ,
    [SellDate] datetime NULL ,
    CONSTRAINT [PK_PD_PriceTrail] PRIMARY KEY NONCLUSTERED ([TID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_PriceTrail]') AND name = N'IXC_PD_PriceTrail_BtypeIDGoodsIDUnitID') 
	CREATE CLUSTERED  INDEX IXC_PD_PriceTrail_BtypeIDGoodsIDUnitID on PD_PriceTrail ([BtypeID],[GoodsID],[UnitID]) WITH (FILLFACTOR = 90);
 



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_ProduceModelBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_ProduceModelBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [ModelName] [varchar](100) NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_ModelName] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [OutWhsID] [int] NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_OutWhsID] DEFAULT 0,
    [InWhsID] [int] NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_InWhsID] DEFAULT 0,
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_Qty] DEFAULT 0,
    [CreateDate] [datetime] NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_CreateDate] DEFAULT getdate(),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_Creator] DEFAULT (0),
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_Ppt2ID] DEFAULT (0),    
    [AssemblyCost] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_AssemblyCost] DEFAULT (0),
    CONSTRAINT [PK_PD_ProduceModelBill] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelBill' AND a.Name='Ppt1ID')
    ALTER TABLE PD_ProduceModelBill ADD Ppt1ID INT NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_Ppt1ID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelBill' AND a.Name='Ppt2ID')
    ALTER TABLE PD_ProduceModelBill ADD Ppt2ID INT NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_Ppt2ID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelBill' AND a.Name='AssemblyCost')
    ALTER TABLE PD_ProduceModelBill ADD AssemblyCost DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_ProduceModelBill_AssemblyCost] DEFAULT (0)
    
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelBill' AND a.Name='OutWhsID')
   AND NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_ProduceModelBill' AND so.xtype = 'D' AND so.name = 'DF_PD_ProduceModelBill_OutWhsID')
    ALTER TABLE PD_ProduceModelBill ADD CONSTRAINT [DF_PD_ProduceModelBill_OutWhsID] DEFAULT 0 for OutWhsID
    
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelBill' AND a.Name='InWhsID')
   AND NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_ProduceModelBill' AND so.xtype = 'D' AND so.name = 'DF_PD_ProduceModelBill_InWhsID')
    ALTER TABLE PD_ProduceModelBill ADD CONSTRAINT [DF_PD_ProduceModelBill_InWhsID] DEFAULT 0 for InWhsID
    
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelBill' AND a.Name='Qty')
   AND NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_ProduceModelBill' AND so.xtype = 'D' AND so.name = 'DF_PD_ProduceModelBill_Qty')
    ALTER TABLE PD_ProduceModelBill ADD CONSTRAINT [DF_PD_ProduceModelBill_Qty] DEFAULT 0 for Qty





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_ProduceModelDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_ProduceModelDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [GoodsID] [bigint] NOT NULL,
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_ProduceModelDetail_Qty] DEFAULT (0),
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_ProduceModelDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_ProduceModelDetail_Ppt2ID] DEFAULT (0),
    CONSTRAINT [PK_PD_ProduceModelDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelDetail' AND a.Name='Ppt1ID')
    ALTER TABLE PD_ProduceModelDetail ADD Ppt1ID INT NOT NULL CONSTRAINT [DF_PD_ProduceModelDetail_Ppt1ID] DEFAULT (0)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_ProduceModelDetail' AND a.Name='Ppt2ID')
    ALTER TABLE PD_ProduceModelDetail ADD Ppt2ID INT NOT NULL CONSTRAINT [DF_PD_ProduceModelDetail_Ppt2ID] DEFAULT (0)
	
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id 
         INNER JOIN sys.types c ON a.system_type_id = c.system_type_id  WHERE b.Name='PD_ProduceModelDetail' AND a.Name='BillNo' AND c.name = 'int')
    ALTER TABLE PD_ProduceModelDetail ALTER COLUMN BillNo BIGINT NOT NULL




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellAccounts]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellAccounts]
(
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [PayDate] [date] NOT NULL CONSTRAINT [DF_PD_SellAccounts_PayDate] DEFAULT getdate(),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellAccounts_Total] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellAccounts_PayRecTotal] DEFAULT (0),
    CONSTRAINT [PK_PD_SellAccounts] PRIMARY KEY CLUSTERED ([BillNo],[FinanceID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_SellBill_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [LogistBTypeID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_LogistBTypeID] DEFAULT (0),
    [LogistBillNo] [varchar](20) NULL CONSTRAINT [DF_PD_SellBill_LogistBillNo] DEFAULT (''),
    [Freight] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_Freight] DEFAULT (0),
    [FreightTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_FreightTotal] DEFAULT (0),
    [FreightFinanceID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_FreightFinanceID] DEFAULT (0),
    [FreightType] [bit] NOT NULL CONSTRAINT [DF_PD_SellBill_FreightType] DEFAULT (0),
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_SellBill_IsAccounts] DEFAULT (0),
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_PaidTotal] DEFAULT (0),
    [FreightPaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_FreightPaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_SellBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellBill_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_StlTag] DEFAULT (0),
    [FreightStlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_FreightStlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_SellBill_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_PD_SellBill_IsOS] DEFAULT(0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_InvoiceTotal] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_SellBill_AuditStatus] DEFAULT (0)    ,
    VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_SellBill_VerifyElyID] DEFAULT (0),
    VerifyDate VARCHAR(20)  NULL,
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellBill_IsInvoice] DEFAULT (1),
    VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellBill_VipCardID]  DEFAULT(0),
    DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_DeductionCent]  DEFAULT(0),
    IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellBill_IsDeduction] DEFAULT(0),
    ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_ExchangeCent]  DEFAULT(0),
    BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0), --此前应收
    CONSTRAINT [PK_PD_SellBill] PRIMARY KEY CLUSTERED ([BillNo]),
   
)
END
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='InvoiceMode')
    ALTER TABLE PD_SellBill ADD [InvoiceMode] tinyint NOT NULL CONSTRAINT [DF_PD_SellBill_InvoiceMode] DEFAULT (0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_SellBill' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellBill' AND so.xtype = 'D' AND so.name = 'DF_PD_SellBill_InvoiceMode')
			ALTER TABLE PD_SellBill DROP CONSTRAINT [DF_PD_SellBill_InvoiceMode]
		ALTER TABLE PD_SellBill ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_SellBill ADD CONSTRAINT [DF_PD_SellBill_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='VerifyElyID')
    ALTER TABLE dbo.PD_SellBill ADD VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_SellBill_VerifyElyID] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='VerifyDate')
    ALTER TABLE dbo.PD_SellBill ADD VerifyDate VARCHAR(20)  NULL 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_SellBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_SellBill_AuditStatus] DEFAULT (0) 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_SellBill ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_InvoiceTotal] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_SellBill ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellBill_IsInvoice] DEFAULT (1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='VipCardID')
    ALTER TABLE dbo.PD_SellBill ADD VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellBill_VipCardID]  DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='IsDeduction')
    ALTER TABLE dbo.PD_SellBill ADD IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellBill_IsDeduction] DEFAULT(0)
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='DeductionCent')
    ALTER TABLE dbo.PD_SellBill ADD DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_DeductionCent]  DEFAULT(0)      

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='PD_SellBill' AND a.Name='CentDisc')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellBill' AND so.xtype = 'D' AND so.name = 'DF_PD_SellBill_CentDisc')
			ALTER TABLE PD_SellBill DROP CONSTRAINT [DF_PD_SellBill_CentDisc]
		ALTER TABLE PD_SellBill DROP COLUMN CentDisc
    END    
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='ExchangeCent')
    ALTER TABLE dbo.PD_SellBill ADD ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_ExchangeCent]  DEFAULT(0)


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IXC_PD_SellBill_BillCode') 
	CREATE  INDEX IXC_PD_SellBill_BillCode on PD_SellBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IXC_PD_SellBill_BillDate') 
	CREATE  INDEX IXC_PD_SellBill_BillDate on PD_SellBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IXC_PD_SellBill_CreateTime') 
	CREATE  INDEX IXC_PD_SellBill_CreateTime on PD_SellBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IXC_PD_SellBill_PosTime') 
	CREATE  INDEX IXC_PD_SellBill_PosTime on PD_SellBill ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_BTypeID') 
	CREATE  INDEX IX_PD_SellBill_BTypeID on PD_SellBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_LogistBTypeID') 
	CREATE  INDEX IX_PD_SellBill_LogistBTypeID on PD_SellBill ([LogistBTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_WhsID') 
	CREATE  INDEX IX_PD_SellBill_WhsID on PD_SellBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_DeptID') 
	CREATE  INDEX IX_PD_SellBill_DeptID on PD_SellBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_ElyID') 
	CREATE  INDEX IX_PD_SellBill_ElyID on PD_SellBill ([ElyID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_FreightFinanceID') 
	CREATE  INDEX IX_PD_SellBill_FreightFinanceID on PD_SellBill ([FreightFinanceID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_FinanceID') 
	CREATE  INDEX IX_PD_SellBill_FinanceID on PD_SellBill ([FinanceID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill]') AND name = N'IX_PD_SellBill_VipCardID') 
	CREATE  INDEX IX_PD_SellBill_VipCardID on PD_SellBill ([VipCardID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill' AND a.Name='BeforeARTotal')
    ALTER TABLE PD_SellBill ADD BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0)


GO
    



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_SellBill_His_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [LogistBTypeID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_His_LogistBTypeID] DEFAULT (0),
    [LogistBillNo] [varchar](20) NULL CONSTRAINT [DF_PD_SellBill_His_LogistBillNo] DEFAULT (''),
    [Freight] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_Freight] DEFAULT (0),
    [FreightTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_FreightTotal] DEFAULT (0),
    [FreightFinanceID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_His_FreightFinanceID] DEFAULT (0),
    [FreightType] [bit] NOT NULL CONSTRAINT [DF_PD_SellBill_His_FreightType] DEFAULT (0),
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_His_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_SellBill_His_IsAccounts] DEFAULT (0),
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_PaidTotal] DEFAULT (0),
    [FreightPaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_FreightPaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_SellBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_SellBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellBill_His_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_His_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_His_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_His_StlTag] DEFAULT (0),
    [FreightStlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_His_FreightStlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_SellBill_His_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_PD_SellBill_His_IsOS] DEFAULT(0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellBill_His_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_InvoiceTotal] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_SellBill_His_AuditStatus] DEFAULT (0)    ,
    VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_SellBill_His_VerifyElyID] DEFAULT (0),
    VerifyDate VARCHAR(20)  NULL,
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellBill_His_IsInvoice] DEFAULT (1),
    VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellBill_His_VipCardID]  DEFAULT(0),
    IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellBill_His_IsDeduction] DEFAULT(0),
    DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_His_DeductionCent]  DEFAULT(0),
    ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_His_ExchangeCent]  DEFAULT(0),
    BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0),
    CONSTRAINT [PK_PD_SellBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='InvoiceMode')
    ALTER TABLE PD_SellBill_His ADD [InvoiceMode] tinyint NOT NULL CONSTRAINT [DF_PD_SellBill_His_InvoiceMode] DEFAULT (0)
 
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_SellBill_His' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_SellBill_His_InvoiceMode')
			ALTER TABLE PD_SellBill_His DROP CONSTRAINT [DF_PD_SellBill_His_InvoiceMode]
		ALTER TABLE PD_SellBill_His ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_SellBill_His ADD CONSTRAINT [DF_PD_SellBill_His_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_SellBill_His ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellBill_His_InvoiceTotal] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_SellBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_SellBill_His_AuditStatus] DEFAULT (0) 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='VerifyElyID')
    ALTER TABLE dbo.PD_SellBill_His ADD VerifyElyID INT NOT NULL CONSTRAINT [DF_PD_SellBill_His_VerifyElyID] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='VerifyDate')
    ALTER TABLE dbo.PD_SellBill_His ADD VerifyDate VARCHAR(20)  NULL 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_SellBill_His ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellBill_His_IsInvoice] DEFAULT (1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='VipCardID')
    ALTER TABLE dbo.PD_SellBill_His ADD VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellBill_His_VipCardID]  DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='IsDeduction')
    ALTER TABLE dbo.PD_SellBill_His ADD IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellBill_His_IsDeduction] DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='DeductionCent')
    ALTER TABLE dbo.PD_SellBill_His ADD DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_His_DeductionCent]  DEFAULT(0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='CentDisc')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_SellBill_His_CentDisc')
			ALTER TABLE PD_SellBill_His DROP CONSTRAINT [DF_PD_SellBill_His_CentDisc]
		ALTER TABLE PD_SellBill_His DROP COLUMN CentDisc
    END 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='ExchangeCent')
    ALTER TABLE dbo.PD_SellBill_His ADD ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellBill_His_ExchangeCent]  DEFAULT(0)
    
    

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IXC_PD_SellBill_His_BillCode') 
	CREATE  INDEX IXC_PD_SellBill_His_BillCode on PD_SellBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IXC_PD_SellBill_His_BillDate') 
	CREATE  INDEX IXC_PD_SellBill_His_BillDate on PD_SellBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IXC_PD_SellBill_His_CreateTime') 
	CREATE  INDEX IXC_PD_SellBill_His_CreateTime on PD_SellBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IXC_PD_SellBill_His_PosTime') 
	CREATE  INDEX IXC_PD_SellBill_His_PosTime on PD_SellBill_His ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_BTypeID') 
	CREATE  INDEX IX_PD_SellBill_His_BTypeID on PD_SellBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_LogistBTypeID') 
	CREATE  INDEX IX_PD_SellBill_His_LogistBTypeID on PD_SellBill_His ([LogistBTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_WhsID') 
	CREATE  INDEX IX_PD_SellBill_His_WhsID on PD_SellBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_DeptID') 
	CREATE  INDEX IX_PD_SellBill_His_DeptID on PD_SellBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_ElyID') 
	CREATE  INDEX IX_PD_SellBill_His_ElyID on PD_SellBill_His ([ElyID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_FreightFinanceID') 
	CREATE  INDEX IX_PD_SellBill_His_FreightFinanceID on PD_SellBill_His ([FreightFinanceID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_FinanceID') 
	CREATE  INDEX IX_PD_SellBill_His_FinanceID on PD_SellBill_His ([FinanceID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellBill_His]') AND name = N'IX_PD_SellBill_His_VipCardID') 
	CREATE  INDEX IX_PD_SellBill_His_VipCardID on PD_SellBill_His ([VipCardID]) WITH (FILLFACTOR = 90);  
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellBill_His' AND a.Name='BeforeARTotal')
    ALTER TABLE PD_SellBill_His ADD BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0);
  
go    



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
	[OrdDID] [bigint] NOT NULL CONSTRAINT [DF_PD_SellDetail_OrdDID] DEFAULT (0),
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_GoodsCostTotal] DEFAULT (-1),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellDetail_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_SellDetail_IsReconciled]  DEFAULT(0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_SellDetail_PriceID]  DEFAULT(0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_SellDetail_InPutPrice]  DEFAULT(1),
    [VerifyQty] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_VerifyQty] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_ComTotal] DEFAULT (0),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellDetail_EndDate]  DEFAULT (''),     
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellDetail_IsSelectBatch]  DEFAULT (0), 
     [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_SellDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_SellDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_SellDetail_InPutPrice]  DEFAULT(1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='PriceID')
    ALTER TABLE PD_SellDetail ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_SellDetail_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='VerifyQty')
    ALTER TABLE dbo.PD_SellDetail ADD VerifyQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_VerifyQty] DEFAULT (0)      
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='ComQty')
    ALTER TABLE PD_SellDetail ADD [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_ComQty] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='ComTotal')
    ALTER TABLE PD_SellDetail ADD  [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_ComTotal] DEFAULT (0)
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_SellDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_SellDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='EndDate')
    ALTER TABLE PD_SellDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellDetail_EndDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_SellDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellDetail_IsSelectBatch]  DEFAULT (0) 
     
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail]') AND name = N'IXC_PD_SellDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellDetail_BillDate on PD_SellDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail]') AND name = N'IXC_PD_SellDetail_BillNo') 
	CREATE  INDEX IXC_PD_SellDetail_BillNo on PD_SellDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail]') AND name = N'IX_PD_SellDetail_OrdDID') 
	CREATE  INDEX IX_PD_SellDetail_OrdDID on PD_SellDetail ([OrdDID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail]') AND name = N'IX_PD_SellDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_SellDetail_GoodsIDPpt12ID on PD_SellDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail]') AND name = N'IX_PD_SellDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_SellDetail_WhsIDWhsPtID on PD_SellDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail]') AND name = N'IX_PD_SellDetail_GoodsID') 
	CREATE INDEX [IX_PD_SellDetail_GoodsID] ON [PD_SellDetail] ([GoodsID])INCLUDE(BSQty,GoodsCostTotal)WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail' AND a.Name='GoodsNO')
    ALTER TABLE PD_SellDetail ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_SellDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO


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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
	[OrdDID] [bigint] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_OrdDID] DEFAULT (0),
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_GoodsCostTotal] DEFAULT (-1),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_IsReconciled]  DEFAULT(0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_SellDetail_His_PriceID]  DEFAULT(0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_SellDetail_His_InPutPrice]  DEFAULT(1),
    [VerifyQty] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_VerifyQty] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_ComTotal] DEFAULT (0),
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellDetail_His_EndDate]  DEFAULT (''), 
	[IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellDetail_His_IsSelectBatch]  DEFAULT (0)  ,
	 [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),     
    CONSTRAINT [PK_PD_SellDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='InPutPrice')
    ALTER TABLE PD_SellDetail_His ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_SellDetail_His_InPutPrice]  DEFAULT(1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='PriceID')
    ALTER TABLE PD_SellDetail_His ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_SellDetail_His_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='VerifyQty')
    ALTER TABLE dbo.PD_SellDetail_His ADD VerifyQty DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_VerifyQty] DEFAULT (0)      
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='ComQty')
    ALTER TABLE PD_SellDetail_His ADD [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_ComQty] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='ComTotal')
    ALTER TABLE PD_SellDetail_His ADD  [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_ComTotal] DEFAULT (0)
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_SellDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_SellDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_SellDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellDetail_His_EndDate]  DEFAULT ('') 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_SellDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellDetail_His_IsSelectBatch]  DEFAULT (0)    
    
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail_His]') AND name = N'IXC_PD_SellDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellDetail_His_BillDate on PD_SellDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail_His]') AND name = N'IXC_PD_SellDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_SellDetail_His_BillNo on PD_SellDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail_His]') AND name = N'IX_PD_SellDetail_His_OrdDID') 
	CREATE  INDEX IX_PD_SellDetail_His_OrdDID on PD_SellDetail_His ([OrdDID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail_His]') AND name = N'IX_PD_SellDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_SellDetail_His_GoodsIDPpt12ID on PD_SellDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail_His]') AND name = N'IX_PD_SellDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_SellDetail_His_WhsIDWhsPtID on PD_SellDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellDetail_His]') AND name = N'IX_PD_SellDetail_His_GoodsID') 
	CREATE INDEX [IX_PD_SellDetail_His_GoodsID] ON [PD_SellDetail_His] ([GoodsID])INCLUDE(BSQty,GoodsCostTotal)WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellDetail_His' AND a.Name='GoodsNO')
    ALTER TABLE PD_SellDetail_His ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_SellDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellOrdBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_CreateTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_Stt] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_StopTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_SellOrdBill] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdBill' AND a.Name='IsDraft')
BEGIN
    ALTER TABLE dbo.PD_SellOrdBill ADD [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_IsDraft] DEFAULT (1)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill]') AND name = N'IXC_PD_SellOrdBill_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellOrdBill_BillDate on PD_SellOrdBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill]') AND name = N'IX_PD_SellOrdBill_BTypeID') 
	CREATE  INDEX IX_PD_SellOrdBill_BTypeID on PD_SellOrdBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill]') AND name = N'IX_PD_SellOrdBill_WhsID') 
	CREATE  INDEX IX_PD_SellOrdBill_WhsID on PD_SellOrdBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill]') AND name = N'IX_PD_SellOrdBill_DeptID') 
	CREATE  INDEX IX_PD_SellOrdBill_DeptID on PD_SellOrdBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill]') AND name = N'IX_PD_SellOrdBill_ElyID') 
	CREATE  INDEX IX_PD_SellOrdBill_ElyID on PD_SellOrdBill ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_SellOrdBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdBill_AuditStatus] DEFAULT (0) 





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellOrdBill_His]
(
    [BillNo] [bigint]  NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_CreateTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_Stt] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_StopTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL,
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_PD_SellOrdBill_His] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdBill_His' AND a.Name='IsDraft')
BEGIN
    ALTER TABLE dbo.PD_SellOrdBill_His ADD [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_IsDraft] DEFAULT (1) 
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill_His]') AND name = N'IXC_PD_SellOrdBill_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellOrdBill_His_BillDate on PD_SellOrdBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill_His]') AND name = N'IX_PD_SellOrdBill_His_BTypeID') 
	CREATE  INDEX IX_PD_SellOrdBill_His_BTypeID on PD_SellOrdBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill_His]') AND name = N'IX_PD_SellOrdBill_His_WhsID') 
	CREATE  INDEX IX_PD_SellOrdBill_His_WhsID on PD_SellOrdBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill_His]') AND name = N'IX_PD_SellOrdBill_His_DeptID') 
	CREATE  INDEX IX_PD_SellOrdBill_His_DeptID on PD_SellOrdBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdBill_His]') AND name = N'IX_PD_SellOrdBill_His_ElyID') 
	CREATE  INDEX IX_PD_SellOrdBill_His_ElyID on PD_SellOrdBill_His ([ElyID]) WITH (FILLFACTOR = 90);
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_SellOrdBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdBill_His_AuditStatus] DEFAULT (0) 




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellOrdDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Price] DEFAULT (0),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Discount] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Tax] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_ComTotal] DEFAULT (0),
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Stt] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_Gift] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_StopTag] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_PriceID]  DEFAULT(0),
    [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_SellOrdDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdDetail' AND a.Name='PriceID')
    ALTER TABLE PD_SellOrdDetail ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail]') AND name = N'IXC_PD_SellOrdDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellOrdDetail_BillDate on PD_SellOrdDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail]') AND name = N'IXC_PD_SellOrdDetail_BillNo') 
	CREATE  INDEX IXC_PD_SellOrdDetail_BillNo on PD_SellOrdDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail]') AND name = N'IX_PD_SellOrdDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_SellOrdDetail_GoodsIDPpt12ID on PD_SellOrdDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail]') AND name = N'IX_PD_SellOrdDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_SellOrdDetail_WhsIDWhsPtID on PD_SellOrdDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdDetail' AND a.Name='GoodsNO')
    ALTER TABLE PD_SellOrdDetail ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellOrdDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_SellOrdDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

--条形码长度从20变成100 V6.2 谢吉康 2020-2-7
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellOrdDetail]') and  name = 'BarCode' and Length=30)
BEGIN
	 ALTER TABLE PD_SellOrdDetail
	    ALTER COLUMN BarCode VARCHAR(100)
END
GO



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellOrdDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Price] DEFAULT (0),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Discount] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Tax] DEFAULT (0),
    [ComQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_ComQty] DEFAULT (0),
    [ComTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_ComTotal] DEFAULT (0),
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Stt] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_Gift] DEFAULT (0),
    [StopTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_StopTag] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_PriceID]  DEFAULT(0),
    [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),
    CONSTRAINT [PK_PD_SellOrdDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdDetail_His' AND a.Name='PriceID')
    ALTER TABLE PD_SellOrdDetail_His ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_SellOrdDetail_His_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail_His]') AND name = N'IXC_PD_SellOrdDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellOrdDetail_His_BillDate on PD_SellOrdDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail_His]') AND name = N'IXC_PD_SellOrdDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_SellOrdDetail_His_BillNo on PD_SellOrdDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail_His]') AND name = N'IX_PD_SellOrdDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_SellOrdDetail_His_GoodsIDPpt12ID on PD_SellOrdDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellOrdDetail_His]') AND name = N'IX_PD_SellOrdDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_SellOrdDetail_His_WhsIDWhsPtID on PD_SellOrdDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellOrdDetail_His' AND a.Name='GoodsNO')
    ALTER TABLE PD_SellOrdDetail_His ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellOrdDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_SellOrdDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

--条形码长度从20变成100 V6.2 谢吉康 2020-2-7
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellOrdDetail_His]') and  name = 'BarCode' and Length=30)
BEGIN
	 ALTER TABLE PD_SellOrdDetail_His
	    ALTER COLUMN BarCode VARCHAR(100)
END
GO



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellRetBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_SellRetBill_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetBill_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_SellRetBill_IsAccounts] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_SellRetBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellRetBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellRetBill_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_SellRetBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellRetBill_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_SellRetBill_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_IsOS] DEFAULT(0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_InvoiceTotal] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_AuditStatus] DEFAULT (0)    ,
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_IsInvoice] DEFAULT (1),
    VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellRetBill_VipCardID]  DEFAULT(0),
    IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_IsDeduction] DEFAULT(0),
    DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_DeductionCent]  DEFAULT(0),
    ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_ExchangeCent]  DEFAULT(0),
	BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0),
    CONSTRAINT [PK_PD_SellRetBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='InvoiceMode')
    ALTER TABLE PD_SellRetBill ADD [InvoiceMode] TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_InvoiceMode] DEFAULT (0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_SellRetBill' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellRetBill' AND so.xtype = 'D' AND so.name = 'DF_PD_SellRetBill_InvoiceMode')
			ALTER TABLE PD_SellRetBill DROP CONSTRAINT [DF_PD_SellRetBill_InvoiceMode]
		ALTER TABLE PD_SellRetBill ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_SellRetBill ADD CONSTRAINT [DF_PD_SellRetBill_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_SellRetBill ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_InvoiceTotal] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_SellRetBill ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_IsInvoice] DEFAULT (1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='VipCardID')
    ALTER TABLE dbo.PD_SellRetBill ADD VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellRetBill_VipCardID]  DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='IsDeduction')
    ALTER TABLE dbo.PD_SellRetBill ADD IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_IsDeduction] DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='ExchangeCent')
    ALTER TABLE dbo.PD_SellRetBill ADD ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_ExchangeCent]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='DeductionCent')
    ALTER TABLE dbo.PD_SellRetBill ADD DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_DeductionCent]  DEFAULT(0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='CentDisc')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellRetBill' AND so.xtype = 'D' AND so.name = 'DF_PD_SellRetBill_CentDisc')
			ALTER TABLE PD_SellRetBill DROP CONSTRAINT [DF_PD_SellRetBill_CentDisc]
		ALTER TABLE PD_SellRetBill DROP COLUMN CentDisc
    END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_SellRetBill ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_AuditStatus] DEFAULT (0) 





IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IXC_PD_SellRetBill_BillCode') 
	CREATE  INDEX IXC_PD_SellRetBill_BillCode on PD_SellRetBill ([BillCode]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IXC_PD_SellRetBill_BillDate') 
	CREATE  INDEX IXC_PD_SellRetBill_BillDate on PD_SellRetBill ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IXC_PD_SellRetBill_CreateTime') 
	CREATE  INDEX IXC_PD_SellRetBill_CreateTime on PD_SellRetBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IXC_PD_SellRetBill_PosTime') 
	CREATE  INDEX IXC_PD_SellRetBill_PosTime on PD_SellRetBill ([PosTime]) WITH (FILLFACTOR = 90);
		
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IX_PD_SellRetBill_BTypeID') 
	CREATE  INDEX IX_PD_SellRetBill_BTypeID on PD_SellRetBill ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IX_PD_SellRetBill_WhsID') 
	CREATE  INDEX IX_PD_SellRetBill_WhsID on PD_SellRetBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IX_PD_SellRetBill_DeptID') 
	CREATE  INDEX IX_PD_SellRetBill_DeptID on PD_SellRetBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IX_PD_SellRetBill_ElyID') 
	CREATE  INDEX IX_PD_SellRetBill_ElyID on PD_SellRetBill ([ElyID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IX_PD_SellRetBill_FinanceID') 
	CREATE  INDEX IX_PD_SellRetBill_FinanceID on PD_SellRetBill ([FinanceID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill]') AND name = N'IX_PD_SellRetBill_VipCardID') 
	CREATE  INDEX IX_PD_SellRetBill_VipCardID on PD_SellRetBill ([VipCardID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill' AND a.Name='BeforeARTotal')
    ALTER TABLE PD_SellRetBill ADD BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0);

GO




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellRetBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DlvDate] [date] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_DlvDate] DEFAULT getdate(),
    [BTypeID] [int] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_BillQty] DEFAULT (0),
    [BTDTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_BTDTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_Privilege] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_PayRecTotal] DEFAULT (0),
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_FinanceID] DEFAULT (0),
    [IsAccounts] [bit] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_IsAccounts] DEFAULT (0),
	[PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_PaidTotal] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_PosTime] DEFAULT '',
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_Stt] DEFAULT (0),
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_Red] DEFAULT (0),
    [StlTag] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_StlTag] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_IsDraft] DEFAULT (1),
    IsOS TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_IsOS] DEFAULT(0),
    [InvoiceMode] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_InvoiceMode] DEFAULT (0),
    [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_InvoiceTotal] DEFAULT (0),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_AuditStatus] DEFAULT (0)    ,
    [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_IsInvoice] DEFAULT (1),
    VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_VipCardID]  DEFAULT(0),
    IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_IsDeduction] DEFAULT(0),
    DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_DeductionCent]  DEFAULT(0),
    ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_ExchangeCent]  DEFAULT(0),
    BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0),
    CONSTRAINT [PK_PD_SellRetBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='InvoiceMode')
    ALTER TABLE PD_SellRetBill_His ADD [InvoiceMode] TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_InvoiceMode] DEFAULT (0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='InvoiceMode' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellRetBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_SellRetBill_His_InvoiceMode')
			ALTER TABLE PD_SellRetBill_His DROP CONSTRAINT [DF_PD_SellRetBill_His_InvoiceMode]
		ALTER TABLE PD_SellRetBill_His ALTER COLUMN InvoiceMode tinyint NOT NULL
		ALTER TABLE PD_SellRetBill_His ADD CONSTRAINT [DF_PD_SellRetBill_His_InvoiceMode] DEFAULT(0) FOR InvoiceMode
    END
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='InvoiceTotal')
    ALTER TABLE PD_SellRetBill_His ADD [InvoiceTotal] DECIMAL(20,8) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_InvoiceTotal] DEFAULT (0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='IsInvoice')
    ALTER TABLE dbo.PD_SellRetBill_His ADD [IsInvoice] BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_IsInvoice] DEFAULT (1)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='VipCardID')
    ALTER TABLE dbo.PD_SellRetBill_His ADD VipCardID INT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_VipCardID]  DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='IsDeduction')
    ALTER TABLE dbo.PD_SellRetBill_His ADD IsDeduction BIT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_IsDeduction] DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='DeductionCent')
    ALTER TABLE dbo.PD_SellRetBill_His ADD DeductionCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_DeductionCent]  DEFAULT(0)  
        
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='ExchangeCent')
    ALTER TABLE dbo.PD_SellRetBill_His ADD ExchangeCent DECIMAL(10,0) NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_ExchangeCent]  DEFAULT(0)

IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='CentDisc')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_SellRetBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_SellRetBill_His_CentDisc')
			ALTER TABLE PD_SellRetBill_His DROP CONSTRAINT [DF_PD_SellRetBill_His_CentDisc]
		ALTER TABLE PD_SellRetBill_His DROP COLUMN CentDisc
    END
    
     
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='AuditStatus')
    ALTER TABLE dbo.PD_SellRetBill_His ADD AuditStatus TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetBill_His_AuditStatus] DEFAULT (0)    
    
    
    
    
    
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IXC_PD_SellRetBill_His_BillCode') 
	CREATE  INDEX IXC_PD_SellRetBill_His_BillCode on PD_SellRetBill_His ([BillCode]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IXC_PD_SellRetBill_His_BillDate') 
	CREATE  INDEX IXC_PD_SellRetBill_His_BillDate on PD_SellRetBill_His ([BillDate]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IXC_PD_SellRetBill_His_CreateTime') 
	CREATE  INDEX IXC_PD_SellRetBill_His_CreateTime on PD_SellRetBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IXC_PD_SellRetBill_His_PosTime') 
	CREATE  INDEX IXC_PD_SellRetBill_His_PosTime on PD_SellRetBill_His ([PosTime]) WITH (FILLFACTOR = 90);
		
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IX_PD_SellRetBill_His_BTypeID') 
	CREATE  INDEX IX_PD_SellRetBill_His_BTypeID on PD_SellRetBill_His ([BTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IX_PD_SellRetBill_His_WhsID') 
	CREATE  INDEX IX_PD_SellRetBill_His_WhsID on PD_SellRetBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IX_PD_SellRetBill_His_DeptID') 
	CREATE  INDEX IX_PD_SellRetBill_His_DeptID on PD_SellRetBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IX_PD_SellRetBill_His_ElyID') 
	CREATE  INDEX IX_PD_SellRetBill_His_ElyID on PD_SellRetBill_His ([ElyID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IX_PD_SellRetBill_His_FinanceID') 
	CREATE  INDEX IX_PD_SellRetBill_His_FinanceID on PD_SellRetBill_His ([FinanceID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetBill_His]') AND name = N'IX_PD_SellRetBill_His_VipCardID') 
	CREATE  INDEX IX_PD_SellRetBill_His_VipCardID on PD_SellRetBill_His ([VipCardID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetBill_His' AND a.Name='BeforeARTotal')
    ALTER TABLE PD_SellRetBill_His ADD BeforeARTotal [decimal](20,8) NOT  NULL DEFAULT(0);
GO




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellRetDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_GoodsCostTotal] DEFAULT (-1),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_IsReconciled]  DEFAULT(0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetDetail_PriceID]  DEFAULT(0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_InPutPrice]  DEFAULT(1),
    [SellDID] [bigint] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_SellDID] DEFAULT (0), 
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_EndDate]  DEFAULT (''),
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_IsSelectBatch]  DEFAULT (0), 
    [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),     
    CONSTRAINT [PK_PD_SellRetDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='InPutPrice')
    ALTER TABLE PD_SellRetDetail ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetDetail_InPutPrice]  DEFAULT(1)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='PriceID')
    ALTER TABLE PD_SellRetDetail ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetDetail_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='SellDID')
    ALTER TABLE dbo.PD_SellRetDetail ADD [SellDID] [bigint] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_SellDID] DEFAULT (0)   
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_SellRetDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_SellRetDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='EndDate')
    ALTER TABLE PD_SellRetDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_EndDate]  DEFAULT ('') 
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_SellRetDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_IsSelectBatch]  DEFAULT (0)
    
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail]') AND name = N'IXC_PD_SellRetDetail_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellRetDetail_BillDate on PD_SellRetDetail ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail]') AND name = N'IXC_PD_SellRetDetail_BillNo') 
	CREATE  INDEX IXC_PD_SellRetDetail_BillNo on PD_SellRetDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail]') AND name = N'IX_PD_SellRetDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_SellRetDetail_GoodsIDPpt12ID on PD_SellRetDetail ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail]') AND name = N'IX_PD_SellRetDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_SellRetDetail_WhsIDWhsPtID on PD_SellRetDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail]') AND name = N'IX_PD_SellRetDetail_SellDID') 
	CREATE  INDEX IX_PD_SellRetDetail_SellDID on PD_SellRetDetail ([SellDID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail' AND a.Name='GoodsNO')
    ALTER TABLE PD_SellRetDetail ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO	

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellRetDetail]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_SellRetDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellRetDetail]') and  name = 'BarCode' and Length=30)
BEGIN
	 ALTER TABLE PD_SellRetDetail
	    ALTER COLUMN BarCode VARCHAR(100)
END
Go



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_SellRetDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillDate] [DATE] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_WhsPtID] DEFAULT (0),
    [UnitID] [int] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_UnitID] DEFAULT (0),
    [Convfactor] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Convfactor] DEFAULT (1),
    [Price] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Price] DEFAULT (0),
    [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_CostPrice] DEFAULT (-1),
	[GoodsCostTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_GoodsCostTotal] DEFAULT (0),
    [DiscPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_DiscPrice] DEFAULT (0),
    [TaxPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_TaxPrice] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Qty] DEFAULT (0),
    [BSQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_BSQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Total] DEFAULT (0),
    [DiscTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_DiscTotal] DEFAULT (0),
    [TaxTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_TaxTotal] DEFAULT (0),
    [Discount] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Rebate] DEFAULT (1),
    [TaxRate] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_TaxRate] DEFAULT (0),
    [Tax] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Tax] DEFAULT (0),
    [Gift] [tinyint] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_Gift] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [IsReconciled] [BIT] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_IsReconciled]  DEFAULT(0),
    [PriceID] TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_PriceID]  DEFAULT(0),
    [InPutPrice] [TINYINT] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_InPutPrice]  DEFAULT(1),
    [SellDID] [bigint] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_SellDID] DEFAULT (0), 
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_EndDate]  DEFAULT (''),    
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_IsSelectBatch]  DEFAULT (0),   
    [GoodsNO] [varchar](50) NOT  NULL DEFAULT(''),    
    CONSTRAINT [PK_PD_SellRetDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='InPutPrice')
    ALTER TABLE PD_SellRetDetail_His ADD InPutPrice TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_InPutPrice]  DEFAULT(1)
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='PriceID')
    ALTER TABLE PD_SellRetDetail_His ADD PriceID TINYINT NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_PriceID]  DEFAULT(0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='SellDID')
    ALTER TABLE dbo.PD_SellRetDetail_His ADD [SellDID] [bigint] NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_SellDID] DEFAULT (0)   

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_SellRetDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_SellRetDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_SellRetDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_EndDate]  DEFAULT ('') 
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_SellRetDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_SellRetDetail_His_IsSelectBatch]  DEFAULT (0)
 

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail_His]') AND name = N'IXC_PD_SellRetDetail_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_SellRetDetail_His_BillDate on PD_SellRetDetail_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail_His]') AND name = N'IXC_PD_SellRetDetail_His_BillNo') 
	CREATE  INDEX IXC_PD_SellRetDetail_His_BillNo on PD_SellRetDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail_His]') AND name = N'IX_PD_SellRetDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_SellRetDetail_His_GoodsIDPpt12ID on PD_SellRetDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID],[UnitID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail_His]') AND name = N'IX_PD_SellRetDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_SellRetDetail_His_WhsIDWhsPtID on PD_SellRetDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetDetail_His]') AND name = N'IX_PD_SellRetDetail_His_SellDID') 
	CREATE  INDEX IX_PD_SellRetDetail_His_SellDID on PD_SellRetDetail_His ([SellDID]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_SellRetDetail_His' AND a.Name='GoodsNO')
    ALTER TABLE PD_SellRetDetail_His ADD [GoodsNO] [varchar](50)  NOT  NULL DEFAULT('')
GO	

--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_SellRetDetail_His]') and  name = 'Remark' and length=100)
BEGIN
	 ALTER TABLE PD_SellRetDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellRetSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_SellRetSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_SellRetSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetSerial]') AND name = N'XC_PD_SellRetSerial_BillDID') 
	CREATE INDEX XC_PD_SellRetSerial_BillDID on PD_SellRetSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellRetSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_SellRetSerial_His
(
	[ID] BIGINT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_SellRetSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellRetSerial_His]') AND name = N'XC_PD_SellRetSerial_His_BillDID') 
	CREATE INDEX XC_PD_SellRetSerial_His_BillDID on PD_SellRetSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_SellSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_SellSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellSerial]') AND name = N'XC_PD_SellSerial_BillDID') 
	CREATE INDEX XC_PD_SellSerial_BillDID on PD_SellSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_SellSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_SellSerial_His
(
	[ID] BIGINT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_SellSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_SellSerial_His]') AND name = N'XC_PD_SellSerial_His_BillDID') 
	CREATE INDEX XC_PD_SellSerial_His_BillDID on PD_SellSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_StockBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_StockBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockBill_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_StockBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_StockBill_CreateTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_StockBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_StockBill_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_StockBill_Stt] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_StockBill_IsDraft] DEFAULT (1),
    CONSTRAINT [PK_PD_StockBill] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill]') AND name = N'IXC_PD_StockBill_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_StockBill_BillDate on PD_StockBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill]') AND name = N'IX_PD_StockBill_WhsID') 
	CREATE  INDEX IX_PD_StockBill_WhsID on PD_StockBill ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill]') AND name = N'IX_PD_StockBill_DeptID') 
	CREATE  INDEX IX_PD_StockBill_DeptID on PD_StockBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill]') AND name = N'IX_PD_StockBill_ElyID') 
	CREATE  INDEX IX_PD_StockBill_ElyID on PD_StockBill ([ElyID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_StockBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_StockBill_His]
(
    [BillNo] [bigint] NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [BillQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockBill_His_BillQty] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_PD_StockBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_PD_StockBill_His_CreateTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_PD_StockBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_PD_StockBill_His_Description] DEFAULT '',
    [Stt] [tinyint] NOT NULL CONSTRAINT [DF_PD_StockBill_His_Stt] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_PD_StockBill_His_IsDraft] DEFAULT (1),
    CONSTRAINT [PK_PD_StockBill_His] PRIMARY KEY NONCLUSTERED ([BillNo])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill_His]') AND name = N'IXC_PD_StockBill_His_BillDate') 
	CREATE CLUSTERED  INDEX IXC_PD_StockBill_His_BillDate on PD_StockBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill_His]') AND name = N'IX_PD_StockBill_His_WhsID') 
	CREATE  INDEX IX_PD_StockBill_His_WhsID on PD_StockBill_His ([WhsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill_His]') AND name = N'IX_PD_StockBill_His_DeptID') 
	CREATE  INDEX IX_PD_StockBill_His_DeptID on PD_StockBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockBill_His]') AND name = N'IX_PD_StockBill_His_ElyID') 
	CREATE  INDEX IX_PD_StockBill_His_ElyID on PD_StockBill_His ([ElyID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_StockDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_StockDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_StockDetail_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_WhsPtID] DEFAULT (0),
    [StockQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_StockQty] DEFAULT (0),
    [CheckQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_CheckQty] DEFAULT (0),
    [PLQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_PLQty] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_StockDetail_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_StockDetail_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_StockDetail_EndDate]  DEFAULT (''), 
  	[CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_CostPrice] DEFAULT (0),
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_StockDetail_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_StockDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail' AND a.Name='BatchNumber')
    ALTER TABLE PD_StockDetail ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_StockDetail_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail' AND a.Name='ProductDate')
    ALTER TABLE PD_StockDetail ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_StockDetail_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail' AND a.Name='EndDate')
    ALTER TABLE PD_StockDetail ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_StockDetail_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail' AND a.Name='CostPrice')
    ALTER TABLE PD_StockDetail ADD [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_CostPrice] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_StockDetail ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_StockDetail_IsSelectBatch]  DEFAULT (0)
    

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockDetail]') AND name = N'IXC_PD_StockDetail_BillNo') 
	CREATE CLUSTERED  INDEX IXC_PD_StockDetail_BillNo on PD_StockDetail ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockDetail]') AND name = N'IX_PD_StockDetail_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_StockDetail_GoodsIDPpt12ID on PD_StockDetail ([GoodsID],[Ppt1ID],[Ppt2ID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockDetail]') AND name = N'IX_PD_StockDetail_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_StockDetail_WhsIDWhsPtID on PD_StockDetail ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
			--修改表结构长度
IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_StockDetail]') and  name = 'Remark' and length=100) 
BEGIN
	 ALTER TABLE PD_StockDetail
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_StockDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_StockDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BarCode] [varchar](100) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_BarCode] DEFAULT '',
    [GoodsID] [bigint] NOT NULL,
    [Ppt1ID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_His_Ppt1ID] DEFAULT (0),
    [Ppt2ID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_His_Ppt2ID] DEFAULT (0),
    [WhsID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_His_WhsID] DEFAULT (0),
    [WhsPtID] [int] NOT NULL CONSTRAINT [DF_PD_StockDetail_His_WhsPtID] DEFAULT (0),
    [StockQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_StockQty] DEFAULT (0),
    [CheckQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_CheckQty] DEFAULT (0),
    [PLQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_PLQty] DEFAULT (0),
    [Remark] [varchar](256) NULL,
    [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_BatchNumber]  DEFAULT (''),
	[ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_ProductDate]  DEFAULT (''),
	[EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_StockDetail_His_EndDate]  DEFAULT (''), 
	[CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_CostPrice] DEFAULT (0),
    [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_StockDetail_His_IsSelectBatch]  DEFAULT (0), 
    CONSTRAINT [PK_PD_StockDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail_His' AND a.Name='BatchNumber')
    ALTER TABLE PD_StockDetail_His ADD [BatchNumber] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_BatchNumber]  DEFAULT ('')

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail_His' AND a.Name='ProductDate')
    ALTER TABLE PD_StockDetail_His ADD [ProductDate] VARCHAR(10) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_ProductDate]  DEFAULT ('')  

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail_His' AND a.Name='EndDate')
    ALTER TABLE PD_StockDetail_His ADD [EndDate] VARCHAR(10)  NOT NULL CONSTRAINT [DF_PD_StockDetail_His_EndDate]  DEFAULT ('') 

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail_His' AND a.Name='CostPrice')
    ALTER TABLE PD_StockDetail_His ADD [CostPrice] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_StockDetail_His_CostPrice] DEFAULT (0)

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_StockDetail_His' AND a.Name='IsSelectBatch')
    ALTER TABLE PD_StockDetail_His ADD [IsSelectBatch] [bit]  NOT NULL CONSTRAINT [DF_PD_StockDetail_His_IsSelectBatch]  DEFAULT (0)


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockDetail_His]') AND name = N'IXC_PD_StockDetail_His_BillNo') 
	CREATE CLUSTERED  INDEX IXC_PD_StockDetail_His_BillNo on PD_StockDetail_His ([BillNo]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockDetail_His]') AND name = N'IX_PD_StockDetail_His_GoodsIDPpt12ID') 
	CREATE  INDEX IX_PD_StockDetail_His_GoodsIDPpt12ID on PD_StockDetail_His ([GoodsID],[Ppt1ID],[Ppt2ID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockDetail_His]') AND name = N'IX_PD_StockDetail_His_WhsIDWhsPtID') 
	CREATE  INDEX IX_PD_StockDetail_His_WhsIDWhsPtID on PD_StockDetail_His ([WhsID],[WhsPtID]) WITH (FILLFACTOR = 90);
	
	IF EXISTS(select * from syscolumns where id = object_id(N'[dbo].[PD_StockDetail_His]') and  name = 'Remark' and length=100) 
BEGIN
	 ALTER TABLE PD_StockDetail_His
	    ALTER COLUMN Remark VARCHAR(256) NULL
END
GO

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



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_StockSerial]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_StockSerial
(
	[ID] BIGINT IDENTITY(1,1) NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_StockSerial] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockSerial]') AND name = N'XC_PD_StockSerial_BillDID') 
	CREATE INDEX XC_PD_StockSerial_BillDID on PD_StockSerial ([BillDID]) WITH (FILLFACTOR = 90);
   



/*====================== TABLE: [D9ZTInfo] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_StockSerial_His]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_StockSerial_His
(
	[ID] BIGINT NOT NULL,
    [Serial] [varchar](50) NULL,
	[BillDID] BIGINT NOT NULL,
	[CostPrice]	DECIMAL(20,8) NULL,
	[Remark] [varchar](256) NULL,
    CONSTRAINT [PK_PD_StockSerial_His] PRIMARY KEY NONCLUSTERED ([ID])
    )
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_StockSerial_His]') AND name = N'XC_PD_StockSerial_His_BillDID') 
	CREATE INDEX XC_PD_StockSerial_His_BillDID on PD_StockSerial_His ([BillDID]) WITH (FILLFACTOR = 90);
   



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

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from sys.objects where object_id = object_id(N'[dbo].[PD_VipCardBillScore]') and type IN(N'U'))
BEGIN
	CREATE TABLE [PD_VipCardBillScore](
		[ID] [BIGINT] IDENTITY(1,1) NOT NULL,
		[BillTypeID] INT NOT NULL,
		[BillNo] [BIGINT] NOT NULL,
		[GoodsID] [INT]  NULL,
		[Type][TINYINT]  NULL,
		[Cent] DECIMAL(10,0) NULL,
		[Total] DECIMAL(20,8) NULL,
		[BillDate] DATE NULL,
		[ScoreRemark] VARCHAR(256) NULL,
		CONSTRAINT [PK_PD_VipCardBillScore] PRIMARY KEY NONCLUSTERED ([ID])
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_VipCardBillScore]') AND name = N'IXC_PD_VipCardBillScore_BillTypeID') 
	CREATE CLUSTERED INDEX IXC_PD_VipCardBillScore_BillTypeID on PD_VipCardBillScore ([BillTypeID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_VipCardBillScore]') AND name = N'IX_PD_VipCardBillScore_BillNo') 
	CREATE INDEX IX_PD_VipCardBillScore_BillNo on PD_VipCardBillScore ([BillNo]) WITH (FILLFACTOR = 90);	
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_VipCardBillScore]') AND name = N'IX_PD_VipCardBillScore_GoodsID') 
	CREATE INDEX IX_PD_VipCardBillScore_GoodsID on PD_VipCardBillScore (GoodsID) WITH (FILLFACTOR = 90);
	
	
------------------------------------------表修改区域结束-------------------------------------------------


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




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PD_WeiXinAccounts]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_WeiXinAccounts]
(
	[ID] INT IDENTITY(1,1) NOT NULL,
	[BillTypeID] INT NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_PD_WeiXinAccounts_Total] DEFAULT (0),
    PayStatus TINYINT NOT NULL CONSTRAINT [DF_PD_WeiXinAccounts_PayStatus] DEFAULT (0),
    CONSTRAINT [PK_PD_WeiXinAccounts] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF EXISTS(SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_WeiXinAccounts]') AND name = N'PK_PD_WeiXinAccounts' AND type_desc='CLUSTERED')
BEGIN
	ALTER TABLE [dbo].[PD_WeiXinAccounts] DROP CONSTRAINT [PK_PD_WeiXinAccounts]
	ALTER TABLE [dbo].[PD_WeiXinAccounts] ADD CONSTRAINT [PK_PD_WeiXinAccounts] PRIMARY KEY NONCLUSTERED ([ID] ASC) ON [PRIMARY]
END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_WeiXinAccounts]') AND name = N'IXC_PD_WeiXinAccounts_BillTypeID') 
	CREATE CLUSTERED INDEX IXC_PD_WeiXinAccounts_BillTypeID on PD_WeiXinAccounts ([BillTypeID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_WeiXinAccounts]') AND name = N'IX_PD_WeiXinAccounts_BillNo') 
	CREATE INDEX IX_PD_WeiXinAccounts_BillNo on PD_WeiXinAccounts ([BillNo]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_WeiXinAccounts]') AND name = N'IX_PD_WeiXinAccounts_FinanceID') 
	CREATE INDEX IX_PD_WeiXinAccounts_FinanceID on PD_WeiXinAccounts ([FinanceID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PD_WeiXinRecord]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_WeiXinRecord
(
	[ID] INT IDENTITY(1,1) NOT NULL,
	[BillTypeID] INT NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [BillCode] VARCHAR(50) NOT NULL CONSTRAINT [DF_PD_WeiXinRecord_BillCode] DEFAULT(''),
    [appid] VARCHAR(32),
    [sub_mch_id] VARCHAR(32),
    device_info VARCHAR(32),
	result_code VARCHAR(16),
	err_code VARCHAR(32),
	err_code_des VARCHAR(156),
    [openid] VARCHAR(128),
    [is_subscribe] CHAR(1),
    sub_openid VARCHAR(128),
	sub_is_subscribe CHAR(1),
	trade_type VARCHAR(16),
	bank_type VARCHAR(16),
	fee_type VARCHAR(16),
	total_fee INTEGER,
	cash_fee_type VARCHAR(16),
	cash_fee INT,
	coupon_fee INT,
	transaction_id VARCHAR(32),
	out_trade_no VARCHAR(32)  NOT NULL CONSTRAINT [DF_PD_WeiXinRecord_out_trade_no] DEFAULT(''),
	[attach] VARCHAR(128), 
	time_end VARCHAR(14),
	coupon_count INT,
	coupon_id VARCHAR(20),
	coupon_id_batch VARCHAR(20),
	out_refund_no VARCHAR(32) NOT NULL CONSTRAINT [DF_PD_WeiXinRecord_out_refund_no] DEFAULT(''),
	refund_id VARCHAR(28),
	refund_channel VARCHAR(16),
	refund_fee INT ,
	cash_refund_fee INT,
	coupon_refund_fee  INT,
	coupon_refund_count INT,
	coupon_refund_id INT,
	refund_status varchar(16)
    CONSTRAINT [PK_PD_WeiXinRecord] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='PD_WeiXinRecord' AND a.Name='BillCode')
    ALTER TABLE PD_WeiXinRecord ADD  [BillCode] VARCHAR(50) NOT NULL


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_WeiXinRecord]') AND name = N'IXC_PD_WeiXinRecord_BillTypeID') 
	CREATE CLUSTERED INDEX IXC_PD_WeiXinRecord_BillTypeID on PD_WeiXinRecord ([BillTypeID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_WeiXinRecord]') AND name = N'IX_PD_WeiXinRecord_BillNo') 
	CREATE INDEX IX_PD_WeiXinRecord_BillNo on PD_WeiXinRecord ([BillNo]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PD_WeiXinRecord_Success]') AND type in (N'U'))
BEGIN
CREATE TABLE PD_WeiXinRecord_Success
(
	[DID] INT IDENTITY(1,1) NOT NULL,
	[RecordID] INT NOT NULL,
    [openid] VARCHAR(128),
    [is_subscribe] CHAR(1),
    sub_openid VARCHAR(128),
	sub_is_subscribe CHAR(1),
	trade_type VARCHAR(16),
	bank_type VARCHAR(16),
	fee_type VARCHAR(16),
	total_fee INTEGER,
	cash_fee_type VARCHAR(16),
	cash_fee INT,
	coupon_fee INT,
	transaction_id VARCHAR(32),
	out_trade_no VARCHAR(32),
	[attach] VARCHAR(128), 
	time_end VARCHAR(14),
	coupon_count INT,
	coupon_id_$n VARCHAR(20),
	coupon_id_batch_$n VARCHAR(20),
	coupon_fee_$n INT,
	CONSTRAINT [PK_PD_WeiXinRecord_Success] PRIMARY KEY NONCLUSTERED ([DID])
)
END

	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[PD_WeiXinRecord_Success]') AND name = N'IX_PD_WeiXinRecord_Success_RecordID') 
	CREATE INDEX IX_PD_WeiXinRecord_Success_RecordID on PD_WeiXinRecord_Success ([RecordID]) WITH (FILLFACTOR = 90);




if not exists (select * from sysobjects where id = object_id(N'[sqlLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	CREATE TABLE [sqlLog] (
		[id] [int] IDENTITY (1, 1) NOT NULL ,
		[type] [tinyint] NOT NULL ,
		[dateTime] [datetime] NOT NULL ,
		[elapsed] [int] NOT NULL ,
		[url] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[params] [varchar] (1000) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[ipAddress] [varchar] (15) COLLATE Chinese_PRC_CI_AS NULL ,
		[_sql] [varchar] (8000) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[executeElapsed] [int] NOT NULL ,
		[fetchElapsed] [int] NOT NULL ,
		[_rowCount] [int] NOT NULL ,
		[error] [varchar] (400) COLLATE Chinese_PRC_CI_AS NULL ,
		[profileId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[loginUserId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
end	
GO

------------------------------------------表修改区域开始-------------------------------------------------
IF EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='sqlLog' AND a.Name='_sql' AND Length=2000
)
BEGIN
	ALTER TABLE sqlLog
	 ALTER COLUMN _sql [varchar] (8000) NOT NULL
END
GO
IF  EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[sqlLog]') and name = 'params' )
BEGIN
	ALTER TABLE sqlLog 
		ALTER COLUMN  params VARCHAR(1000);
END

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

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

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


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

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



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[PD_AuditItems]') AND type in (N'U'))
BEGIN
CREATE TABLE [PD_AuditItems]
(
    [ID] INT IDENTITY(1,1) NOT NULL,
	[Description] [varchar](255) NULL,
    CONSTRAINT [PK_PD_AuditItems] PRIMARY KEY NONCLUSTERED ([ID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_AuditSet]') AND type in (N'U'))
BEGIN
CREATE TABLE SS_AuditSet
(
    [ID] INT IDENTITY(1,1) NOT NULL,
	[BillTypeID] [int] NOT NULL,
	[ProjectName] VARCHAR(100) NOT NULL,
    [ProjectCode] VARCHAR(50) NOT NULL,
	[IfUse] [bit] NOT NULL,
	[Range] [TinyINT] NOT NULL CONSTRAINT [DF_SS_AuditSet_Range] DEFAULT (1),
	[DeptID] VARCHAR(200) NOT NULL CONSTRAINT [DF_SS_AuditSet_DeptID] DEFAULT(''),
	[SignElyID] int NOT NULL CONSTRAINT [DF_SS_AuditSet_SignElyID] DEFAULT(0),
	[SpecElyID] INT NOT NULL CONSTRAINT [DF_SS_AuditSet_SpecElyID]  DEFAULT(0),
	[CreateDate] DATE NOT NULL,
	[ModifyDate] DATE NULL,
    CONSTRAINT [PK_SS_AuditSet] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_AuditSet' AND a.Name='Range')
    ALTER TABLE SS_AuditSet ADD Range tinyint NOT NULL CONSTRAINT [DF_SS_AuditSet_Range] DEFAULT (1)



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_AuditSetDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE SS_AuditSetDetail
(
    [ID] INT IDENTITY(1,1) NOT NULL,
	[SetID] [int] NOT NULL,
	[Type] [TINYINT] NOT NULL,
	[Level] [TINYINT] NOT NULL,
	[StepName] [varchar](50)NOT NULL,
	[ElyID] VARCHAR(200),
	[Sort] [int] NOT NULL,
	[StepID] INT NOT NULL,
	[AuditType] TINYINT NOT NULL,
    CONSTRAINT [PK_SS_AuditSetDetail] PRIMARY KEY NONCLUSTERED ([ID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_AuditStepReason]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_AuditStepReason]
(
    [ID] INT IDENTITY(1,1) NOT NULL,
	[SetDID] INT NOT NULL,
	[ItemsID] INT  NOT NULL,
	[Value] VARCHAR(50) NOT NULL
    CONSTRAINT [PK_SS_AuditStepReason] PRIMARY KEY NONCLUSTERED ([ID])
)
END





GO
/*====================== TABLE: [SS_BarcodeRule] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_BarcodeRule]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_BarcodeRule]
(
    [ID] INT NOT NULL,
    [SeqStart] TINYINT NOT NULL,
    [SeqEnd] TINYINT NULL,
    [FieldID] TINYINT NOT NULL,
    CONSTRAINT [PK_SS_BarcodeRule] PRIMARY KEY CLUSTERED ([ID])
)
END



/*====================== TABLE: [SS_Btype_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Btype_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Btype_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [BtypeID] [int] NOT NULL,
    [BtypeTypeID] [int] NOT NULL,
    [Flag] [bit] NOT NULL CONSTRAINT [DF_SS_Btype_Jur_Flag] DEFAULT (0),
    CONSTRAINT [PK_SS_Btype_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Btype_Jur]') AND name = N'IXU_SS_Btype_Jur_RoleID') 
	CREATE  INDEX IXU_SS_Btype_Jur_RoleID on SS_Btype_Jur ([RoleID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Btype_Jur]') AND name = N'IX_SS_Btype_Jur_BtypeID') 
	CREATE  INDEX IX_SS_Btype_Jur_BtypeID on SS_Btype_Jur ([BtypeID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Btype_Jur' AND a.Name='BtypeTypeID')
BEGIN
	ALTER TABLE SS_Btype_Jur ADD BtypeTypeID INT NULL
	EXEC sp_executesql N'UPDATE a SET a.BtypeTypeID = b.BtypeTypeID FROM 
						 SS_Btype_Jur a INNER JOIN BD_Btype b ON a.BTypeID = b.BTypeID WHERE a.BtypeTypeID IS NULL'
	ALTER TABLE SS_Btype_Jur ALTER COLUMN BtypeTypeID INT NOT NULL
END



/*====================== TABLE: [SS_BtypeType_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_BtypeType_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_BtypeType_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [BtypeTypeID] [int] NOT NULL,
    [LimitTag] TINYINT NOT NULL CONSTRAINT [DF_SS_BtypeType_Jur_LimitTag] DEFAULT (0),
    CONSTRAINT [PK_SS_BtypeType_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_BtypeType_Jur' AND a.Name='LimitTag')
BEGIN
	ALTER TABLE [SS_BtypeType_Jur] ADD LimitTag TINYINT  NOT NULL CONSTRAINT [DF_SS_BtypeType_Jur_LimitTag] DEFAULT (0)
END



/*====================== TABLE: [SS_Company] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Company]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Company]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [CompKey] [varchar](200) NOT NULL,
    [CompValue] [varchar](500) NOT NULL,
    CONSTRAINT [PK_SS_Company] PRIMARY KEY CLUSTERED ([ID])
)
SET IDENTITY_INSERT [SS_Company] ON
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (10,'CompanyName','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (11,'LinkMan','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (12,'Tel','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (13,'Province','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (14,'City','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (15,'Area','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (16,'Postcode','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (17,'Address','');
    INSERT INTO [SS_Company] ([ID],[CompKey],[CompValue]) values (18,'QQ','');
SET IDENTITY_INSERT [SS_Company] OFF
END





/*====================== TABLE: [SS_Eshop_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Eshop_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Eshop_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [OperID] [int] NOT NULL,
    [EshopID] [int] NOT NULL,
    [Flag] [bit] NOT NULL,
    CONSTRAINT [PK_SS_Eshop_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Eshop_Jur]') AND name = N'IXU_SS_Eshop_Jur_OperID') 
	CREATE  INDEX IXU_SS_Eshop_Jur_OperID on SS_Eshop_Jur ([OperID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Eshop_Jur]') AND name = N'IX_SS_Eshop_Jur_EshopID') 
	CREATE  INDEX IX_SS_Eshop_Jur_EshopID on SS_Eshop_Jur ([EshopID]) WITH (FILLFACTOR = 90);




/*====================== TABLE: [SS_Finance_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Finance_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Finance_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [FinanceID] [int] NOT NULL,
    [FinanceTypeID] [int] NOT NULL,
    [Flag] [bit] NOT NULL CONSTRAINT [DF_SS_Finance_Jur_Flag] DEFAULT (0),
    CONSTRAINT [PK_SS_Finance_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Finance_Jur]') AND name = N'IXU_SS_Finance_Jur_RoleID') 
	CREATE  INDEX IXU_SS_Finance_Jur_RoleID on SS_Finance_Jur ([RoleID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Finance_Jur]') AND name = N'IX_SS_Finance_Jur_FinanceID') 
	CREATE  INDEX IX_SS_Finance_Jur_FinanceID on SS_Finance_Jur ([FinanceID]) WITH (FILLFACTOR = 90);



/*====================== TABLE: [SS_FinanceType_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_FinanceType_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_FinanceType_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [FinanceTypeID] [int] NOT NULL,
    [LimitTag] TINYINT NOT NULL CONSTRAINT [DF_SS_FinanceType_Jur_LimitTag] DEFAULT (0),
    CONSTRAINT [PK_SS_FinanceType_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_FinanceType_Jur' AND a.Name='LimitTag')
BEGIN
	ALTER TABLE [SS_FinanceType_Jur] ADD LimitTag TINYINT  NOT NULL CONSTRAINT [DF_SS_FinanceType_Jur_LimitTag] DEFAULT (0)
END



/*====================== TABLE: [SS_Jur_Type] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Jur_Type]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Jur_Type]
(
    [JurTypeID] [int] IDENTITY(1,1) NOT NULL,
    [TypeName] [varchar](50) NOT NULL CONSTRAINT [DF_SS_Jur_Type_TypeName] DEFAULT '',
    [TypeCode] [varchar](10) NOT NULL CONSTRAINT [DF_SS_Jur_Type_TypeCode] DEFAULT '',
    CONSTRAINT [PK_SS_Jur_Type] PRIMARY KEY CLUSTERED ([JurTypeID])
)
SET IDENTITY_INSERT [SS_Jur_Type] ON
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (1,'查看','View');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (2,'新增/复制/录入','create');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (3,'修改','modified');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (4,'删除','delete');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (5,'停用/终止','stop');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (6,'打印','print');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (7,'导入','input');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (8,'导出','output');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (9,'新建分类','createtype');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (10,'新建子类','createson');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (11,'设置','set');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (12,'过账','posting');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (13,'处理','handle');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (14,'结存','balance');
	INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (15,'经营历程','BsProcess');
	INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (16,'业务草稿','draft');
	INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (17,'数据搬移','datamove');
	INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (18,'数据结转','datatrans');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (19,'保存','save');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (20,'价格权限','priceinfo');
    INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (99,'定制权限-其它权限','extother');
SET IDENTITY_INSERT [SS_Jur_Type] OFF
END
IF NOT EXISTS (SELECT 1 FROM [SS_Jur_Type] WHERE JurTypeID = 99)
	BEGIN
		SET IDENTITY_INSERT [SS_Jur_Type] ON
			INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (99,'定制权限-其它权限','extother')
		SET IDENTITY_INSERT [SS_Jur_Type] OFF
	END
IF NOT EXISTS (SELECT 1 FROM [SS_Jur_Type] WHERE JurTypeID = 20)
	BEGIN
		SET IDENTITY_INSERT [SS_Jur_Type] ON
			INSERT INTO [SS_Jur_Type] ([JurTypeID],[TypeName],[TypeCode]) values (20,'价格权限','priceinfo')
		SET IDENTITY_INSERT [SS_Jur_Type] OFF
	END




/*====================== TABLE: [SS_Jurisdiction] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Jurisdiction]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Jurisdiction]
(
    [JurID] [int] NOT NULL,
    [JurName] [varchar](50) NOT NULL,
    [MenuID] [int] NOT NULL CONSTRAINT [DF_SS_Jurisdiction_MenuID] DEFAULT (0),
    [JurTypeID] [int] NOT NULL,
    [OrdID] [int] NOT NULL default(1000),
    CONSTRAINT [PK_SS_Jurisdiction] PRIMARY KEY CLUSTERED ([JurID])
)

END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Jurisdiction]') AND name = N'IX_SS_Jurisdiction_JurTypeID') 
	CREATE  INDEX IX_SS_Jurisdiction_JurTypeID on SS_Jurisdiction ([JurTypeID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Jurisdiction]') AND name = N'IX_SS_Jurisdiction_MenuID') 
	CREATE  INDEX IX_SS_Jurisdiction_MenuID on SS_Jurisdiction ([MenuID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Jurisdiction' AND a.Name='OrdID')
    ALTER TABLE SS_Jurisdiction ADD OrdID INT NOT NULL CONSTRAINT [DF_SS_Jurisdiction_OrdID] DEFAULT(1000)	

GO


TRUNCATE TABLE [SS_Jurisdiction]

    --INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID]) values (1010010,'系统开账',3005,11);
    --INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID]) values (1010110,'系统重建',3006,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1010010,'进销存设置',3002,11,1);
    --INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID]) values (1010110,'网店设置',3003,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1010110,'操作员管理',3007,11,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1010210,'用户组权限',3008,11,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1010310,'组合条码规则设置',3013,11,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1010410,'微信支付设置',3014,11,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1010510,'关于软件',3012,11,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1010610,'手机版',3015,11,7);
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110010,'商品信息',2507,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110011,'商品信息',2507,2,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110012,'商品信息',2507,3,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110013,'商品信息',2507,4,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110014,'商品信息',2507,5,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110015,'商品信息',2507,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110016,'商品信息',2507,7,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110110,'地区信息',2511,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110111,'地区信息',2511,2,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110112,'地区信息',2511,3,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110113,'地区信息',2511,4,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110114,'地区信息',2511,5,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110115,'地区信息',2511,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110116,'地区信息',2511,7,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110210,'往来单位',2512,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110211,'往来单位',2512,2,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110212,'往来单位',2512,3,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110213,'往来单位',2512,4,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110214,'往来单位',2512,5,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110215,'往来单位',2512,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110216,'往来单位',2512,7,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110310,'部门信息',2513,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110311,'部门信息',2513,2,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110312,'部门信息',2513,3,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110313,'部门信息',2513,4,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110314,'部门信息',2513,5,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110315,'部门信息',2513,6,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110316,'部门信息',2513,7,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110410,'职员信息',2514,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110411,'职员信息',2514,2,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110412,'职员信息',2514,3,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110413,'职员信息',2514,4,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110414,'职员信息',2514,5,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110415,'职员信息',2514,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110416,'职员信息',2514,7,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110510,'存货仓库',2515,1,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110511,'存货仓库',2515,2,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110512,'存货仓库',2515,3,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110513,'存货仓库',2515,4,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110514,'存货仓库',2515,5,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110515,'存货仓库',2515,6,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110516,'存货仓库',2515,7,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110610,'货位信息',2516,1,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110611,'货位信息',2516,2,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110612,'货位信息',2516,3,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110613,'货位信息',2516,4,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110614,'货位信息',2516,5,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110615,'货位信息',2516,6,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110616,'货位信息',2516,7,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110710,'财务项目',2505,1,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110711,'财务项目',2505,2,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110712,'财务项目',2505,3,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110713,'财务项目',2505,4,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110714,'财务项目',2505,5,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110715,'财务项目',2505,6,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110716,'财务项目',2505,7,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110810,'价格设置',2531,1,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110811,'价格设置',2531,2,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110812,'价格设置',2531,3,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110813,'价格设置',2531,4,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110814,'价格设置',2531,5,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110815,'价格设置',2531,6,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1110816,'价格设置',2531,7,9);
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120010,'商品分类',2507,9,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120011,'商品分类',2507,10,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120012,'商品分类',2507,3,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120013,'商品分类',2507,4,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120110,'往来单位分类',2512,9,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120111,'往来单位分类',2512,10,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120112,'往来单位分类',2512,3,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120113,'往来单位分类',2512,4,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120210,'仓库分类',2515,9,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120211,'仓库分类',2515,10,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120212,'仓库分类',2515,3,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1120213,'仓库分类',2515,4,3);
																		
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130010,'属性值设置',2508,11,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130110,'属性组设置',2509,11,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130210,'商品多编号设置',2510,11,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130310,'期初库存商品录入',2517,11,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130410,'期初应收应付录入',2518,11,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130510,'期初现金银行录入',2519,11,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130610,'物价管理查看',1031,1,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130710,'物价管理修改',1031,3,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130810,'价格跟踪查看',1032,1,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1130910,'价格跟踪修改',1032,3,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131010,'预设价1',8000,20,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131110,'预设价2',8000,20,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131210,'预设价3',8000,20,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131310,'预设价4',8000,20,14);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131410,'预设价5',8000,20,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131510,'最近进价',8000,1,35);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131610,'成本查看',8000,1,36);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131710,'期初收入支出录入',2520,11,37);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131810,'自定义基础资料',2522,1,38);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1131910,'基础资料自定义字段配置',2523,1,39);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1133510,'商品条码打印',2524,1,40);
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132010,'预设价6',8000,20,16);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132110,'预设价7',8000,20,17);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132210,'预设价8',8000,20,18);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132310,'预设价9',8000,20,19);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132410,'预设价10',8000,20,20);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132510,'预设价11',8000,20,21);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132610,'预设价12',8000,20,22);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132710,'预设价13',8000,20,23);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132810,'预设价14',8000,20,24);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1132910,'预设价15',8000,20,25);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1133010,'预设价16',8000,20,26);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1133110,'预设价17',8000,20,27);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1133210,'预设价18',8000,20,28);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1133310,'预设价19',8000,20,29);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1133410,'预设价20',8000,20,30);
    
																		
																		
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210010,'采购订单',1502,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210011,'采购订单',1502,2,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210012,'采购订单',1502,19,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210013,'采购订单',1502,12,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210014,'采购订单',1502,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210110,'采购入库单',1501,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210111,'采购入库单',1501,2,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210112,'采购入库单',1501,19,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210113,'采购入库单',1501,12,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210114,'采购入库单',1501,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210210,'采购退货单',1504,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210211,'采购退货单',1504,2,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210212,'采购退货单',1504,19,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210213,'采购退货单',1504,12,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1210214,'采购退货单',1504,6,3);
																		
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220010,'采购订单管理',1503,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220011,'采购订单管理',1503,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220110,'采购订单汇总查询',1511,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220111,'采购订单汇总查询',1511,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220210,'采购订单明细查询',1510,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220211,'采购订单明细查询',1510,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220310,'采购汇总统计',1508,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220311,'采购汇总统计',1508,6,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220410,'采购明细查询',1509,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220411,'采购明细查询',1509,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220510,'采购退货统计',1506,1,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1220511,'采购退货统计',1506,6,6);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1230010,'采购订单删除',1502,4,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1230110,'采购订单中止',1502,5,2);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310010,'销售订单',1001,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310011,'销售订单',1001,2,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310012,'销售订单',1001,19,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310013,'销售订单',1001,12,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310014,'销售订单',1001,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310110,'销售出库单',1003,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310111,'销售出库单',1003,2,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310112,'销售出库单',1003,19,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310113,'销售出库单',1003,12,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310114,'销售出库单',1003,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310210,'销售退货单',1004,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310211,'销售退货单',1004,2,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310212,'销售退货单',1004,19,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310213,'销售退货单',1004,12,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1310214,'销售退货单',1004,6,3);
																		
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320010,'销售订单管理',1002,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320011,'销售订单管理',1002,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320110,'销售订单汇总查询',1006,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320111,'销售订单汇总查询',1006,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320210,'销售订单明细查询',1007,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320211,'销售订单明细查询',1007,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320310,'销售汇总统计',1008,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320311,'销售汇总统计',1008,6,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320410,'销售明细查询',1009,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320411,'销售明细查询',1009,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320510,'销售退货统计',1010,1,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320511,'销售退货统计',1010,6,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320610,'滞销商品查询',1011,1,30);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1320611,'滞销商品查询',1011,6,30);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1330010,'销售订单删除',1001,4,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1330110,'销售订单中止',1001,5,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1330210,'超过对账期允许保存销售草稿',8000,19,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1330310,'超过对账期允许销售单据过账',8000,12,4);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410010,'同价调拨单',2001,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410011,'同价调拨单',2001,2,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410012,'同价调拨单',2001,19,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410013,'同价调拨单',2001,12,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410014,'同价调拨单',2001,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410110,'调价单',2002,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410111,'调价单',2002,2,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410112,'调价单',2002,19,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410113,'调价单',2002,12,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410114,'调价单',2002,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410210,'其他入库单',2003,1,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410211,'其他入库单',2003,2,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410212,'其他入库单',2003,19,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410213,'其他入库单',2003,12,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410214,'其他入库单',2003,6,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410310,'其它出库单',2004,1,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410311,'其它出库单',2004,2,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410312,'其它出库单',2004,19,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410313,'其它出库单',2004,12,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410314,'其它出库单',2004,6,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410410,'报损单',2005,1,20);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410411,'报损单',2005,2,20);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410412,'报损单',2005,19,20);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410413,'报损单',2005,12,20);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410414,'报损单',2005,6,20);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410510,'报溢单',2006,1,25);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410511,'报溢单',2006,2,25);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410512,'报溢单',2006,19,25);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410513,'报溢单',2006,12,25);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410514,'报溢单',2006,6,25);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410610,'变价调拨单',2022,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410611,'变价调拨单',2022,2,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410612,'变价调拨单',2022,19,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410613,'变价调拨单',2022,12,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410614,'变价调拨单',2022,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410710,'调拨申请单',2021,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410711,'调拨申请单',2021,2,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410712,'调拨申请单',2021,19,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410713,'调拨申请单',2021,12,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410714,'调拨申请单',2021,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410810,'生产拆装单',2030,1,35);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410811,'生产拆装单',2030,2,35);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410812,'生产拆装单',2030,19,35);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410813,'生产拆装单',2030,12,35);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1410814,'生产拆装单',2030,6,35);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420010,'库存状况表',2010,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420011,'库存状况表',2010,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420110,'存货明细账',2011,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420111,'存货明细账',2011,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420210,'出入库汇总查询',2012,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420211,'出入库汇总查询',2012,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420310,'出入库单据明细',2014,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420311,'出入库单据明细',2014,6,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420410,'进销存汇总表',2013,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420411,'进销存汇总表',2013,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420510,'货位及属性调整',2008,1,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420511,'货位及属性调整',2008,6,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420610,'调拨申请管理',2023,1,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420611,'调拨申请管理',2023,6,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420710,'调拨验收',2024,1,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420711,'调拨验收',2024,6,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420810,'库存上下限设置',2016,1,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420811,'库存上下限设置',2016,6,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420910,'库存上限报警',2017,1,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1420911,'库存上限报警',2017,6,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421010,'库存下限报警',2019,1,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421011,'库存下限报警',2019,6,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421110,'虚拟库存查询',2031,1,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421111,'虚拟库存查询',2031,6,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421210,'序列号库存查询',2025,1,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421211,'序列号库存查询',2025,6,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421310,'序列号跟踪查询',2026,1,14);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421311,'序列号跟踪查询',2026,6,14);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421410,'批次库存查询',2027,1,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421411,'批次库存查询',2027,6,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421510,'批次跟踪查询',2028,1,16);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1421511,'批次跟踪查询',2028,6,16);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430010,'盘点单录入',2007,2,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430110,'盘点单修改',2007,3,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430210,'盘点单删除',2007,4,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430310,'盘点单处理',2007,13,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430410,'货位属性调整',2008,13,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430510,'调拨申请单删除',2023,4,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430610,'调拨申请单中止',2023,5,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430710,'生产模板录入',2521,2,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430810,'生产模板修改',2521,3,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1430910,'生产模板删除',2521,4,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1431010,'库存分布查看所有仓库',8000,11,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1431110,'调拨验收入库',2024,13,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1431210,'出入库条码校验',2032,1,13);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510010,'网店配置',4530,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510110,'商品信息手工同步',4510,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510210,'商品对应关系设置',4515,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510310,'网店商品数量更新',4516,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510410,'网店业务处理',4540,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510510,'已处理订单下载',4551,1,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510610,'运费结算单据下载',4552,1,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510710,'网店订单统计',4561,1,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510810,'退换货业务统计',4562,1,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1510910,'商品库存手工同步',4517,1,10);
																		 
																		
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610010,'付款单',3502,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610011,'付款单',3502,2,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610012,'付款单',3502,19,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610013,'付款单',3502,12,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610014,'付款单',3502,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610110,'收款单',3503,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610111,'收款单',3503,2,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610112,'收款单',3503,19,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610113,'收款单',3503,12,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610114,'收款单',3503,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610210,'现金费用单',3505,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610211,'现金费用单',3505,2,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610212,'现金费用单',3505,19,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610213,'现金费用单',3505,12,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610214,'现金费用单',3505,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610310,'一般费用单',3506,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610311,'一般费用单',3506,2,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610312,'一般费用单',3506,19,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610313,'一般费用单',3506,12,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610314,'一般费用单',3506,6,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610410,'其它收入单',3507,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610411,'其它收入单',3507,2,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610412,'其它收入单',3507,19,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610413,'其它收入单',3507,12,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610414,'其它收入单',3507,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610510,'转款单',3508,1,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610511,'转款单',3508,2,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610512,'转款单',3508,19,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610513,'转款单',3508,12,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610514,'转款单',3508,6,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610610,'应收增加',3510,1,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610611,'应收增加',3510,2,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610612,'应收增加',3510,19,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610613,'应收增加',3510,12,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610614,'应收增加',3510,6,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610710,'应收减少',3535,1,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610711,'应收减少',3535,2,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610712,'应收减少',3535,19,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610713,'应收减少',3535,12,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610714,'应收减少',3535,6,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610810,'应付增加',3511,1,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610811,'应付增加',3511,2,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610812,'应付增加',3511,19,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610813,'应付增加',3511,12,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610814,'应付增加',3511,6,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610910,'应付减少',3512,1,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610911,'应付减少',3512,2,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610912,'应付减少',3512,19,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610913,'应付减少',3512,12,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1610914,'应付减少',3512,6,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611010,'销售发票',3547,1,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611011,'销售发票',3547,2,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611012,'销售发票',3547,19,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611013,'销售发票',3547,12,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611014,'销售发票',3547,6,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611110,'采购发票',3548,1,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611111,'采购发票',3548,2,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611112,'采购发票',3548,19,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611113,'采购发票',3548,12,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1611114,'采购发票',3548,6,12);
      
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620010,'单位应收应付',3530,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620011,'单位应收应付',3530,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620110,'单位应收应付明细',-1010,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620111,'单位应收应付明细',-1010,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620210,'往来发生统计',3515,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620211,'往来发生统计',3515,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620310,'往来对账',3514,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620311,'往来对账',3514,6,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620410,'按单结算查询',3518,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620411,'按单结算查询',3518,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620510,'回款统计',3521,1,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620511,'回款统计',3521,6,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620610,'项目明细查询',3519,1,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620611,'项目明细查询',3519,6,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620710,'项目历史对比',3537,1,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620711,'项目历史对比',3537,6,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620810,'现金银行查询',3538,1,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620811,'现金银行查询',3538,6,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620910,'费用支出统计',3531,1,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1620911,'费用支出统计',3531,6,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621010,'费用分布表',3532,1,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621011,'费用分布表',3532,6,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621110,'其他收入统计',3536,1,14);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621111,'其他收入统计',3536,6,14);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621210,'经营利润表',3534,1,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621211,'经营利润表',3534,6,15);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621310,'创利分类统计',3529,1,16);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621311,'创利分类统计',3529,6,16);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621410,'销售发票管理',3541,1,17);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621411,'销售发票管理',3541,6,17);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621510,'销售开票统计',3542,1,18);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621511,'销售开票统计',3542,6,18);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621610,'销售单据开票情况查询',3543,1,19);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621611,'销售单据开票情况查询',3543,6,19);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621710,'采购发票管理',3544,1,20);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621711,'采购发票管理',3544,6,20)
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621810,'采购开票统计',3545,1,21);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621811,'采购开票统计',3545,6,21);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621910,'采购单据开票情况查询',3546,1,22);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1621911,'采购单据开票情况查询',3546,6,22);
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1622210,'现金银行报表',3539,1,23);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1622211,'现金银行报表',3539,6,23);

    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1622010,'应收超期查询',3549,1,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1622011,'应收超期查询',3549,6,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1622110,'微信支付对账单查询',3550,1,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1622111,'微信支付对账单查询',3550,6,8);

    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1630010,'月结存',3009,13,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1630110,'销售发票审核',3547,13,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1630210,'销售发票反审核',3547,13,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1630310,'采购发票审核',3548,13,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1630410,'采购发票反审核',3548,13,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1630510,'收支账户显示余额',8000,11,6);
    --INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeI,[OrdID])D]) values (1630110,'年结存',8000,13);
																		 
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710010,'经营历程',4002,15,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710110,'经营历程-修改单据',8000,3,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710210,'红冲本人单据',8000,3,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710310,'红冲他人单据',8000,3,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710410,'业务草稿',4001,16,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710510,'录单日期修改',8000,3,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710610,'修改他人草稿',8000,3,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710710,'查看他人草稿',8000,1,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710810,'赠品标记权限',8000,11,9);
    --INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1710910,'归档还原',8000,11,10);
    --INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1711010,'归档数据查询',8000,11,11);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1711110,'单据审核设置',3011,15,12);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1711210,'单据审核中心',4004,15,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1711310,'单据查看应收余额',4004,15,14);  
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1711410,'单据查看应付余额',4004,15,15);  
      
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1810010,'往来单位详情',8000,15,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1810110,'商品详情',8000,15,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1810210,'库存分布',8000,15,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1810310,'月度销售情况',8000,15,13);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (1810410,'历史售价',8000,15,13);
    
    ---会员管理权限
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010010,'积分兑换单',5004,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010011,'积分兑换单',5004,2,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010012,'积分兑换单',5004,19,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010013,'积分兑换单',5004,12,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010014,'积分兑换单',5004,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010110,'会员充值单',5009,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010111,'会员充值单',5009,2,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010112,'会员充值单',5009,19,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010113,'会员充值单',5009,12,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2010114,'会员充值单',5009,6,2);
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020010,'会员卡类型设置',5002,1,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020011,'会员卡类型设置',5002,6,1);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020110,'会员卡管理',5003,1,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020111,'会员卡管理',5003,6,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020210,'会员消费统计',5005,1,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020211,'会员消费统计',5005,6,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020310,'会员消费明细',5006,1,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020311,'会员消费明细',5006,6,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020410,'会员积分明细',5007,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020411,'会员积分明细',5007,6,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020510,'会员充值查询',5008,1,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2020511,'会员充值查询',5008,6,5);
    
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030010,'会员卡类型新增',5002,2,2);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030110,'会员卡类型修改',5002,3,3);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030210,'会员卡类型删除',5002,4,4);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030310,'会员卡新增',5001,13,5);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030410,'会员卡修改',5003,13,6);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030510,'会员卡删除',5003,4,7);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030610,'会员卡挂失',5003,5,8);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030710,'会员卡停用',5003,2,9);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030810,'会员卡批量导入',5003,3,10);
    INSERT INTO [SS_Jurisdiction] ([JurID],[JurName],[MenuID],[JurTypeID],[OrdID]) values (2030910,'积分调整单',8000,1,1);
    
 
 
GO



/*====================== TABLE: [SS_Jurisdiction_Ext] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Jurisdiction_Ext]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Jurisdiction_Ext]
(
    [JurID] [int] NOT NULL,
    [JurName] [varchar](50) NOT NULL,
    [MenuID] [int] NOT NULL CONSTRAINT [DF_SS_Jurisdiction_Ext_MenuID] DEFAULT (0),
    [JurTypeID] [int] NOT NULL,
    [ExtID] TINYINT NOT NULL CONSTRAINT [DF_SS_Jurisdiction_Ext_ExtID] DEFAULT (0),
    CONSTRAINT [PK_SS_Jurisdiction_Ext] PRIMARY KEY CLUSTERED ([JurID])
)

END

IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Jurisdiction_Ext' AND a.Name='ExtID')
    ALTER TABLE SS_Jurisdiction_Ext ADD [ExtID] TINYINT NOT NULL CONSTRAINT [DF_SS_Jurisdiction_Ext_ExtID] DEFAULT (0)
    
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Jurisdiction_Ext]') AND name = N'IX_SS_Jurisdiction_Ext_JurTypeID') 
	CREATE  INDEX IX_SS_Jurisdiction_Ext_JurTypeID on SS_Jurisdiction_Ext ([JurTypeID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Jurisdiction_Ext]') AND name = N'IX_SS_Jurisdiction_Ext_MenuID') 
	CREATE  INDEX IX_SS_Jurisdiction_Ext_MenuID on SS_Jurisdiction_Ext ([MenuID]) WITH (FILLFACTOR = 90);



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_MacAddr_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_MacAddr_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [MacAddr] [varchar](50) NOT NULL CONSTRAINT [DF_SS_MacAddr_Jur_MacAddr] DEFAULT '',
    [Remark] [varchar](256) NOT NULL CONSTRAINT [DF_SS_MacAddr_Jur_Remark] DEFAULT '',
    [Creator] [int] NOT NULL CONSTRAINT [DF_SS_MacAddr_Jur_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_SS_MacAddr_Jur_CreateTime] DEFAULT getdate(),
    CONSTRAINT [PK_SS_MacAddr_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END






IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_MonthArAp]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_MonthArAp]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Period] [tinyint] NOT NULL,
    [BTypeID] [int] NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthArAp_Total] DEFAULT (0),
    [BqTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthArAp_BqTotal] DEFAULT (0),
    CONSTRAINT [PK_SS_MonthArAp] PRIMARY KEY NONCLUSTERED ([ID])
)
END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_MonthBalance]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_MonthBalance]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Period] [tinyint] NOT NULL,
    [FinanceID] [int] NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthBalance_Total] DEFAULT (0),
    [BqTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthBalance_BqTotal] DEFAULT (0),
    CONSTRAINT [PK_SS_MonthBalance] PRIMARY KEY NONCLUSTERED ([ID])
)
END





/*====================== TABLE: [SS_MonthProc] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_MonthProc]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_MonthProc]
(
    [Period] [tinyint] NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [StartDate] [datetime] NOT NULL,
    [EndDate] [datetime] NULL,
    [Remark] [varchar](100) NULL,
    [State] [bit] NOT NULL CONSTRAINT [DF_SS_MonthProc_State] DEFAULT (0),
    CONSTRAINT [PK_SS_MonthProc] PRIMARY KEY NONCLUSTERED ([Period])
)
    
    -- ********	处理 SS_MonthProc	********
	DELETE FROM SS_MonthProc
	INSERT INTO SS_MonthProc Select 1,'本期','2015-01-01',NULL,'',0

END





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_MonthStock]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_MonthStock]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Period] [tinyint] NOT NULL,
    [WhsID] [int] NULL,
    [GoodsID] [int] NULL,
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthStock_Total] DEFAULT (0),
    [BqTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthStock_BqTotal] DEFAULT (0),
    [Qty] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthStock_Qty] DEFAULT (0),
    [BqQty] [decimal](20,8) NOT NULL CONSTRAINT [DF_SS_MonthStock_BqQty] DEFAULT (0),
    CONSTRAINT [PK_SS_SS_MonthStock] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_MonthStock]') AND name = N'IX_SS_MonthStock_WhsIDGoodsID') 
	CREATE CLUSTERED INDEX IX_SS_MonthStock_WhsIDGoodsID on SS_MonthStock ([WhsID],[GoodsID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_MonthStock]') AND name = N'IX_SS_MonthStock_GoodsID') 
	CREATE  INDEX IX_SS_MonthStock_GoodsID on SS_MonthStock ([GoodsID]) WITH (FILLFACTOR = 90);




/*====================== TABLE: [SS_Oper_Role] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Oper_Role]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Oper_Role]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [OperID] [int] NOT NULL,
    [RoleID] [int] NOT NULL,
    [Stt] [bit] NOT NULL CONSTRAINT [DF_SS_Oper_Role_Stt] DEFAULT (1),
    CONSTRAINT [PK_SS_Oper_Role] PRIMARY KEY NONCLUSTERED ([ID])
)
END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Oper_Role]') AND name = N'IXU_SS_Oper_Role_OperID') 
	CREATE  INDEX IXU_SS_Oper_Role_OperID on SS_Oper_Role ([OperID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Oper_Role]') AND name = N'IX_SS_Oper_Role_RoleID') 
	CREATE  INDEX IX_SS_Oper_Role_RoleID on SS_Oper_Role ([RoleID]) WITH (FILLFACTOR = 90);
 



/*====================== TABLE: [SS_Operator] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Operator]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Operator]
(
    [ElyID] [int] NOT NULL,
    [PASSWORD] [varchar](50) NOT NULL CONSTRAINT [DF_SS_Operator_PASSWORD] DEFAULT '',
    [Stt] [bit] NOT NULL CONSTRAINT [DF_SS_Operator_Stt] DEFAULT (1),
    [SysRow] [bit] NOT NULL CONSTRAINT [DF_SS_Operator_SysRow] DEFAULT (0),
    [remark] [varchar](256) NULL,
    [LoginCount] [int] NOT NULL CONSTRAINT [DF_SS_Operator_LoginCount] DEFAULT 0,
    CONSTRAINT [PK_SS_Operator] PRIMARY KEY CLUSTERED ([ElyID])
)
INSERT INTO [SS_Operator] ([ElyID],[Password],[Stt],[SysRow],[Remark]) values (1,'',1,1,'');
END
	
IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Operator' AND a.Name='LoginCount')
	ALTER TABLE SS_Operator ADD [LoginCount] [int] NOT NULL CONSTRAINT [DF_SS_Operator_LoginCount] DEFAULT 0
	



IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_OtherCfg]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_OtherCfg]
(
    [ID] [int] NOT NULL,
    [CfgName] [varchar](100) NOT NULL,
    [CfgValue] [tinyint] NOT NULL,
    [Remark] [varchar](256) NOT NULL CONSTRAINT [DF_SS_OtherCfg_Remark] DEFAULT '',
    CONSTRAINT [PK_SS_OtherCfg] PRIMARY KEY NONCLUSTERED ([ID])
)
    INSERT INTO [SS_OtherCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (101,'LoginLimit',0,'启用登录限制；0=不启用 1=启用');
END

IF NOT EXISTS (SELECT 1 FROM [SS_OtherCfg] where ID = 102)
    INSERT INTO [SS_OtherCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (102,'VirtualFormula',0,'账面库存 + 采购订单在途数 - 销售订单未发数 + 草稿数量');

GO




/*====================== TABLE: [SS_Role] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Role]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Role]
(
    [RoleID] [int] IDENTITY(1,1) NOT NULL,
    [RoleName] [varchar](20) NOT NULL,
    [Describe] [varchar](100) NULL,
    [Stt] [bit] NOT NULL CONSTRAINT [DF_SS_Role_Stt] DEFAULT (1),
    [WhsLimitTag] TINYINT NOT NULL CONSTRAINT [DF_SS_Role_WhsLimitTag] DEFAULT (0),
    [BtypeLimitTag] TINYINT NOT NULL CONSTRAINT [DF_SS_Role_BtypeLimitTag] DEFAULT (0),
    [FinanceLimitTag] TINYINT NOT NULL CONSTRAINT [DF_SS_Role_FinanceLimitTag] DEFAULT (0),
    CONSTRAINT [PK_SS_Role] PRIMARY KEY CLUSTERED ([RoleID])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Role' AND a.Name='WhsLimitTag')
BEGIN
	ALTER TABLE [SS_Role] ADD WhsLimitTag TINYINT  NOT NULL CONSTRAINT [DF_SS_Role_WhsLimitTag] DEFAULT (0)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Role' AND a.Name='BtypeLimitTag')
BEGIN
	ALTER TABLE [SS_Role] ADD BtypeLimitTag TINYINT  NOT NULL CONSTRAINT [DF_SS_Role_BtypeLimitTag] DEFAULT (0)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Role' AND a.Name='FinanceLimitTag')
BEGIN
	ALTER TABLE [SS_Role] ADD FinanceLimitTag TINYINT  NOT NULL CONSTRAINT [DF_SS_Role_FinanceLimitTag] DEFAULT (0)
END







/*====================== TABLE: [SS_Role_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Role_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Role_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [JurID] [int] NOT NULL,
    [opp] [tinyint] NOT NULL,
    CONSTRAINT [PK_SS_Role_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Role_Jur]') AND name = N'IXU_SS_Role_Jur_RoleID') 
	CREATE  INDEX IXU_SS_Role_Jur_RoleID on SS_Role_Jur ([RoleID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Role_Jur]') AND name = N'IX_SS_Role_Jur_JurID') 
	CREATE  INDEX IX_SS_Role_Jur_JurID on SS_Role_Jur ([JurID]) WITH (FILLFACTOR = 90);
 




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Role_Jur_Cfg]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Role_Jur_Cfg]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [CfgID] [int] NOT NULL,
    [CfgValue] [int] NOT NULL,
    CONSTRAINT [PK_SS_Role_Jur_Cfg] PRIMARY KEY NONCLUSTERED ([ID])
)
END




/*====================== TABLE: [SS_Role_Jur_Ext] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Role_Jur_Ext]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Role_Jur_Ext]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [JurID] [int] NOT NULL,
    [opp] [tinyint] NOT NULL,
    CONSTRAINT [PK_SS_Role_Jur_Ext] PRIMARY KEY NONCLUSTERED ([ID])
)
END
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Role_Jur_Ext]') AND name = N'IXU_SS_Role_Jur_Ext_RoleID') 
	CREATE  INDEX IXU_SS_Role_Jur_Ext_RoleID on SS_Role_Jur_Ext ([RoleID]) WITH (FILLFACTOR = 90);
 
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Role_Jur_Ext]') AND name = N'IX_SS_Role_Jur_Ext_JurID') 
	CREATE  INDEX IX_SS_Role_Jur_Ext_JurID on SS_Role_Jur_Ext ([JurID]) WITH (FILLFACTOR = 90);
 




GO
/*====================== TABLE: [SS_SysCfg] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_SysCfg]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_SysCfg]
(
    [ID] [int] NOT NULL,
    [CfgName] [varchar](100) NOT NULL,
    [CfgValue] INT NOT NULL,
    [Remark] [varchar](256) NULL,
    CONSTRAINT [PK_SS_SysCfg] PRIMARY KEY CLUSTERED ([ID])
)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (101,'AccountType',1,'收付款结算方式;1=按单结算 2=按金额结算');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (102,'IsNegative',0,'允许负库存；0=不允许 1=允许');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (103,'PropertyM',0,'属性管理；0=不启用 1=启用 2=不可取消');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (104,'HasWhsPt',0,'启用货位；0=不启用 1=启用 2=不可取消');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (105,'AutoDayPaid',0,'自动日结；0=不启用 1=启用');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (106,'DayPaidTime',1900000,'自动日结时间');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (107,'NotAllowNegativeTotal',0,'库存金额不允许为负；0=不启用 1=启用');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (108,'ElyDeptStrictMatch',0,'单据上经手人和部门严格对应；0=不启用 1=启用');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (109,'SerialNoMgt',0,'启用序列号管理；0=不启用 1=启用');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (110,'AutoGoodsName',0,'自动生成商品名称；0=不启用 1=启用');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (111,'ReportSum',0,'报表统计合计值；0=不启用 1=启用');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (112,'CostMethod',1,'成本算法；1=移动加权 2=手工指定 3=按商品配置');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (113,'UseBtypeCode',0,'启用往来单位商品编号；0=不启用 1=启用');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (114,'UsePtypeQuery',0,'启用商品开单模糊查询；0=不启用 1=启用');
	
	
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (201,'BuyDefault',1,'采购读取预设价；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (202,'SaleDefault',1,'销售读取预设价；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (203,'AutoRemark',1,'自动生成摘要;0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (204,'PostAllowPrint',1,'已过账状态允许打印；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (205,'SaveAllowPrint',1,'已保存状态允许打印；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (206,'PostTipPrint',0,'过账后提示打印；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (207,'SaveTipPrint',0,'保存后提示打印；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (208,'UseBuyDiscount',0,'启用采购折扣；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (209,'UseSaleDiscount',0,'启用销售折扣；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (210,'UseBuyPrcTrack',0,'启用采购价格跟踪;0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (211,'UseBuyDisTrack',0,'启用采购折扣跟踪；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (212,'UseSalePrcTrack',0,'启用销售价格跟踪;0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (213,'UseSaleDisTrack',0,'启用销售折扣跟踪；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (214,'IsSaleZero',0,'销售允许单价为0；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (215,'AutoSavePricePlan',0,'自动保存价格批量调整方案；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (216,'OverAllowSaveSale',0,'超过对账期允许保存销售草稿；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (217,'OverAllowPostSale',0,'超过对账期允许销售单据过账；0=不选 1=勾选');
	
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (301,'BuyMustImportOrd',0,'采购入库必须引用采购订单；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (302,'BuyNotOverOrdQty',0,'采购入库不允许超出订单数量；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (303,'SaleMustImportOrd',0,'销售出库必须引用销售订单;0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (304,'SaleNotOverOrdQty',0,'销售出库不允许超出订单数量；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (305,'AllotMustImportReq',0,'同价调拨单必须引用调拨申请单；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (306,'AllotPriceMustImprotReq',0,'变价调拨单必须引用调拨申请单；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (307,'AllotWithInspect',0,'调拨单启用验货流程；0=不选 1=勾选');
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (308,'BuyBackMustImportBuy',0,'采购退货必须引用原采购单；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (309,'BuyBackNotOverBuyQty',0,'采购退货不允许超出原采购数量；0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (310,'SaleBackMustImportSale',0,'销售退货必须引用原销售单;0=不选 1=勾选');
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (311,'SaleBackNotOverSaleQty',0,'销售退货不允许超出原销售数量；0=不选 1=勾选');
END

IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_SysCfg]') AND name = N'IX_SS_SysCfg_CfgValue') 
	DROP INDEX IX_SS_SysCfg_CfgValue ON SS_SysCfg
  
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
            INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='SS_SysCfg' AND a.Name='CfgValue' AND c.name = 'tinyint')
    ALTER TABLE SS_SysCfg ALTER COLUMN CfgValue INT NOT NULL

IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 102)
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (102,'IsNegative',0,'允许负库存；0=不允许 1=允许');

IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 105)
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (105,'AutoDayPaid',0,'自动日结；0=不启用 1=启用');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 106)
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (106,'DayPaidTime',1900000,'自动日结时间');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 107)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (107,'NotAllowNegativeTotal',0,'库存金额不允许为负；0=不启用 1=启用');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 108)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (108,'ElyDeptStrictMatch',0,'单据上经手人和部门严格对应；0=不启用 1=启用');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 109)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (109,'SerialNoMgt',0,'启用序列号管理；0=不启用 1=启用');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 215)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (215,'AutoSavePricePlan',0,'自动保存价格批量调整方案；0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 216)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (216,'OverAllowSaveSale',0,'超过对账期允许保存销售草稿；0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 217)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (217,'OverAllowPostSale',0,'超过对账期允许销售单据过账；0=不选 1=勾选');
    
IF EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 105 AND CfgValue = 0) AND EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 106 AND CfgValue = 100000) 
    UPDATE SS_SysCfg SET CfgValue = 1900000 WHERE ID = 106
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 301)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (301,'BuyMustImportOrd',0,'采购入库必须引用采购订单；0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 302)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (302,'BuyNotOverOrdQty',0,'采购入库不允许超出订单数量；0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 303)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (303,'SaleMustImportOrd',0,'销售出库必须引用销售订单;0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 304)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (304,'SaleNotOverOrdQty',0,'销售出库不允许超出订单数量；0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 305)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (305,'AllotMustImportReq',0,'同价调拨单必须引用调拨申请单；0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 306)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (306,'AllotPriceMustImprotReq',0,'变价调拨单必须引用调拨申请单；0=不选 1=勾选');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 307)
	BEGIN
		INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (307,'AllotWithInspect',0,'调拨单启用验货流程；0=不选 1=勾选');
		IF EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 218 AND CfgName = 'AllotWithInspect')
			BEGIN
				UPDATE dbo.SS_SysCfg SET CfgValue = (SELECT CfgValue FROM SS_SysCfg WHERE ID = 218 AND CfgName = 'AllotWithInspect') WHERE ID = 307		
				DELETE FROM dbo.SS_SysCfg WHERE ID = 218 AND CfgName = 'AllotWithInspect'
			END
    END
    
--录单时允许打印
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 219)
BEGIN
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (219,'newbillprint',0,'录单时允许打印；0=不选 1=勾选');
END     
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 110)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (110,'AutoGoodsName',0,'自动生成商品名称；0=不启用 1=启用');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 111)
	INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (111,'ReportSum',0,'报表统计合计值；0=不启用 1=启用');

IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 112)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (112,'CostMethod',1,'成本算法；1=移动加权 2=手工指定 3=按商品配置'); 

IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 308)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (308,'BuyBackMustImportBuy',0,'采购退货必须引用原采购单；0=不选 1=勾选');

IF EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 308 AND CfgName = 'BuyRetMustImportBuy')
	UPDATE dbo.SS_SysCfg SET CfgName = 'BuyBackMustImportBuy' WHERE ID = 308
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 309)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (309,'BuyBackNotOverBuyQty',0,'采购退货不允许超出原采购数量；0=不选 1=勾选');
    
IF EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 309 AND CfgName = 'BuyRetNotOverBuyQty')
	UPDATE dbo.SS_SysCfg SET CfgName = 'BuyBackNotOverBuyQty' WHERE ID = 309
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 310)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (310,'SaleBackMustImportSale',0,'销售退货必须引用原销售单;0=不选 1=勾选');
    
IF EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 310 AND CfgName = 'SaleRetMustImportSale')
	UPDATE dbo.SS_SysCfg SET CfgName = 'SaleBackMustImportSale' WHERE ID = 310
	
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 311)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (311,'SaleBackNotOverSaleQty',0,'销售退货不允许超出原销售数量；0=不选 1=勾选');
 
/*这个配置表是分号段配置的100-200  200-300 300以上*/  
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 113)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (113,'UseBtypeCode',1,'启用往来单位商品编号；0=不启用 1=启用');
    
IF NOT EXISTS (SELECT 1 FROM SS_SysCfg WHERE ID = 114)
    INSERT INTO [SS_SysCfg] ([ID],[CfgName],[CfgValue],[Remark]) values (114,'UsePtypeQuery',0,'启用商品开单模糊查询；0=不启用 1=启用');    

GO






/*====================== TABLE: [SS_WebMenu] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_WebMenu]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_WebMenu]
(
    [MenuID] [int] NOT NULL,
    [MenuName] [varchar](30) NOT NULL,
    [Caption] [varchar](30) NOT NULL,
    [ParID] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_Lvl] DEFAULT (0),
    [IsRoot] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_IsRoot] DEFAULT (0),
    [OrderID] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_OrderID] DEFAULT (1),
    [HotKey] [varchar](50) NOT NULL CONSTRAINT [DF_SS_WebMenu_HotKey] DEFAULT '',
    [WebURL] [varchar](100) NOT NULL CONSTRAINT [DF_SS_WebMenu_WebURL] DEFAULT '',
    [Stt] [bit] NOT NULL CONSTRAINT [DF_SS_WebMenu_Stt] DEFAULT (1),
    [IsGroup] bit NOT NULL DEFAULT(0),
    CONSTRAINT [PK_SS_WebMenu] PRIMARY KEY CLUSTERED ([MenuID])
)
END
IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_WebMenu]') AND name = N'IX_SS_WebMenu_OrderID') 
DROP INDEX [IX_SS_WebMenu_OrderID] ON [SS_WebMenu]; 
CREATE  INDEX IX_SS_WebMenu_OrderID on SS_WebMenu ([OrderID]) WITH (FILLFACTOR = 90);
 
IF  EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_WebMenu]') AND name = N'IX_SS_WebMenu_ParID') 
DROP INDEX [IX_SS_WebMenu_ParID] ON [SS_WebMenu]; 
CREATE  INDEX IX_SS_WebMenu_ParID on SS_WebMenu ([ParID]) WITH (FILLFACTOR = 90);

	TRUNCATE TABLE [SS_WebMenu]
	
	---常用功能4000 "4999这个MenuID不能使用，在程序中被帮助中心占用"
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (4000,'LIMIT_COMMON','常用功能',0,1,1,0,'',1,'');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (4001,'LIMIT_COMMON_DRIFT','业务草稿',4000,2,0,10,'',1,'~/Report/Draft/DraftBill.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (4002,'LIMIT_COMMON_POSTM','经营历程',4000,2,0,20,'',1,'~/Report/PostBill.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4004,'Limit_SHZX','单据审核中心',4000,2,0,21,'',1,'~/Report/Draft/BillAuditCenter.gspx');
	INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (4003,'LIMIT_START','导航图',4000,2,0,30,'',1,'~/Start.gspx');
	
	
	
	
	
	---销售 1000
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1000,'LIMIT_SALE','销售管理',0,1,1,10,'',1,'');
	
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1030,'LIMIT_SALE_ORDERMM','销售订单管理',1000,2,1,10,'',1,'');	
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1001,'LIMIT_SALE_ORDERBILL','销售订单',1030,3,0,10,'',1,'~/Bill/Sale/SaleOrderBill.gspx');	
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1002,'LIMIT_SALE_ORDERM','销售订单管理',1030,3,0,20,'',1,'~/Report/Sale/SaleOrderm.gspx');
			
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1040,'LIMIT_SALE_BILLM','销售业务管理',1000,2,1,20,'',1,'');	
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1003,'LIMIT_SALE_BILL','销售出库单',1040,3,0,10,'',1,'~/Bill/Sale/SaleBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1004,'LIMIT_SALE_BACKBILL','销售退货单',1040,3,0,20,'',1,'~/Bill/Sale/SaleBackBill.gspx');
			
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1005,'LIMIT_SALE_R','销售报表',1000,2,1,50,'',1,'');  
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1006,'LIMIT_SALE_RGOODSYMD','销售订单汇总查询',1005,3,0,10,'',1,'~/Report/Sale/SaleOrderSummary.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1007,'LIMIT_SALE_RORDERBILL','销售订单明细查询',1005,3,0,20,'',1,'~/Report/Sale/SaleOrderDetail.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) VALUES (1008,'LIMIT_SALE_RGOODS','销售汇总统计',1005,3,0,30,'',1,'~/Report/Sale/SaleSummary.gspx',1);
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1009,'LIMIT_SALE_RBTYPEBACK','销售明细查询',1005,3,0,40,'',1,'~/Report/Sale/SaleDetailsSearch.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1010,'LIMIT_SALE_RGOODSSUM','销售退货统计',1005,3,0,50,'',1,'~/Report/Sale/SaleBackReport.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1011,'LIMIT_SALE_RGOODSUNSALABLE','滞销商品查询',1005,3,0,60,'',1,'~/Report/Sale/UnsalableGoods.gspx');
	
	 --会员管理5000		
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5000,'LIMIT_VIP','会员管理',0,1,1,20,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5001,'LIMIT_VIP_ADD','新增会员卡',5000,2,0,10,'',1,'~/Report/Vip/VipCardEdit.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5002,'LIMIT_VIP_TYPE_ADD','会员卡类型设置',5000,2,0,20,'',1,'~/Report/Vip/VipCardTypeList.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5003,'LIMIT_VIP_MANAGE','会员卡管理',5000,2,0,30,'',1,'~/Report/Vip/VipCardList.gspx');    
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5004,'LIMIT_VIP_MANAGE','积分兑换单',5000,2,0,40,'',1,'~/Bill/Vip/ExchangeBill.gspx');        
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5005,'LIMIT_VIP_MANAGE','会员消费统计',5000,2,0,50,'',1,'~/Report/Vip/VipConsumSummary.gspx');        
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5006,'LIMIT_VIP_MANAGE','会员消费明细',5000,2,0,60,'',1,'~/Report/Vip/VipConsumDetail.gspx');   
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5009,'LIMIT_VIP_CHARGE','会员充值单',5000,2,0,45,'',1,'~/Bill/Vip/VipChargeBill.gspx');   
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (5008,'LIMIT_VIP_CHARGEQUERY','会员充值查询',5000,2,0,65,'',1,'~/Report/Vip/VipChargeQuery.gspx');       
    
        
    
    --采购1500
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1500,'LIMIT_BUY','采购管理',0,1,1,30,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1520,'LIMIT_BUY_ORDERMM','采购订单管理',1500,2,1,10,'',1,'~/Report/Buy/BuyOrderSummary.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1502,'LIMIT_BUY_ORDERBILL','采购订单',1520,3,0,10,'',1,'~/Bill/Buy/BuyOrderBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1503,'LIMIT_BUY_ORDERM','采购订单管理',1520,3,0,20,'',1,'~/Report/Buy/BuyOrderm.gspx');
			
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1530,'LIMIT_BUY_BILLM','采购业务管理',1500,2,1,20,'',1,'~/Report/Buy/BuyOrderSummary.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1501,'LIMIT_BUY_BILL','采购入库单',1530,3,0,10,'',1,'~/Bill/Buy/BuyBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1504,'LIMIT_BUY_BACKBILL','采购退货单',1530,3,0,20,'',1,'~/Bill/Buy/BuyBackBill.gspx');
			
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1505,'LIMIT_BUY_R','采购报表',1500,2,1,50,'',1,''); 
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1511,'LIMIT_BUY_RORDERSUM','采购订单汇总查询',1505,3,0,10,'',1,'~/Report/Buy/BuyOrderSummary.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1510,'LIMIT_BUY_RDETAILQUERY','采购订单明细查询',1505,3,0,20,'',1,'~/Report/Buy/BuyOrderDetailQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) VALUES (1508,'LIMIT_BUY_SUMMARYBILL','采购汇总统计',1505,3,0,30,'',1,'~/Report/Buy/BuySummary.gspx',1);
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1509,'LIMIT_BUY_DETAILBILL','采购明细查询',1505,3,0,40,'',1,'~/Report/Buy/BuyDetailsSearch.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1506,'LIMIT_BUY_RBUYBACK','采购退货统计',1505,3,0,50,'',1,'~/Report/Buy/BuyBackReport.gspx');
			
			
			
			
    
    
    
    ---库存 2000
    
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2000,'LIMIT_STOCK','仓储管理',0,1,1,40,'',1,'');
    
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2020,'LIMIT_STOCK_ALLOT','调拨管理',2000,2,1,10,'',1,'~/Bill/Stock/AllotBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2021,'LIMIT_STOCK_ALLOTAPPLY','调拨申请单',2020,3,0,10,'',1,'~/Bill/Stock/AllotApplyBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2001,'LIMIT_STOCK_ALLOTBILL','同价调拨单',2020,3,0,11,'',1,'~/Bill/Stock/AllotBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2022,'LIMIT_STOCK_PRICEALLOTBILL','变价调拨单',2020,3,0,12,'',1,'~/Bill/Stock/PriceAllotBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2023,'LIMIT_STOCK_ALLOTM','调拨申请管理',2020,3,0,13,'',1,'~/Report/Stock/StockAllotM.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2024,'LIMIT_STOCK_ALLOTMCHECK','调拨验收',2020,3,0,14,'',1,'~/Report/Stock/StockAllotCheck.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2002,'LIMIT_STOCK_ADJUST','调价单',2000,2,0,20,'',1,'~/Bill/Stock/AdjustPriceBill.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2003,'LIMIT_STOCK_OTHERIN','其他入库单',2000,2,0,30,'',1,'~/Bill/Stock/OtherInBill.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2004,'LIMIT_STOCK_OTHEROUT','其他出库单',2000,2,0,40,'',1,'~/Bill/Stock/OtherOutBill.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2030,'LIMIT_STOCK_DISMANTLE','生产拆装单',2000,2,0,45,'',1,'~/Bill/Stock/DismantleBill.gspx');
		
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2018,'LIMIT_STOCK_M','盘点管理',2000,2,1,50,'',1,'');  
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2005,'LIMIT_STOCK_BSBILL','报损单',2018,3,0,5,'',1,'~/Bill/Stock/MinusStockBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2006,'LIMIT_STOCK_BYBILL','报溢单',2018,3,0,6,'',1,'~/Bill/Stock/PlusStockBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2007,'LIMIT_STOCK_PDBILL','库存盘点',2018,3,0,7,'',1,'~/Report/Stock/StockCheck.gspx');
		
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2008,'LIMIT_STOCK_ADWHSPT','货位及属性调整',2000,2,0,60,'',1,'~/Report/Stock/AdjustWhsPt.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2032,'LIMIT_STOCK_INOUTCODECHECK','出入库条码校验',2000,2,0,61,'',1,'~/Report/Stock/BarCodeVerify.gspx');
		
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2009,'LIMIT_STOCK_R','库存报表',2000,2,1,70,'',1,'');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2010,'LIMIT_STOCK_RSUM','库存状况表',2009,3,0,1,'',1,'~/Report/Stock/StockSummary.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2031,'LIMIT_STOCK_RVirtual','虚拟库存查询',2009,3,0,2,'',1,'~/Report/Stock/VirtualStock.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2011,'LIMIT_STOCK_RGOODSD','存货明细账',2009,3,0,3,'',1,'~/Report/Stock/RGoodSD.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2012,'LIMIT_STOCK_RDIS','出入库汇总查询',2009,3,0,4,'',1,'~/Report/Stock/InOutStockQuery.gspx');  
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2014,'LIMIT_STOCK_DETAIL','出入库单据明细',2009,3,0,5,'',1,'~/Report/Stock/InOutDetailSearch.gspx');  
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2013,'LIMIT_STOCK_JXCSUM','进销存汇总表',2009,3,0,6,'',1,'~/Report/Stock/JXCSumQuery.gspx');   
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],[IsGroup]) VALUES (2025,'LIMIT_STOCK_XLHKC','序列号库存查询',2009,3,0,7,'',1,'~/Report/Stock/SeriesNumStockQuery.gspx',1);   
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2026,'LIMIT_STOCK_XLHGZ','序列号跟踪查询',2009,3,0,8,'',1,'~/Report/Stock/SeriesNumStalkQuery.gspx');   
       INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2015,'LIMIT_STOCK_W','库存报警',2000,2,1,70,'',1,'');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2016,'LIMIT_STOCK_WUPDOWNSET','库存上下限设置',2015,3,0,1,'',1,'~/Report/Stock/StockLimitSettings.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2017,'LIMIT_STOCK_WUP','库存上限报警',2015,3,0,2,'',1,'~/Report/Stock/StockUBWarn.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2019,'LIMIT_STOCK_WDOWN','库存下限报警',2015,3,0,3,'',1,'~/Report/Stock/StockLBWarn.gspx'); 
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],[IsGroup]) VALUES (2027,'LIMIT_STOCK_BSTOCK','批次库存查询',2009,3,0,12,'',1,'~/Report/Stock/BatchStockQuery.gspx',1);  
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2028,'LIMIT_STOCK_BTRACK','批次跟踪查询',2009,3,0,16,'',1,'~/Report/Stock/BatchTrack.gspx');  
              
       
	---账务管理 3500
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3500,'LIMIT_PAY','账务管理',0,1,1,50,'',1,'');
     
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3501,'LIMIT_PAY_ZW','账务处理',3500,2,1,10,'',1,'');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3502,'LIMIT_PAY_FKBILL','付款单',3501,3,0,10,'',1,'~/Bill/Accounts/PaymentBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3503,'LIMIT_PAY_SKBILL','收款单',3501,3,0,20,'',1,'~/Bill/Accounts/GatheringBill.gspx');   
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3505,'LIMIT_PAY_CASHBILL','现金费用单',3501,3,0,30,'',1,'~/Bill/Accounts/CashBill.gspx');  
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3506,'LIMIT_PAY_YBFYBILL','一般费用单',3501,3,0,40,'',1,'~/Bill/Accounts/YBFYBill.gspx'); 
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3507,'LIMIT_PAY_OTHERSR','其他收入单',3501,3,0,50,'',1,'~/Bill/Accounts/OtherMoneyBill.gspx');	
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3508,'LIMIT_PAY_TXZCZZ','转款单',3501,3,0,60,'',1,'~/Bill/Accounts/TransfersBill.gspx');
		
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3509,'LIMIT_PAYADJUST','调账业务',3500,2,1,20,'',1,'');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3510,'LIMIT_PAYADJUST_ARZJ','应收增加单',3509,3,0,1,'',1,'~/Bill/Accounts/ARAddBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3535,'LIMIT_PAYADJUST_ARJS','应收减少单',3509,3,0,2,'',1,'~/Bill/Accounts/ARMinusBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3511,'LIMIT_PAYADJUST_APZJ','应付增加单',3509,3,0,3,'',1,'~/Bill/Accounts/APAddBill.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3512,'LIMIT_PAYADJUST_APJS','应付减少单',3509,3,0,4,'',1,'~/Bill/Accounts/APMinusBill.gspx');
				
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3520,'LIMIT_PAYBTYPER','往来报表',3500,2,1,30,'',1,'');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3530,'LIMIT_PAYCW_ARAP','单位应收应付',3520,3,0,10,'',1,'~/Report/Accounts/ARAPSummay.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3515,'LIMIT_PAYABTYPE_WLZH','往来发生统计',3520,3,0,20,'',1,'~/Report/Accounts/ContactAmountStatistics.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3514,'LIMIT_PAYABTYPE_WLDZ','往来对账',3520,3,0,30,'',1,'~/Report/Accounts/WLDZQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3518,'LIMIT_PAYABTYPE_ADJS','按单结算查询',3520,3,0,40,'',1,'~/Report/Accounts/ADJSQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3521,'LIMIT_PAYBTYPER_HKTJ','回款统计',3520,3,0,50,'',1,'~/Report/Accounts/ReturnStatistics.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3549,'LIMIT_PAYCW_ARCQ','应收超期查询',3520,3,0,60,'',1,'~/Report/Accounts/ARCQQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3550,'LIMIT_PAYCW_WXCQ','微信支付对账单查询',3520,3,0,70,'',1,'~/Report/Accounts/WeiXinPayCheckQuery.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3540,'LIMIT_PAYINVOICE','发票管理',3500,2,1,40,'',1,'');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3541,'LIMIT_PAYINVOICE_SMANAGE','销售发票管理',3540,3,0,10,'',1,'~/Report/Accounts/SaleInvoiceM.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3542,'LIMIT_PAYINVOICE_SSUM','销售开票统计',3540,3,0,11,'',1,'~/Report/Accounts/SaleInvoiceStatistical.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3543,'LIMIT_PAYINVOICE_SSERCH','销售单据开票情况查询',3540,3,0,12,'',1,'~/Report/Sale/SaleInvoiceQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3544,'LIMIT_PAYINVOICE_BMANAGE','采购发票管理',3540,3,0,16,'',1,'~/Report/Accounts/BuyInvoiceM.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3545,'LIMIT_PAYINVOICE_BSUM','采购开票统计',3540,3,0,20,'',1,'~/Report/Accounts/BuyInvoiceStatistical.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3546,'LIMIT_PAYINVOICE_BSERCH','采购单据开票情况查询',3540,3,0,25,'',1,'~/Report/Buy/BuyInvoiceQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3547,'LIMIT_PAYINVOICE_SALE','销售发票',3540,3,0,5,'',1,'~/Bill/Sale/SaleInvoice.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) values (3548,'LIMIT_PAYINVOICE_BUY','采购发票',3540,3,0,14,'',1,'~/Bill/Buy/BuyInvoice.gspx',1);
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3528,'LIMIT_PAYCW','账务报表',3500,2,1,50,'',1,'');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3519,'LIMIT_PAYABTYPE_SFMXCX','项目明细查询',3528,3,0,10,'',1,'~/Report/Accounts/FinanceDetailsQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3537,'LIMIT_PAYCW_ROTHERSUM','项目历史对比',3528,3,0,20,'',1,'~/Report/Accounts/FinanceHistory.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) values (3538,'LIMIT_PAYCW_BG','现金银行查询',3528,3,0,30,'',1,'~/Report/Accounts/CashBankQuery.gspx',1);
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) values (3539,'LIMIT_PAYCW_XJYHBB','现金银行报表',3528,3,0,90,'',1,'~/Report/Accounts/CashBankReport.gspx',1);
			
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) values (3531,'LIMIT_PAYCW_FYZC','费用支出统计',3528,3,0,40,'',1,'~/Report/Accounts/ExpenditureStatistics.gspx',1);
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3532,'LIMIT_PAYCW_FYFB','费用分布表',3528,3,0,50,'',1,'~/Report/Accounts/MoneyDistributedQuery.gspx');
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) values (3536,'LIMIT_PAYCW_ROTHERSUM','其他收入统计',3528,3,0,60,'',1,'~/Report/Accounts/OtherMoneySummary.gspx',1);
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL],IsGroup) values (3534,'LIMIT_PAYCW_JYLR','经营利润表',3528,3,0,70,'',1,'~/Report/Accounts/OperatingProfit.gspx',1);
			INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3529,'LIMIT_PAYCW_BG','创利分类统计',3528,3,0,80,'',1,'~/Report/Accounts/EtypeProfitQuery.gspx');

   ---基础资料  2500
    
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2500,'LIMIT_BASE','基础资料',0,1,1,60,'',1,'');
    
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2501,'Limit_P','商品管理',2500,2,1,10,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2507,'LIMIT_P_INFO','商品信息',2501,3,0,1,'',1,'~/Base/PtypeList.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2508,'Limit_P_SX','属性值设置',2501,3,0,2,'',1,'~/Base/PtypeAttribute.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2509,'Limit_P_GSX','属性组管理',2501,3,0,3,'',1,'~/Base/AttributeGroupList.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2510,'Limit_P_MST','往来单位商品编号',2501,3,0,4,'',1,'~/Base/MultPtypeCodeList.gspx');
	INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2521,'Limit_P_PT','生产模板',2501,3,0,5,'',1,'~/Base/ProductionTemplate.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2524,'Limit_P_PCP','商品条码打印',2501,3,0,6,'',1,'~/Base/PtypeCodePrint.gspx');	

   	INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2530,'LIMIT_SALE_JGGL','价格管理',2500,2,1,20,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1031,'LIMIT_SALE_WJGL','物价管理',2530,3,0,10,'',1,'~/Report/Sale/GoodsPrice.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (1032,'LIMIT_SALE_JGGZ','价格跟踪',2530,3,0,20,'',1,'~/Report/Sale/PriceTrack.gspx'); 
   
   INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) VALUES (2531,'LIMIT_SALE_PRICESET','价格设置',2500,2,0,21,'',1,'~/Base/PriceNameSet.gspx');
   
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2502,'Limit_B','往来单位管理',2500,2,1,30,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2511,'LIMIT_B_INFO','地区信息',2502,3,0,1,'',1,'~/Base/AreaList.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2512,'Limit_B_SX','往来单位',2502,3,0,2,'',1,'~/Base/BtypeList.gspx');
    
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2503,'Limit_Z','组织架构管理',2500,2,1,40,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2513,'Limit_Z_GSX','部门信息',2503,3,0,1,'',1,'~/Base/DeptList.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2514,'Limit_Z_MST','职员信息',2503,3,0,2,'',1,'~/Base/EtypeList.gspx');
       
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2504,'Limit_S','仓储信息管理',2500,2,1,50,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2515,'Limit_S_GSX','存货仓库',2504,3,0,1,'',1,'~/Base/KtypeList.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2516,'Limit_S_MST','货位信息',2504,3,0,2,'',1,'~/Base/KtypePtList.gspx');
    
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2505,'Limit_C','财务项目',2500,2,0,60,'',1,'~/Base/FinanceList.gspx');
    
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2506,'Limit_I','期初数据录入',2500,2,1,70,'',1,'');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2517,'Limit_I_SSP','期初库存商品',2506,3,0,1,'',1,'~/OpeningData/OpeningStock.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2518,'Limit_I_SARAP','期初应收应付',2506,3,0,2,'',1,'~/OpeningData/OpeningArap.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2519,'Limit_I_SCBANK','期初现金银行',2506,3,0,4,'',1,'~/OpeningData/OpeningFinance.gspx');
		INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2520,'Limit_I_SIPAY','期初收入支出',2506,3,0,5,'',1,'~/OpeningData/OpeningFinance.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2522,'Limit_D_P','自定义基础资料',2500,2,0,80,'',1,'~/Base/CustomBaseList.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (2523,'Limit_D_PS','基础资料自定义字段配置',2500,2,0,81,'',1,'~/Base/BaseInfoCustomItem.gspx');
    
    ---系统管理 3000
    
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3000,'LIMIT_SYSTEM','系统管理',0,1,1,70,'',1,'');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3001,'Limit_SS','系统启用',3000,2,1,1,'',1,'');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3002,'Limit_JXC','进销存设置',3000,2,0,2,'',1,'~/SysSet/JXCSet.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3011,'Limit_SHSZ','单据审核设置',3000,2,0,3,'',1,'~/SysSet/AuditSet.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3004,'Limit_UL','用户权限设置',3000,2,1,4,'',1,'');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3005,'LIMIT_SS_START','系统开账',3001,3,0,1,'',1,'~/SysSet/OpenAccount.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3006,'LIMIT_SS_REBUILD','系统重建',3001,3,0,2,'',1,'~/SysSet/SysRebuild.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3007,'Limit_UL_USER','操作员管理',3004,3,0,1,'',1,'~/SysSet/OperatorList.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3008,'Limit_UL_GUSER','用户组权限',3004,3,0,2,'',1,'~/SysSet/RoleList.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3010,'Limit_LoginLimit','登录限制设置',3004,3,0,3,'',1,'~/SysSet/MacAddrList.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3009,'Limit_MB','月结存',3000,2,0,7,'',1,'~/SysSet/MonthBalance.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3012,'Limit_SYSINFO','关于软件',3000,2,0,8,'',1,'~/SysSet/AboutSoft.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3013,'Limit_CODERULE','组合条码规则设置',3000,2,0,6,'',1,'~/SysSet/BarcodeRuleSet.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3014,'Limit_WXPAY','微信支付设置',3000,2,0,5,'',1,'~/SysSet/WXPaySet.gspx');
    INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (3015,'Limit_LoginD9App','手机版',3000,2,0,15,'',1,'');
    --INSERT INTO dbo.SS_WebMenu( MenuID ,MenuName ,Caption ,ParID ,Lvl ,IsRoot ,OrderID ,HotKey ,WebURL ,Stt ,IsGroup) VALUES  (3015 ,'Limit_Registry','账套激活' ,3000 , 2 ,0,8,'' ,'~/Master/RegistryInfoBox.gspx' ,1 ,0)
 
 
  
	--网店管理 4500
   INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4500,'LIMIT_SYSTEM','网店管理',0,1,1,80,'',1,'');
   --INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4501,'LIMIT_OSG_REG','网店业务绑定',4500,2,0,10,'',1,'~/OSMgt/SignUp.gspx');
   INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4502,'LIMIT_OSG_INIT','基本信息同步',4500,2,1,20,'',1,'');
   
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4510,'LIMIT_OSG_INIT_GOODS','商品信息手工同步',4502,3,0,10,'',1,'~/OSMgt/PtypeUpLoadList.gspx');
   
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4517,'LIMIT_OSG_INIT_STOCK','商品库存手工同步',4502,3,0,20,'',1,'~/OSMgt/SyncStockError.gspx');
	  --INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4511,'LIMIT_OSG_INIT_STOCK','仓库货位同步',4502,3,0,20,'',1,'~/OSMgt/KtypeUpLoadList.gspx');
	  --INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4513,'LIMIT_OSG_INIT_EMP','职员信息同步',4502,3,0,30,'',1,'~/OSMgt/OperatorUploadList.gspx');
	  --INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4514,'LIMIT_OSG_INIT_WLGS','物流公司下载',4502,3,0,40,'',1,'~/OSMgt/LogistBtypeList.gspx');
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4515,'LIMIT_OSG_PTYPE_DYGX','商品对应关系设置',4502,3,0,50,'',1,'~/OSMgt/PtypeRelationship.gspx');
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4516,'LIMIT_OSG_PTYPE_QTY','网店商品数量更新',4502,3,0,60,'',1,'~/OSMgt/PtypeNumberUpLoadList.gspx');
  
  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4530,'LIMIT_OSG_CONFIG','网店配置',4500,2,0,30,'',1,'~/OSMgt/OSSet.gspx');
  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4540,'LIMIT_OSG_LOGIN','网店业务处理',4500,2,0,40,'',1,'');
  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4550,'LIMIT_OSG_BILL','网店业务同步',4500,2,1,50,'',1,'');
	  
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4551,'LIMIT_OSG_ORDERMG','已处理订单下载',4550,3,0,10,'',1,'~/OSMgt/OSOrderBillList.gspx');
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4552,'LIMIT_OSG_ORDERMG','运费结算单处理',4550,3,0,20,'',1,'~/OSMgt/FreightList.gspx');
  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4560,'LIMIT_OSG_Report','网店报表',4500,2,1,60,'',1,'');
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4561,'LIMIT_OSG_ReportOrd','网店订单统计',4560,3,0,10,'',1,'~/OSMgt/OSOrderBillReport.gspx');
	  INSERT INTO [SS_WebMenu] ([MenuID],[MenuName],[Caption],[ParID],[Lvl],[IsRoot],[OrderID],[HotKey],[Stt],[WebURL]) values (4562,'LIMIT_OSG_ReportRet','退换货业务统计',4560,3,0,20,'',1,'~/OSMgt/BackChangeStatistics.gspx');
     



/*====================== TABLE: [SS_WebMenu_Ext_Ext] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_WebMenu_Ext]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_WebMenu_Ext]
(
    [MenuID] [int] NOT NULL,
    [MenuName] [varchar](30) NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_MenuName] DEFAULT '',
    [Caption] [varchar](30) NOT NULL,
    [ParID] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_ParID] DEFAULT (0),
    [Lvl] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_Lvl] DEFAULT (0),
    [IsRoot] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_IsRoot] DEFAULT (0),
    [OrderID] [int] NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_OrderID] DEFAULT (1),
    [HotKey] [varchar](50) NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_HotKey] DEFAULT '',
    [WebURL] [varchar](100) NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_WebURL] DEFAULT '',
    [Stt] [bit] NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_Stt] DEFAULT (1),
    [IsGroup] bit NOT NULL DEFAULT(0),
    [ExtType] TINYINT NOT NULL,
    [ExtID] INT NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_ExtID] DEFAULT (0),
    [PageType] TINYINT NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_PageType] DEFAULT (1),
    CONSTRAINT [PK_SS_WebMenu_Ext] PRIMARY KEY CLUSTERED ([MenuID])
)
END
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='SS_WebMenu_Ext' AND a.Name='ExtID')
	ALTER TABLE SS_WebMenu_Ext ADD ExtID INT NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_ExtID] DEFAULT (0)
 
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='SS_WebMenu_Ext' AND a.Name='ViewJurID')
	ALTER TABLE SS_WebMenu_Ext DROP COLUMN ViewJurID

IF NOT EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'SS_WebMenu_Ext' AND so.xtype = 'D' AND so.name = 'DF_SS_WebMenu_Ext_MenuName')
	ALTER TABLE SS_WebMenu_Ext ADD CONSTRAINT [DF_SS_WebMenu_Ext_MenuName] DEFAULT '' FOR MenuName
 
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id WHERE b.Name='SS_WebMenu_Ext' AND a.Name='PageType')
	ALTER TABLE SS_WebMenu_Ext ADD [PageType] TINYINT NOT NULL CONSTRAINT [DF_SS_WebMenu_Ext_PageType] DEFAULT (1)



/*====================== TABLE: [SS_Whs_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_Whs_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_Whs_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [WhsID] [int] NOT NULL,
    [WhsTypeID] [int] NOT NULL,
    [Flag] [bit] NOT NULL CONSTRAINT [DF_SS_Whs_Jur_Flag] DEFAULT (0),
    CONSTRAINT [PK_SS_Whs_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Whs_Jur]') AND name = N'IXU_SS_Whs_Jur_RoleID') 
	CREATE  INDEX IXU_SS_Whs_Jur_RoleID on SS_Whs_Jur ([RoleID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[SS_Whs_Jur]') AND name = N'IX_SS_Whs_Jur_WhsID') 
	CREATE  INDEX IX_SS_Whs_Jur_WhsID on SS_Whs_Jur ([WhsID]) WITH (FILLFACTOR = 90);	

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_Whs_Jur' AND a.Name='WhsTypeID')
BEGIN
	ALTER TABLE SS_Whs_Jur ADD WhsTypeID INT NULL
	EXEC sp_executesql N'UPDATE a SET a.WhsTypeID = b.WhsTypeID FROM 
						 SS_Whs_Jur a INNER JOIN BD_Whs b ON a.WhsID = b.WhsID WHERE a.WhsTypeID IS NULL'
	ALTER TABLE SS_Whs_Jur ALTER COLUMN WhsTypeID INT NOT NULL
END




/*====================== TABLE: [SS_WhsType_Jur] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[SS_WhsType_Jur]') AND type in (N'U'))
BEGIN
CREATE TABLE [SS_WhsType_Jur]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleID] [int] NOT NULL,
    [WhsTypeID] [int] NOT NULL,
    [LimitTag] TINYINT NOT NULL CONSTRAINT [DF_SS_WhsType_Jur_LimitTag] DEFAULT (0),
    CONSTRAINT [PK_SS_WhsType_Jur] PRIMARY KEY NONCLUSTERED ([ID])
)
END

IF NOT EXISTS(SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='SS_WhsType_Jur' AND a.Name='LimitTag')
BEGIN
	ALTER TABLE [SS_WhsType_Jur] ADD LimitTag TINYINT  NOT NULL CONSTRAINT [DF_SS_WhsType_Jur_LimitTag] DEFAULT (0)
END



SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON


IF NOT EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[SYS_SysData]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [dbo].[SYS_SysData](
		[SubNo] NUMERIC(10,0) NOT NULL Primary KEY,
		[SubName] [varchar](30) COLLATE Chinese_PRC_CI_AS NULL,
		[SubValue] [varchar](5000) COLLATE Chinese_PRC_CI_AS NULL,
		[SubComment] [varchar](500) COLLATE Chinese_PRC_CI_AS NULL
	) ON [PRIMARY]
	
	-- ********	处理 SysData	********
	DELETE FROM SYS_SysData
	INSERT INTO SYS_SysData (SubNo,SubName,SubValue,SubComment) VALUES (1,'writedoglog','1','填写狗日志')

END
GO

--记录升级日期
IF NOT EXISTS(SELECT TOP 1 1 FROM SYS_SysData WHERE SubName = 'packdatetime')
BEGIN
	INSERT INTO SYS_SysData (SubNo,SubName,SubValue,SubComment) VALUES (2,'packdatetime','','升级的时候记录升级日期')
END
GO



/*====================== TABLE: [SS_SysCfg] ======================*/
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[Sysdefine]') AND type in (N'U'))
BEGIN
CREATE TABLE Sysdefine
(
    [ID] [int] NOT NULL,
    [CfgKey] varchar(100) NOT NULL,
    [CfgValue]  varchar(100) NOT NULL,
    CONSTRAINT [PK_sysdefine] PRIMARY KEY CLUSTERED ([ID])
)
END

IF NOT EXISTS (SELECT 1 FROM [Sysdefine] WHERE ID = 10)
	INSERT INTO [Sysdefine]([ID],[CfgKey],[CfgValue]) values (10,'firsttime','');




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[VS_CentAdjust]') AND type in (N'U'))
BEGIN
CREATE TABLE [VS_CentAdjust]
(
    BillNo INT IDENTITY(1,1) NOT NULL,
	VipCardID INT NOT NULL,
    AdjustCent NUMERIC(10, 0) NULL,
    Remark VARCHAR(256) NULL,
    Creator [int] NOT NULL,
    CreateTime [datetime] NOT NULL,
    CONSTRAINT [PK_VS_CentAdjust] PRIMARY KEY NONCLUSTERED (BillNo)
)
END



IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_CentAdjust]') AND name = N'IX_VS_CentAdjust_VipCardID') 
	CREATE INDEX IX_VS_CentAdjust_VipCardID on dbo.VS_CentAdjust ([VipCardID]) WITH (FILLFACTOR = 90);




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[VS_GoodsScore]') AND type in (N'U'))
BEGIN
CREATE TABLE [VS_GoodsScore]
(
    ID INT IDENTITY(1,1) NOT NULL,
	VipCardTypeID INT NOT NULL,
	GoodsID INT NOT NULL,
	Total NUMERIC(20, 8) NULL,
    Cent NUMERIC(10, 0) NULL,
    CONSTRAINT [PK_VS_GoodsScore] PRIMARY KEY NONCLUSTERED (ID)
)
END



IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_GoodsScore]') AND name = N'IX_VS_GoodsScore_VipCardTypeID') 
	CREATE INDEX IX_VS_GoodsScore_VipCardTypeID on dbo.VS_GoodsScore ([VipCardTypeID]) WITH (FILLFACTOR = 90);



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

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from sys.objects where object_id = object_id(N'[dbo].[VS_VipCard]') and type IN(N'U'))
BEGIN
	CREATE TABLE [VS_VipCard](
		[VipCardID] [int] IDENTITY(1,1) NOT NULL,
		[VipCardTypeID] [int] NULL,
		[VipCardNO] [varchar](25)  NULL,
		[VipName] VARCHAR(50) NULL,
		[CardHolder] VARCHAR(50) NULL,
		[IDNO] VARCHAR(30) NULL,
		[Sex] TINYINT NULL,
		[Birthday] [date] NULL,
		[Address] [varchar](50) NULL,
		[Tel] [varchar](20) NULL,
		[Email] VARCHAR(30) NULL,
		[CreateDate] [date] NULL,
		[EndDate] [date] NULL,
		[BTypeID] INT NOT NULL,
		[Status] TINYINT NOT NULL CONSTRAINT[DF_VS_VipCard_Status] DEFAULT (1),
		[BeginMoney] [numeric](20,8),
		[BeginCent] [numeric](10,0),
		[TotalMoney] [numeric](20,8),
		[TotalCent] [numeric](20,8),
		[CentBalance] [numeric](10,0),
		[Remark] VARCHAR(256) NULL,
		[BeginStoreMoney] [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_BeginStoreMoney] DEFAULT(0),
		[TotalStoreMoney]  [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_TotalStoreMoney] DEFAULT(0),
		[BeginExpenseMoney]  [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_BeginExpenseMoney] DEFAULT(0),
		[TotalExpenseMoney]  [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_TotalExpenseMoney] DEFAULT(0),
		[MoneyBalance]  [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_MoneyBalance] DEFAULT(0),
		CONSTRAINT [PK_VS_VipCard] PRIMARY KEY NONCLUSTERED ([VipCardID])
	)
END
GO


------------------------------------------表修改区域开始-------------------------------------------------
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='VS_VipCard' AND a.Name='BeginStoreMoney')
    ALTER TABLE VS_VipCard ADD 	[BeginStoreMoney] [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_BeginStoreMoney] DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='VS_VipCard' AND a.Name='TotalStoreMoney')
    ALTER TABLE VS_VipCard ADD 	[TotalStoreMoney] [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_TotalStoreMoney] DEFAULT(0)
      
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='VS_VipCard' AND a.Name='BeginExpenseMoney')
    ALTER TABLE VS_VipCard ADD 	[BeginExpenseMoney] [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_BeginExpenseMoney] DEFAULT(0)          
      
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='VS_VipCard' AND a.Name='TotalExpenseMoney')
    ALTER TABLE VS_VipCard ADD 	[TotalExpenseMoney] [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_TotalExpenseMoney] DEFAULT(0)
       
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='VS_VipCard' AND a.Name='MoneyBalance')
    ALTER TABLE VS_VipCard ADD 	[MoneyBalance] [numeric](20,8) NOT NULL CONSTRAINT [DF_VS_VipCard_MoneyBalance] DEFAULT(0)    
    
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipCard]') AND name = N'IX_VS_VipCard_VipCardTypeID') 
	CREATE INDEX IX_VS_VipCard_VipCardTypeID on dbo.VS_VipCard ([VipCardTypeID]) WITH (FILLFACTOR = 90);
	
------------------------------------------创建索引区域结束-----------------------------------------------




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

SET QUOTED_IDENTIFIER ON

IF NOT EXISTS(select * from sys.objects where object_id = object_id(N'[dbo].[VS_VipCardType]') and type IN(N'U'))
BEGIN
	CREATE TABLE [VS_VipCardType](
		[VipCardTypeID] [int] IDENTITY(1,1) NOT NULL,
		[TypeName] [varchar](50)  NULL,
		[Discount] NUMERIC(3,2) NULL ,
		[AutoLevelUp] BIT NULL,
		[LevelUpType] TINYINT NULL,
		[LevelUpMoney] DECIMAL(10,0)NOT NULL,
		[CentUpType] TINYINT NULL,
		[LevelUpCent] DECIMAL(10,0)NOT NULL,
		[BTypeID] INT NULL CONSTRAINT [DF_VS_VipCardType_BTypeID] DEFAULT(0),
		[IsScore] BIT NOT NULL,
		[GiveCent] DECIMAL(10,0) NOT NULL ,
		[IsPerWeek] BIT NOT NULL,
		[WeekDay] VARCHAR(7) NOT NULL,
		[IsBirthDay] BIT NOT NULL,
		[IsSpecified] BIT NOT NULL,
		[PerWeekMul] DECIMAL(5,0) NOT NULL,
		[BirthDayMul] DECIMAL(5,0) NOT NULL,
		[SpecifiedMul] DECIMAL(5,0) NOT NULL,
		[SpecifiedStartDate] DATE,
		[SpecifiedEndDate] DATE,
		[ScoreType] TINYINT NOT NULL,
		[BillTotal] [numeric](20, 8) NULL,
		[BillCent] [numeric](10, 0) NULL,
		[GoodsScoreType] TINYINT NOT NULL,
		[IsOtherGoods] BIT NOT NULL,
		[OtherTotal] [numeric](20, 8) NULL,
		[OtherCent] [numeric](10, 0) NULL,
		[IsDeduction] BIT NOT NULL,
		[DeductionCent] [numeric](10, 0) NULL,
		[DeductionTotal] [numeric](20, 8) NULL,
		[ULimitType] TINYINT NOT NULL,
		[TotolULimit] [numeric](20, 8) NULL,
		[PercentULimit] TINYINT NOT NULL,
		[Remark] VARCHAR(256) NULL,
		[IsDefault] BIT NOT NULL DEFAULT(0),
		[FinanceID] INT NOT NULL CONSTRAINT [DF_VS_VipCardType_FinanceID] DEFAULT(0),
		[IsAllPay] BIT NOT NULL CONSTRAINT [DF_VS_VipCardType_IsAllPay] DEFAULT(0),
		CONSTRAINT [PK_VS_VipCardType] PRIMARY KEY NONCLUSTERED ([VipCardTypeID])
	)
END
GO

------------------------------------------表修改区域开始-------------------------------------------------
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='VS_VipCardType' AND a.Name='FinanceID')
    ALTER TABLE VS_VipCardType ADD [FinanceID] INT NOT NULL CONSTRAINT [DF_VS_VipCardType_FinanceID] DEFAULT(0)
    
IF NOT EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id=b.object_id WHERE b.Name='VS_VipCardType' AND a.Name='IsAllPay')
    ALTER TABLE VS_VipCardType ADD [IsAllPay] BIT NOT NULL CONSTRAINT [DF_VS_VipCardType_IsAllPay] DEFAULT(0)  
    
------------------------------------------表修改区域结束-------------------------------------------------


------------------------------------------创建索引区域开始-----------------------------------------------
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipCardType]') AND name = N'IX_VS_VipCardType_BTypeID') 
	CREATE INDEX IX_VS_VipCardType_BTypeID on dbo.VS_VipCardType ([BTypeID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipCardType]') AND name = N'IX_VS_VipCardType_FinanceID') 
	CREATE INDEX IX_VS_VipCardType_FinanceID on dbo.VS_VipCardType ([FinanceID]) WITH (FILLFACTOR = 90);
------------------------------------------创建索引区域结束-----------------------------------------------




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND type in (N'U'))
BEGIN
CREATE TABLE [VS_VipChargeBill]
(
    [BillNo] [bigint] IDENTITY(1,1) NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_FinanceID] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_PayTotal] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_Privilege] DEFAULT (0),
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_PaidTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_VS_VipChargeBill_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_VS_VipChargeBill] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND name = N'IXC_VS_VipChargeBill_BillCode') 
	CREATE  INDEX IXC_VS_VipChargeBill_BillCode on VS_VipChargeBill ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND name = N'IXC_VS_VipChargeBill_BillDate') 
	CREATE  INDEX IXC_VS_VipChargeBill_BillDate on VS_VipChargeBill ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND name = N'IXC_VS_VipChargeBill_CreateTime') 
	CREATE  INDEX IXC_VS_VipChargeBill_CreateTime on VS_VipChargeBill ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND name = N'IXC_VS_VipChargeBill_PosTime') 
	CREATE  INDEX IXC_VS_VipChargeBill_PosTime on VS_VipChargeBill ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND name = N'IX_VS_VipChargeBill_DeptID') 
	CREATE  INDEX IX_VS_VipChargeBill_DeptID on VS_VipChargeBill ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND name = N'IX_VS_VipChargeBill_ElyID') 
	CREATE  INDEX IX_VS_VipChargeBill_ElyID on VS_VipChargeBill ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill]') AND name = N'IX_VS_VipChargeBill_FinanceID') 
	CREATE  INDEX IX_VS_VipChargeBill_FinanceID on VS_VipChargeBill ([FinanceID]) WITH (FILLFACTOR = 90);
   





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [VS_VipChargeBill_His]
(
    [BillNo] [bigint]  NOT NULL,
    [BillCode] [varchar](50) NOT NULL,
    [BillDate] [date] NOT NULL,
    [DeptID] [int] NOT NULL,
    [ElyID] [int] NOT NULL,
    [FinanceID] [int] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_FinanceID] DEFAULT (0),
    [PayRecTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_PayTotal] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_Privilege] DEFAULT (0),
    [PaidTotal] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_PaidTotal] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_Total] DEFAULT (0),
    [Creator] [int] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_Creator] DEFAULT (0),
    [CreateTime] [datetime] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_CreateTime] DEFAULT getdate(),
    [PosElyID] [int] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_PosElyID] DEFAULT (0),
    [PosTime] [datetime] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_PosTime] DEFAULT getdate(),
    [Summary] [varchar](256) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_Summary] DEFAULT '',
    [Description] [varchar](100) NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_Description] DEFAULT '',
    [Red] [tinyint] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_Red] DEFAULT (0),
    [IsDraft] [bit] NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_IsDraft] DEFAULT (1),
    [AuditStatus] TINYINT NOT NULL CONSTRAINT [DF_VS_VipChargeBill_His_AuditStatus] DEFAULT (0)    ,
    CONSTRAINT [PK_VS_VipChargeBill_His] PRIMARY KEY CLUSTERED ([BillNo])
)
END

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND name = N'IXC_VS_VipChargeBill_His_BillCode') 
	CREATE  INDEX IXC_VS_VipChargeBill_His_BillCode on VS_VipChargeBill_His ([BillCode]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND name = N'IXC_VS_VipChargeBill_His_BillDate') 
	CREATE  INDEX IXC_VS_VipChargeBill_His_BillDate on VS_VipChargeBill_His ([BillDate]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND name = N'IXC_VS_VipChargeBill_His_CreateTime') 
	CREATE  INDEX IXC_VS_VipChargeBill_His_CreateTime on VS_VipChargeBill_His ([CreateTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND name = N'IXC_VS_VipChargeBill_His_PosTime') 
	CREATE  INDEX IXC_VS_VipChargeBill_His_PosTime on VS_VipChargeBill_His ([PosTime]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND name = N'IX_VS_VipChargeBill_His_DeptID') 
	CREATE  INDEX IX_VS_VipChargeBill_His_DeptID on VS_VipChargeBill_His ([DeptID]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND name = N'IX_VS_VipChargeBill_His_ElyID') 
	CREATE  INDEX IX_VS_VipChargeBill_His_ElyID on VS_VipChargeBill_His ([ElyID]) WITH (FILLFACTOR = 90);
	
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeBill_His]') AND name = N'IX_VS_VipChargeBill_His_FinanceID') 
	CREATE  INDEX IX_VS_VipChargeBill_His_FinanceID on VS_VipChargeBill_His ([FinanceID]) WITH (FILLFACTOR = 90);
   





IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[VS_VipChargeDetail]') AND type in (N'U'))
BEGIN
CREATE TABLE [VS_VipChargeDetail]
(
    [DID] [bigint] IDENTITY(1,1) NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [VipCardID] [int] NOT NULL,
    [TotalBanlance] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeDetail_TotalBanlance] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeDetail_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeDetail_Privilege] DEFAULT (0),
    [Remark] [varchar](100) NULL,
    CONSTRAINT [PK_VS_VipChargeDetail] PRIMARY KEY NONCLUSTERED ([DID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeDetail]') AND name = N'IX_VS_VipChargeDetail_BillNo') 
	CREATE CLUSTERED  INDEX IX_VS_VipChargeDetail_BillNo on VS_VipChargeDetail ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeDetail]') AND name = N'IX_VS_VipChargeDetail_FinanceID') 
	CREATE  INDEX IX_VS_VipChargeDetail_FinanceID on VS_VipChargeDetail ([VipCardID]) WITH (FILLFACTOR = 90);


IF  EXISTS(
	SELECT a.Name FROM syscolumns a
	INNER JOIN sysobjects	b
	ON a.ID=b.ID
	WHERE b.Name='VS_VipChargeDetail' AND a.Name='Remark' AND a.[length] = 100
    )
BEGIN
	ALTER TABLE VS_VipChargeDetail 
	ALTER COLUMN Remark VARCHAR(256)
END

GO




IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[VS_VipChargeDetail_His]') AND type in (N'U'))
BEGIN
CREATE TABLE [VS_VipChargeDetail_His]
(
    [DID] [bigint] NOT NULL,
    [BillNo] [bigint] NOT NULL,
    [VipCardID] [int] NOT NULL,
    [TotalBanlance] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeDetail_His_TotalBanlance] DEFAULT (0),
    [Total] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeDetail_His_Total] DEFAULT (0),
    [Privilege] [decimal](20,8) NOT NULL CONSTRAINT [DF_VS_VipChargeDetail_His_Privilege] DEFAULT (0),
    [Remark] [varchar](100) NULL,
    CONSTRAINT [PK_VS_VipChargeDetail_His] PRIMARY KEY NONCLUSTERED ([DID])
)
END


IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeDetail_His]') AND name = N'IX_VS_VipChargeDetail_His_BillNo') 
	CREATE CLUSTERED  INDEX IX_VS_VipChargeDetail_His_BillNo on VS_VipChargeDetail_His ([BillNo]) WITH (FILLFACTOR = 90);

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N'[VS_VipChargeDetail_His]') AND name = N'IX_VS_VipChargeDetail_His_FinanceID') 
	CREATE  INDEX IX_VS_VipChargeDetail_His_FinanceID on VS_VipChargeDetail_His ([VipCardID]) WITH (FILLFACTOR = 90);






if NOT exists (select * from sysobjects where id = object_id(N'[webLog]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
	CREATE TABLE [webLog] (
		[id] [int] IDENTITY (1, 1) NOT NULL ,
		[type] [tinyint] NOT NULL ,
		[status] [int] NOT NULL ,
		[dateTime] [datetime] NOT NULL ,
		[elapsed] [int] NOT NULL ,
		[businessElapsed] [int] NOT NULL ,
		[url] [varchar] (200) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[params] [varchar] (1000) COLLATE Chinese_PRC_CI_AS NOT NULL ,
		[referrer] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[ipAddress] [varchar] (15) COLLATE Chinese_PRC_CI_AS NULL ,
		[ipLocation] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[browser] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,
		[profileId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
		[loginUserId] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL 
	) ON [PRIMARY]
END	
GO
------------------------------------------表修改区域开始-------------------------------------------------

IF  EXISTS (SELECT name FROM syscolumns WHERE id = object_id(N'[weblog]') and name = 'params' )
BEGIN
	ALTER TABLE weblog
		ALTER COLUMN params VARCHAR(1000);
END

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


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

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


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

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




IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[UV_PD_PchInOut]'))
DROP VIEW [UV_PD_PchInOut]
GO

CREATE VIEW [UV_PD_PchInOut]
AS
SELECT a.BillNo,a.BillDate,101 AS BillType,a.ElyID,a.BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,b.Total,b.DiscTotal,b.TaxTotal,b.Discount,b.Tax,b.TaxRate
FROM PD_PchBill a INNER JOIN PD_PchDetail b ON a.BillNo = b.BillNo
UNION ALL
SELECT a.BillNo,a.BillDate,102 AS BillType,a.ElyID,a.BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,b.Total,b.DiscTotal,b.TaxTotal,b.Discount,b.Tax,b.TaxRate
FROM PD_PchRetBill a INNER JOIN PD_PchRetDetail b ON a.BillNo = b.BillNo

go



IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[UV_PD_SellInOut]'))
DROP VIEW [UV_PD_SellInOut]
GO

CREATE VIEW [UV_PD_SellInOut]
AS
SELECT a.BillNo,a.BillDate,201 AS BillType,a.ElyID,a.BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,b.Total,b.DiscTotal,b.TaxTotal,b.Discount,b.Tax,b.TaxRate
FROM PD_SellBill a INNER JOIN PD_SellDetail b ON a.BillNo = b.BillNo
UNION ALL
SELECT a.BillNo,a.BillDate,202 AS BillType,a.ElyID,a.BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,b.Total,b.DiscTotal,b.TaxTotal,b.Discount,b.Tax,b.TaxRate
FROM PD_SellRetBill a INNER JOIN PD_SellRetDetail b ON a.BillNo = b.BillNo

go



IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[UV_PD_WhsInOut]'))
DROP VIEW [UV_PD_WhsInOut]
GO

CREATE VIEW [UV_PD_WhsInOut]
AS
SELECT a.BillNo,a.BillDate,101 AS BillType,a.ElyID,0 AS BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,0 as total,0 AS DiscTotal,0 AS TaxTotal,0 AS Discount,0 AS Tax,0 AS TaxRate
FROM PD_AllotBill a INNER JOIN PD_AllotDetail b ON a.BillNo = b.BillNo
UNION ALL
SELECT a.BillNo,a.BillDate,102 AS BillType,a.ElyID,0 AS BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,0 as total,0 AS DiscTotal,0 AS TaxTotal,0 AS Discount,0 AS Tax,0 AS TaxRate
FROM PD_AdjPriceBill a INNER JOIN PD_AdjPriceDetail b ON a.BillNo = b.BillNo
UNION ALL
SELECT a.BillNo,a.BillDate,a.BillTypeID AS BillType,a.ElyID,0 AS BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,0 as total,0 AS DiscTotal,0 AS TaxTotal,0 AS Discount,0 AS Tax,0 AS TaxRate
FROM PD_InOutWhsBill a INNER JOIN PD_InOutWhsDetail b ON a.BillNo = b.BillNo
UNION ALL
SELECT a.BillNo,a.BillDate,a.BillTypeID AS BillType,a.ElyID,0 AS BtypeID
,b.GoodsID,b.Ppt1ID,b.Ppt2ID,b.BSQty,b.GoodsCostTotal,0 as total,0 AS DiscTotal,0 AS TaxTotal,0 AS Discount,0 AS Tax,0 AS TaxRate
FROM PD_LossSpillBill a INNER JOIN PD_LossSpillDetail b ON a.BillNo = b.BillNo

go




IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[UV_PD_InOutStock]'))
DROP VIEW [UV_PD_InOutStock]
GO

CREATE VIEW UV_PD_InOutStock
AS
SELECT * FROM UV_PD_PchInOut
UNION ALL 
SELECT * FROM UV_PD_SellInOut
UNION ALL 
SELECT * FROM UV_PD_WhsInOut

go



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UV_PD_CalAllBillCount]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[UV_PD_CalAllBillCount]
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
 GO 


CREATE VIEW [dbo].UV_PD_CalAllBillCount
--@Encode$--
AS 
SELECT	SUM(B.nCount) AS allCount
FROM	
(
	SELECT COUNT(*) AS nCount FROM MF_ARAPBill					--应收应付增加减少单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM MF_FeeRecBill				--费用、其他收入单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM MF_PayRecBill				--收付款单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM MF_PchInvoiceBill			--采购发票
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM MF_SellInvoiceBill			--转款单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM MF_TransferBill				--转款单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_AdjPriceBill				--调价单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_AllotBill					--调拨单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_AllotReqBill				--调拔申请单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_AssemblyBill				--生产拆装单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_InOutWhsBill				--其他出入库单,积分兑换单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_LossSpillBill				--报损报溢单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_PchBill					--采购入库单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_PchOrdBill				--采购订单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_PchRetBill				--采购退货单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_SellBill					--销售出库单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_SellOrdBill				--销售订单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_SellRetBill				--销售退货单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_StockBill					--盘点单
	UNION ALL 
	SELECT COUNT(*) AS nCount FROM PD_WeiXinRecord
	UNION ALL
	SELECT COUNT(*) AS nCount FROM VS_VipChargeBill				--会员充值单
)B			

GO



if exists (select * from sys.objects where object_id = object_id(N'[TR_OT_UpdateGoodsStockCheck]') and type='TR')
drop TRIGGER [TR_OT_UpdateGoodsStockCheck]
GO

CREATE TRIGGER TR_OT_UpdateGoodsStockCheck
ON PD_GoodsStock
FOR UPDATE,INSERT
AS
IF EXISTS(SELECT 1 FROM dbo.SS_SysCfg WHERE CfgName='IsNegative' AND CfgValue=1)
RETURN

IF UPDATE(Qty)    --如果更新了Qty才触发
BEGIN
	DECLARE @Qty DECIMAL(20,8)=0,@GoodsID INT,@Msg VARCHAR(max)
	SELECT @Qty=Qty,@GoodsID=GoodsID FROM INSERTED WHERE Qty<0
	IF @Qty<0
	BEGIN
		SELECT @Msg='商品【'+GoodsName+'】过账后会产生负库存' FROM BD_Goods WHERE GoodsID=@GoodsID
		RAISERROR(@Msg,16,1);
	END
END

Go




IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OT_Paging]') AND type in (N'P', N'PC')) 
DROP PROCEDURE [UP_OT_Paging] 
GO 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
/*------------------------------------------
    作者：姚鹏
	日期：2014-5-14
	描述：通用分页过程
-------------------------------------------*/
CREATE PROCEDURE UP_OT_Paging 
(
	@Sql	NVARCHAR(max),			--业务SQL
	@TVP TVP_Paging_Param READONLY,	--参数列表
	@PageNo INT,					--页码
	@PageSize INT,					--每页行数
	@RIDField	NVARCHAR(max)=N'',	--行号排序字段
	@ParField	NVARCHAR(max)=N'',	--分组字段
	@OrdField	NVARCHAR(max)=N'',	--结果集排序字段
	@RowIDType TINYINT=1,			--行号方式 1=ROW_NUMBER 2=RANK 3=DENSE_RANK
	@PRINTSQL	BIT=0				--是否打印sql 0=不打印 1=打印
)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @ExeSql NVARCHAR(max),@DecParam NVARCHAR(max),@Param NVARCHAR(max),@RType NVARCHAR(20),@DataSQL  NVARCHAR(max)=N''
	SELECT @RType=CASE WHEN @RowIDType=1 THEN N'ROW_NUMBER()' WHEN @RowIDType=2 THEN N'RANK()' WHEN @RowIDType=3 THEN N'DENSE_RANK()' END;
	IF @ParField<>N'' SET @ParField=N' PARTITION BY '+@ParField;
	IF @OrdField<>N'' SET @OrdField=N' ORDER BY '+@OrdField
	
	IF EXISTS(SELECT 1 FROM @TVP WHERE [ParaName] LIKE '_DATA_%')
	BEGIN
		SELECT @Sql+=N'
		, '+[ParaName]+N' AS 
		(
		 '+[ParaValue]+N'
		)' FROM @TVP WHERE [ParaName] LIKE '_DATA_%'
		
		SELECT @DataSQL+=N'
		LEFT JOIN '+[ParaName]+N' ON '+[DataType]+N' '
		FROM @TVP WHERE [ParaName] LIKE '_DATA_%'
	END
	
	SET @Sql=N'SET NOCOUNT ON;
   '+@Sql+N'
   ,DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	'+@RType+N' OVER('+@ParField+N' ORDER BY '+@RIDField+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	SELECT * FROM DATA '+@DataSQL+@OrdField
	SELECT @DecParam=STUFF((SELECT N','+[ParaName]+N' '+[DataType] FROM @TVP WHERE [ParaName] NOT LIKE '_DATA_%' FOR XML PATH ('')),1,1,'');
	SELECT @Param=STUFF((SELECT N','+CASE WHEN [DataType] NOT IN ('bigint','int','decimal','bit','numeric','smallint','tinyint','varbinary') 
			THEN N''''+[ParaValue]+'''' ELSE [ParaValue] END from @TVP WHERE [ParaName] NOT LIKE '_DATA_%' for xml path ('')),1,1,'')
	IF ISNULL(@DecParam,N'')=N''
		BEGIN
			SET @DecParam=N'@PageNo INT,@PageSize INT,@RIDField NVARCHAR(max)';
			SET @Param=CAST(@PageNo AS VARCHAR(10))+N','+CAST(@PageSize AS VARCHAR(10))+N','''+@RIDField+N''''
		END
	ELSE
		BEGIN
			SET @DecParam=N'@PageNo INT,@PageSize INT,@RIDField NVARCHAR(max),'+@DecParam;
			SET @Param=CAST(@PageNo AS VARCHAR(10))+N','+CAST(@PageSize AS VARCHAR(10))+N','''+@RIDField+N''','+@Param
		END
	SET @ExeSql=N'EXEC sp_executesql @Sql,@DecParam,'+@Param
	EXEC sp_executesql @ExeSql,N'@Sql NVARCHAR(max),@DecParam NVARCHAR(max)',@Sql,@DecParam
	
	IF @PRINTSQL=0
	RETURN
	
	 DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 SELECT @dec=STUFF((SELECT N','+[ParaName]+N' '+[DataType]+N'='+CASE WHEN [DataType] NOT IN 
			('bigint','int','decimal','bit','numeric','smallint','tinyint','varbinary') 
			THEN N''''+[ParaValue]+'''' ELSE [ParaValue] END FROM @TVP WHERE [ParaName] NOT LIKE '_DATA_%' FOR XML PATH ('')),1,1,'');
	 IF @dec<>'' 
		SET @dec=@dec+N','
	 ELSE
		SET @dec=N''
	 --PRINT N'DECLARE '+@dec+N'@RIDField NVARCHAR(max)=N'''+@RIDField+''',@PageNo INT='+CAST(@PageNo AS NVARCHAR)+',@PageSize INT='+CAST(@PageSize AS NVARCHAR)
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 --PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
END
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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



/*
	作者：祁丹
	日期：2020-02-10
	描述：批量过账前的数据检查
*/

CREATE  PROCEDURE Gp_PD_CheckBatchPassBillData
(
	@Etypeid 	varchar(100),
	@BillType	INT,
	@BillNo		NUMERIC(18,0),		-- 单据ID
	@retGoodsID	VARCHAR(20)	OUTPUT
)
--@encode$--
AS
SET NOCOUNT ON

DECLARE @SQL NVARCHAR(MAX),
		@sqlWhere VARCHAR(2000),
		@intResult INT,
		@fieldStr VARCHAR(50),
		@MainTable VARCHAR(50),
		@detailTable VARCHAR(50),
		@serialTable VARCHAR(50),
		@Msg		VARCHAR(200)

SELECT @MainTable=BillTable,@detailTable=BillDetail,@serialTable=BillSerial FROM PD_BillType WHERE BillTypeId=@BillType


--是否开账
IF NOT EXISTS(SELECT 1 FROM dbo.D9ZTInfo WHERE IsOpen=1)
	RETURN -11

DECLARE @temp int
SET @SQL='SELECT @temp=Count(1) FROM '+@MainTable+' Where billdate>=(select Convert(varchar(50),startDate,23) from Ss_MonthProc Where Name=''本期'') and billno='+CAST(@Billno AS VARCHAR(10))+''
EXECUTE sp_executesql @SQL,N'@temp INT OUTPUT',@temp OUTPUT	
IF(@temp<>1)
	RETURN -12
	
--检测单据是否存在或者是否已经过账
SET @SQL='IF NOT EXISTS( SELECT TOP 1 1 FROM '+@MainTable+' WHERE BillNo = '+CAST(@BillNo AS VARCHAR(10))+') OR EXISTS( SELECT TOP 1 1 FROM '+@MainTable+' WITH(NOLOCK) WHERE IsDraft = 0 AND BillNo = '+CAST(@BillNo AS VARCHAR(10))+') SET @intResult=1 ELSE SET @intResult=0'
EXECUTE sp_executesql @SQL,N'@intResult INT OUTPUT',@intResult OUTPUT
IF @intResult=1
	RETURN -10
	
	
--检测关联单据是否已经归档
IF @BillType IN(101,201)
BEGIN
	SELECT @fieldStr=CASE @BillType WHEN 101 THEN 'Pch' ELSE 'Sell' END
	SET @SQL='IF EXISTS(SELECT 1 FROM dbo.PD_'+@fieldStr+'Detail pd WHERE EXISTS(SELECT 1 FROM dbo.PD_'+@fieldStr+'OrdDetail_His WHERE DID=pd.OrdDID) AND pd.BillNo='+CAST(@BillNo AS VARCHAR(10))+') SET @intResult=0 ELSE SET @intResult=1 '
END
ELSE IF @BillType IN(102,202)
BEGIN
	SELECT @fieldStr=CASE @BillType WHEN 102 THEN 'Pch' ELSE 'Sell' END
	SET @SQL='IF EXISTS(SELECT 1 FROM dbo.PD_'+@fieldStr+'RetDetail pd WHERE EXISTS(SELECT 1 FROM dbo.PD_'+@fieldStr+'Detail_His WHERE DID=pd.'+@fieldStr+'DID) AND pd.BillNo='+CAST(@BillNo AS VARCHAR(10))+') SET @intResult=0 ELSE SET @intResult=1 '
END
ELSE IF @BillType IN(301,309)
BEGIN
	SET @SQL='IF EXISTS(SELECT 1 FROM dbo.PD_AllotDetail pd WHERE EXISTS(SELECT 1 FROM dbo.PD_AllotReqDetail_His WHERE DID=pd.ReqDID) AND pd.BillNo='+CAST(@BillNo AS VARCHAR(10))+') SET @intResult=0 ELSE SET @intResult=1 '
END
ELSE
BEGIN
	SELECT @SQL+=' IF EXISTS(SELECT 1 FROM ' +BillTable+'_His WHERE BillNO='+CAST(l.BillNo AS VARCHAR)+') BEGIN SELECT @intResult=0 RETURN END ' 
	FROM dbo.PD_BillType i INNER JOIN dbo.MF_PayRecList l ON i.BillTypeID = l.BillTypeID WHERE PayRecBillNo=@BillNo AND i.BillTypeID NOT IN(998,999)
	SET @SQL+=' SELECT @intResult=1'
END
EXECUTE sp_executesql @SQL,N'@intResult INT OUTPUT',@intResult OUTPUT
IF @intResult=0
	RETURN -102
	
	
--改变单据状态
EXEC('Update '+@MainTable+' SET IsDraft=0,PosTime=getdate(),PosElyID='''+@Etypeid+''' WHERE BillNo = '''+@BillNo+''' ')
IF @@ROWCOUNT = 0
	RETURN 9
	

DECLARE @GoodsInfo VARCHAR(50)=''	
IF @BillType IN(102,201,301,302,304,305,309,310,600)
BEGIN	
	SELECT @fieldStr=CASE WHEN @BillType IN(301,309) THEN 'Out' ELSE '' END
	SELECT @sqlWhere=CASE WHEN @BillType=310 THEN ' AND DetailType=2' ELSE '' END 
	-- 移动加权检查是否录入批次 调价单移动加权的无批次，不选择 商品只有空批次不提示

	SET @SQL='SELECT TOP 1 @GoodsInfo=D.GoodsID FROM '+@detailTable+' D INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID 
				WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND IsSelectBatch=0 AND G.CostMethod=1 
				AND EXISTS(SELECT 1 FROM dbo.PD_GoodsStock_Detail gd WHERE gd.GoodsID=d.GoodsID AND gd.WhsPtID=d.'+@fieldStr+'WhsPtID 
				AND (CostPrice<>0 OR BatchNumber<>'''' OR gd.ProductDate<>'''' OR gd.EndDate<>'''')) '+@sqlWhere+' '
	            
	EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT',@GoodsInfo OUTPUT
	IF ISNULL(@GoodsInfo,'')<>''
	BEGIN
		SET @retGoodsID=@GoodsInfo
		RETURN -7
	END

	IF EXISTS( SELECT 1 FROM SS_SysCfg WHERE CfgName='IsNegative' AND CfgValue=0)
	BEGIN
		 --不允许负库存 检查移动加权的商品
		IF @BillType=302
			SET @SQL=';WITH PostData AS(SELECT D.GoodsID,SUM(Qty)AS Qty,'+@fieldStr+'WhsID AS WhsID FROM '+@detailTable+' D
						INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND G.CostMethod=1 '+@sqlWhere+' GROUP BY D.GoodsID,'+@fieldStr+'WhsID)
						SELECT TOP 1 @GoodsInfo=p.GoodsID FROM PostData p LEFT JOIN PD_GoodsStock s ON p.WhsID=s.WhsID AND p.GoodsID=s.GoodsID WHERE p.Qty>ISNULL(s.Qty,0)'
		ELSE
			SET @SQL=';WITH PostData AS(SELECT D.GoodsID,SUM(BsQty)AS Qty,'+@fieldStr+'WhsPtID WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate FROM '+@detailTable+' D
						INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND G.CostMethod=1 '+@sqlWhere+' GROUP BY D.GoodsID,'+@fieldStr+'WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate)
						SELECT TOP 1 @GoodsInfo=p.GoodsID FROM PostData p LEFT JOIN PD_GoodsStock_Detail s ON p.GoodsID=s.GoodsID AND p.WhsPtID=s.WhsPtID AND s.Ppt1ID=p.Ppt1ID 
						AND s.Ppt2ID=p.Ppt2ID AND s.BatchNumber=P.BatchNumber AND s.ProductDate=P.ProductDate AND s.EndDate=p.EndDate WHERE p.Qty>ISNULL(s.Qty,0)'
		                
		EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT',@GoodsInfo OUTPUT
		IF ISNULL(@GoodsInfo,'')<>''
		BEGIN
			SET @retGoodsID=@GoodsInfo
			IF @BillType=302
				RETURN -2
			ELSE
				RETURN -1
		END 
	END 


	--检查是否录入批次

	SET @SQL='SELECT TOP 1 @GoodsInfo=D.GoodsID FROM '+@detailTable+' D  INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND IsSelectBatch=0  AND G.CostMethod=2 '+@sqlWhere+' '
	EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT',@GoodsInfo OUTPUT
	IF ISNULL(@GoodsInfo,'')<>''
	BEGIN
		SET @retGoodsID=@GoodsInfo
		RETURN -7
	END  


	--手工指定的商品始终检查负库存
	SET @SQL=';WITH PostData AS(SELECT D.GoodsID,SUM(BsQty)AS Qty,'+@fieldStr+'WhsPtID WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,CostPrice FROM '+@detailTable+' D
				INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND InPutPrice=0  AND G.CostMethod=2 '+@sqlWhere+' GROUP BY D.GoodsID,'+@fieldStr+'WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,CostPrice)
				SELECT TOP 1 @GoodsInfo=p.GoodsID FROM PostData p LEFT JOIN PD_GoodsStock_Detail s ON p.GoodsID=s.GoodsID AND p.WhsPtID=s.WhsPtID AND s.Ppt1ID=p.Ppt1ID 
				AND s.Ppt2ID=p.Ppt2ID AND s.BatchNumber=P.BatchNumber AND s.ProductDate=P.ProductDate AND s.EndDate=p.EndDate AND s.CostPrice=p.CostPrice WHERE p.Qty>ISNULL(s.Qty,0)'
	EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT',@GoodsInfo OUTPUT
	IF ISNULL(@GoodsInfo,'')<>''
	BEGIN
		SET @retGoodsID=@GoodsInfo
		IF @BillType=302
			RETURN -2
		ELSE
			RETURN -1
	END 
END
IF @BillType IN(102,201,202,301,304,305,306,309,310,600)
BEGIN
	SELECT @fieldStr=CASE WHEN @BillType IN(301,309) THEN 'Out' ELSE '' END
	SELECT @sqlWhere=CASE WHEN @BillType=310 THEN ' AND DetailType=2' ELSE '' END 
	--检查成本单价，没有成本单价或者成本单价为负的时候录入成本单价
	SET @SQL=';WITH PostData AS(SELECT D.GoodsID,'+@fieldStr+'WhsID AS WhsID,SUM(GoodsCostTotal) AS GoodsCostTotal,InPutPrice,CostMethod FROM '+@detailTable+' D 
				INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE  BillNo='+CAST(@BillNo AS VARCHAR(10))+' '+@sqlWhere+' GROUP BY D.GoodsID,'+@fieldStr+'WhsID,InPutPrice,CostMethod)
				SELECT DISTINCT p.GoodsID INTO #T FROM PostData p LEFT JOIN PD_GoodsStock s ON p.WhsID=s.WhsID AND p.GoodsID=s.GoodsID
				WHERE  InPutPrice=1 AND (CostMethod=1 AND (s.Price IS NULL OR s.Price<0 ) OR CostMethod=2)
				AND NOT EXISTS( SELECT 1 FROM PD_PriceTrail WHERE GoodsID=p.GoodsID AND PchPrice IS NOT NULL)
				IF EXISTS(SELECT TOP 1 GoodsID FROM #T WHERE ISNULL(GoodsID,'''')<>'''' ) SET @intResult=1 ELSE SET @intResult=0
				'
	EXECUTE sp_executesql @SQL,N'@intResult INT OUTPUT',@intResult OUTPUT
	IF @intResult=1
		RETURN -5
END


--检查序列号相关，先判断是否启用序列号
IF EXISTS( SELECT 1 FROM SS_SysCfg WHERE CfgName='SerialNoMgt' AND CfgValue=1)
BEGIN
	IF @BillType IN(101,102,201,202,301,302,303,304,305,306,309,310,600)
	BEGIN
	
		--序列号的数量
		DECLARE @Serial VARCHAR(50)
		SELECT @sqlWhere=CASE WHEN @BillType=302 THEN ' AND G.CostMethod=2' ELSE '' END
		SET @SQL='SELECT TOP 1 @GoodsInfo=GoodsName FROM '+@detailTable+' d
					INNER JOIN dbo.BD_Goods g ON g.GoodsID=d.GoodsID
					LEFT JOIN
					(SELECT COUNT(1)Qty,BillDID FROM '+@serialTable+' GROUP BY BillDID)s
					ON d.DID=s.BillDID
					WHERE BillNo='+CAST(@billNo AS VARCHAR(10))+' AND IsSerial=1 AND d.BSQty<>ISNULL(s.Qty,0)'+@sqlWhere+''
		EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT',@GoodsInfo OUTPUT
		IF isnull(@GoodsInfo,'')<>''
		BEGIN
			SET @Msg='商品【'+@GoodsInfo+'】的序列号数量不等于商品数量'
			RAISERROR(@Msg,16,1)
			RETURN -6
		END
		
		
		--序列号
		IF @BillType IN(101,202,303,306,310)
		BEGIN
			SELECT @sqlWhere=CASE WHEN @BillType=310 THEN ' AND d.DetailType= 1' ELSE '' END
			SET @SQL='SELECT TOP 1 @GoodsInfo=GoodsName,@Serial=Serial FROM '+@serialTable+' s INNER JOIN '+@detailTable+' d ON s.BillDID=d.DID INNER JOIN BD_Goods G ON d.GoodsID=g.GoodsID
                        WHERE d.BillNo='+CAST(@billNo AS VARCHAR(10))+' AND EXISTS(SELECT 1 FROM  dbo.PD_GoodsSerial gs WHERE gs.Serial=s.Serial AND gs.Flag IN(1,2))'+@sqlWhere+''
            EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT,@Serial VARCHAR(50) OUTPUT,',@GoodsInfo OUTPUT,@Serial OUTPUT
			IF isnull(@GoodsInfo,'')<>''
			BEGIN
				SET @Msg='商品【'+@GoodsInfo+'】的序列号【'+@Serial+'】已经在库'
				RAISERROR(@Msg,16,1)
				RETURN -4
			END
		END
		
		IF @BillType IN(102,201,301,302,304,305,309,310,600)
		BEGIN
			SELECT @fieldStr=CASE WHEN @BillType IN(301,309) THEN 'Out' ELSE '' END
			SELECT @sqlWhere=CASE WHEN @BillType=310 THEN ' AND d.DetailType=2' ELSE '' END 
			DECLARE @SQL1 VARCHAR(500)
			SET @SQL1=CASE WHEN @BillType=302 THEN '' ELSE ' AND gs.Ppt1ID=d.Ppt1ID AND gs.Ppt2ID=d.Ppt2ID AND gs.WhsPtID=d.'+@fieldStr+'WhsPtID AND gs.BatchNumber=d.BatchNumber
                                     AND gs.ProductDate=d.ProductDate AND gs.EndDate=d.EndDate ' END
                                     
			SET @SQL='SELECT TOP 1 @GoodsInfo=GoodsName,@Serial=Serial FROM (SELECT TOP 1 GoodsName,Serial FROM '+@serialTable+' s  INNER JOIN '+@detailTable+' d ON s.BillDID=d.DID INNER JOIN BD_Goods G ON d.GoodsID=g.GoodsID
						 WHERE d.BillNo='+CAST(@billNo AS VARCHAR(10))+' AND NOT EXISTS(SELECT 1 FROM  dbo.PD_GoodsSerial gs WHERE gs.Serial=s.Serial AND gs.GoodsID=d.GoodsID '+@SQL1
						 +' AND gs.WhsID=d.'+@fieldStr+'WhsID AND gs.Flag=1) AND G.CostMethod=1 '+@sqlWhere+'
						 UNION ALL 
						 SELECT TOP 1 GoodsName,Serial FROM '+@serialTable+' s  INNER JOIN '+@detailTable+' d ON s.BillDID=d.DID INNER JOIN BD_Goods G ON d.GoodsID=g.GoodsID
						 WHERE d.BillNo='+CAST(@billNo AS VARCHAR(10))+' AND NOT EXISTS(SELECT 1 FROM  dbo.PD_GoodsSerial gs WHERE gs.Serial=s.Serial AND gs.GoodsID=d.GoodsID 
						 AND gs.Ppt1ID=d.Ppt1ID AND gs.Ppt2ID=d.Ppt2ID AND gs.WhsPtID=d.'+@fieldStr+'WhsPtID AND gs.BatchNumber=d.BatchNumber AND gs.CostPrice=d.CostPrice
						 AND gs.ProductDate=d.ProductDate AND gs.EndDate=d.EndDate AND gs.WhsID=d.'+@fieldStr+'WhsID AND gs.Flag=1) AND G.CostMethod=2 '+@sqlWhere+')TT'
			EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT,@Serial VARCHAR(50) OUTPUT,',@GoodsInfo OUTPUT,@Serial OUTPUT
			IF isnull(@GoodsInfo,'')<>''
			BEGIN
				SET @Msg='商品【'+@GoodsInfo+'】的序列号【'+@Serial+'】不在库'
				RAISERROR(@Msg,16,1)
				RETURN -4
			END
		END
	END
END


--用户数
DECLARE @UserCount INT,@UserNumber INT
SELECT @UserCount=count(1) FROM SS_Operator where stt=1 and ElyID<>1
SELECT @UserNumber=isnull(UserNumber,1) from D9Master.dbo.D9AccountList where (usercode=DB_NAME() or fullname=DB_NAME())
IF @UserCount>@UserNumber
	RETURN 819
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 sysobjects where id = object_id(N'[dbo].[UP_BD_CheckInOutBillUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop PROCEDURE [dbo].[UP_BD_CheckInOutBillUsed]
GO
--实现检测基本信息是否被使用功能 的存储过程   函数中不能使用EXEC sp_executesql
--date    :20014-6-24
-- update 20150520商品删除检查排除OS_GoodsRelation的检查
CREATE PROCEDURE [dbo].[UP_BD_CheckInOutBillUsed]
(
	@GoodsID INT=0			--商品单位的判断才需要此字段
)

AS 
BEGIN

DECLARE @Sql NVARCHAR(Max)='',
		@TableName VARCHAR(50)='' ,--使用到的表
		@UseName VARCHAR(100)='' --表对应的功能

	select @Sql += ' IF Exists(Select top 1 1 from ' + BillTable + ' a inner join ' + BillDetail +' b on a.BillNo = b.BillNo where GoodsID = @GoodsID and red = 0 ) BEGIN SELECT @TableName='''+BillDetail +''' RETURN END 
					IF Exists(Select top 1 1 from ' + BillTable + '_His a inner join ' + BillDetail +'_His b on a.BillNo = b.BillNo where GoodsID = @GoodsID and red = 0 ) BEGIN SELECT @TableName='''+BillDetail +'His' + ''' RETURN END '
		from PD_BillType 
		where BillTypeID in (101,102,201,202,301,303,304,305,306,309)
	Select @Sql += ' IF Exists(Select top 1 1 from BD_OpeningStock_Detail where GoodsID=@GoodsID) BEGIN SELECT @TableName='''+'BD_OpeningStock_Detail'+''' RETURN END '
	Select @Sql += ' IF Exists(Select top 1 1 from PD_StockDetail where GoodsID=@GoodsID) BEGIN SELECT @TableName='''+'PD_StockDetail'+''' RETURN END '
	Select @Sql += ' IF Exists(Select top 1 1 from PD_StockDetail_His where GoodsID=@GoodsID) BEGIN SELECT @TableName='''+'PD_StockDetail_His'+''' RETURN END '
	--Select @Sql += ' IF Exists(Select top 1 1 from PD_GoodsStock where GoodsID=@GoodsID) BEGIN SELECT @TableName='''+'PD_GoodsStock'+''' RETURN END '
	EXEC sp_executesql @Sql,N'@TableName varchar(50) out,@GoodsID int',@TableName OUT,@GoodsID
	if @TableName <> ''
	BEGIN
		select @TableName
		return
	END
	
	select ''
	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



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

/*------------------------------------------
    作者：WangWei
	日期：2015-01-08
	描述：项目分类时删除权限相关的值
-------------------------------------------*/
CREATE PROCEDURE UP_BD_DeleteLimit
(
	@FID INT 
)

AS

return 
DECLARE @sonnum INT

SET @sonnum=0 --传入的层级

DECLARE @lv INT =0,@FinanceID INT ,@ParID INT,@id INT 
SELECT @lv=Lvl,@FinanceID=FinanceID,@ParID=parid FROM BD_Finance where FinanceID=  @FID

DELETE FROM  SS_Finance_Jur where FinanceID=@FinanceID
DELETE FROM  SS_Finance_Jur where FinanceTypeID=@FinanceID

DECLARE @ExtRole TABLE(id INT ) --排除的角色
	
BEGIN TRAN DelLimit	

while @lv>0
BEGIN

	INSERT INTO @ExtRole(id)
	SELECT  RoleID  FROM SS_Finance_Jur  
	WHERE RoleID Not IN(SELECT id FROM @ExtRole) AND  FinanceTypeID=@ParID
	group by RoleID

	DECLARE @tmID INT  
	SELECT @tmID=ParID FROM BD_Finance where FinanceID=@ParID  
	DELETE FROM  SS_Finance_Jur where FinanceID=@ParID AND RoleID NOT IN (SELECT id FROM @ExtRole)
	SET @ParID=@tmID	
	SET @lv=@lv-1
END

COMMIT TRAN DelLimit	

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_GoodsPriceList]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_GoodsPriceList]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*------------------------------------------
    作者：WangWei
	日期：2014-5-23
	描述：商品物价信息
-------------------------------------------*/
CREATE PROCEDURE UP_BD_GoodsPriceList
(
	 @pageNo INT=0
	,@pageSize INT=0
	,@GoodsTypeID INT=0
	,@fullName VARCHAR(100)=''
	,@fullNameMatch int =0
	,@userCode VARCHAR(50)=''
	,@userCodeMatch int =0
	,@Spec VARCHAR(50)=''--规格
	,@SpecMatch int =0
	,@Model VARCHAR(50)=''--型号
	,@ModelMatch int =0
	,@Place VARCHAR(50)=''--产地
	,@PlaceMatch int =0
	,@Name VARCHAR(50)=''--简名
	,@NameMatch int =0
	,@Brand VARCHAR(50)=''--品牌
	,@BrandMatch int =0
	,@BarCode VARCHAR(100)=''--条码
	,@BarCodeMatch int =0
	,@UnitID int =0--计量单位
	,@PriceIndex int =0--价格类型
	,@PriceMin decimal(20,8)=-1 --最小值
	,@PriceMax decimal(20,8)=-1 --最大值
	,@showStock bit=0-- 只显示有库存的商品 0==所有
	,@showStopped BIT=0 --/*是否显示停用信息*/ 0=所有
)

AS
SET NOCOUNT ON
begin


DECLARE @sql NVARCHAR(max), @TVP as TVP_Paging_Param



SET @sql=''

IF @GoodsTypeID>0
BEGIN
	
	SET	@sql+='  
				DECLARE @GoodsTypeTd as table(GoodsTypeID int,TypeCode varchar(50),TypeName varchar(100))
				
				INSERT INTO @GoodsTypeTd( GoodsTypeID,TypeCode,TypeName)
				SELECT gt.GoodsTypeID,gt.TypeCode,gt.TypeName
				FROM BD_Goods_Type t	
				INNER JOIN BD_Goods_Type gt ON gt.[Path] like t.[Path]+''%''			
				WHERE t.GoodsTypeID=@GoodsTypeID  AND gt.SonNum=0 '
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsTypeID','int',@GoodsTypeID)
END






SET @sql+=';WITH '

SET @sql+='AvgData as (
					SELECT goodsid,
							(CASE  sum(qty) WHEN 0 THEN 0
							ELSE  CAST(sum(Total) as numeric(20,8))/CAST(sum(qty) as numeric(20,8)) END) as AvgPrice
							,CAST(sum(qty) as numeric(20,4)) as StockQty
					FROM PD_GoodsStock GROUP BY GoodsID
			),'
SET @sql+='
		PChPriceData as 
		(
		SELECT  GoodsID,max(PchDate)as maxDate,UnitID  FROM PD_PRiceTrail b
		GROUP BY  GoodsID,UnitID
		)
		, priceData as 
		(
		SELECT  a.goodsid,PchPrice*a.PchDis as PchPrice,a.UnitID  from PD_PRiceTrail a inner join PChPriceData b on a.goodsid=b.goodsid and b.maxDate=a.pchdate and a.UnitID=b.UnitID

		), '  --最近进价

IF 	 @BarCode<>''
BEGIN
	SET @sql+=' GoodsBarCode as
		(
			select distinct GoodsID from BD_Goods_Price where ' + case @BarCodeMatch when 0 then ' BarCode like ''%''+@BarCode+''%'' ' else ' BarCode = @BarCode ' end
		+' ), '
END
		
SET @sql+='
	PagingData AS
	(
		SELECT 
		   p.[GoodsID]
		  ,p.[UnitID]
		  ,p.[Unit]
		  ,p.[Convfactor]
		  ,p.[BarCode]
		  ,p.[Price_Rtl]
		  ,p.[Price1]
		  ,p.[Price2]
		  ,p.[Price3]
		  ,p.[Price4]
		  ,p.[Price5]
		  ,p.[Price6]
		  ,p.[Price7]
		  ,p.[Price8]
		  ,p.[Price9]
		  ,p.[Price10]
		  ,p.[Price11]
		  ,p.[Price12]
		  ,p.[Price13]
		  ,p.[Price14]
		  ,p.[Price15]
		  ,g.[Stt]
		  ,g.GoodsAbbName as Name
		  ,g.Brand
		  ,g.GoodsName
		  ,g.GoodsNo
		  ,g.Spell
		  ,g.Spec
		  ,g.Model
		  ,g.Place
		  ,gt.GoodsTypeID
		  ,gt.TypeCode
		  ,gt.TypeName'
SET 	@sql+=' ,pd.PchPrice  as PchPrice '   --最近进价
SET 	@sql+=' ,CAST(ad.AvgPrice as numeric(20,8)) * p.Convfactor  as AvgPrice ,CAST( CAST(ad.StockQty as numeric(20,4)) / p.Convfactor  as numeric(20,4)) as  StockQty'   --成本均价
SET 	@sql+='
	FROM [BD_Goods_Price] p
			INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID'
IF @GoodsTypeID>0
	SET @sql+='
			INNER JOIN @GoodsTypeTd  gt ON g.GoodsTypeID=gt.GoodsTypeID '
else 
	SET @sql+='
			INNER JOIN BD_Goods_Type gt ON g.GoodsTypeID=gt.GoodsTypeID '
IF @BarCode<>''
	SET @sql+='
			INNER JOIN GoodsBarCode Gbc ON g.GoodsID=Gbc.GoodsID '
SET @sql+=' 
			LEFT JOIN priceData pd ON p.GoodsID=pd.goodsid AND p.UnitID=pd.UnitID
			LEFT JOIN AvgData ad ON P.goodsID=ad.GoodsID
			 '	 --最近进价	
	
SET @sql+='	WHERE 1=1 '





if @PriceIndex<>0 AND ( @PriceMin<>-1 OR  @PriceMax<>-1)
BEGIN
	if(@PriceIndex=-1)--成本均价
	BEGIN
		if(@PriceMin<>-1)
			SET	@sql+=' AND ad.AvgPrice >=@PriceMin'	 
		if(@PriceMax<>-1)	
			SET	@sql+=' AND ad.AvgPrice <= @PriceMax '
	END	
	ELSE if(@PriceIndex=-2)--最近进价
	BEGIN
		 
		if(@PriceMin<>-1)
			SET	@sql+=' AND pd.PchPrice >= @PriceMin '
		if(@PriceMax<>-1)		
			SET	@sql+=' AND pd.PchPrice <= @PriceMax'	
	END	
	ELSE  
	BEGIN
		if(@PriceMin<>-1)
			SET	@sql+=' AND p.Price'+CAST(@PriceIndex as Varchar)+' >= @PriceMin  '	 
		if(@PriceMax<>-1)	
			SET	@sql+=' AND p.Price'+CAST(@PriceIndex as Varchar)+' <= @PriceMax  '
	END
	
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@PriceMin','decimal(20,8)',@PriceMin)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@PriceMax','decimal(20,8)',@PriceMax)
END


IF @UnitID>0
BEGIN
		SET	@sql+=' AND p.UnitID=@UnitID '
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UnitID','int',@UnitID)
END


IF 	 @userCode<>''
BEGIN
	
		if(@userCodeMatch=0)
				SET @sql +=' AND g.GoodsNo like ''%''+@userCode+''%'' '
		else if(@userCodeMatch=1)
				SET @sql +=' AND g.GoodsNo = @userCode '	  	
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@userCode','VARCHAR(50)',@userCode)
END	  

IF 	 @fullName<>''
BEGIN
		if(@fullNameMatch=0)
				SET @sql +=' AND g.GoodsName like ''%''+@fullName+''%'' '
		else if (@fullNameMatch=1)
			SET @sql +=' AND g.GoodsName = @fullName '
			
	 
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@fullName','VARCHAR(100)',@fullName)
	  	
END



IF 	 @Spec<>''
BEGIN
		if(@SpecMatch=0)
			SET @sql +=' AND g.Spec like  ''%''+@Spec+''%'' '
		else if  (@SpecMatch=1)
			SET @sql +=' AND g.Spec = @Spec '
			
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Spec','VARCHAR(50)',@Spec)
	  	
END

IF 	 @Model<>''
BEGIN

		if(@ModelMatch=0)
			SET @sql +=' AND g.Model like ''%''+@Model+''%'' '
		else if (@ModelMatch=1)
			SET @sql +=' AND g.Model = @Model '	
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Model','VARCHAR(50)',@Model)	  	
END


IF 	 @Name<>''
BEGIN

		if(@NameMatch=0)
			SET @sql +=' AND g.GoodsAbbName like ''%''+@Name+''%'' '
		else if (@NameMatch=1)
			SET @sql +=' AND g.GoodsAbbName = @Name  '
	  
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Name','VARCHAR(50)',@Name)
END

IF 	 @Brand<>''
BEGIN

		if(@BrandMatch=0)
			SET @sql +=' AND g.Brand like ''%''+@Brand+''%'' '
		else if (@BrandMatch=1)
			SET @sql +=' AND g.Brand = @Brand  '
	  
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Brand','VARCHAR(50)',@Brand)
END

IF 	 @BarCode<>''
BEGIN

		--if(@BarCodeMatch=0)
		--	SET @sql +=' AND p.BarCode like ''%''+@BarCode+''%'' '
		--else if (@BarCodeMatch=1)
		--	SET @sql +=' AND P.BarCode = @BarCode  '	  
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BarCode','VARCHAR(100)',@BarCode)
END

IF 	 @Place<>''
BEGIN

		if(@PlaceMatch=0)
			SET @sql +=' AND g.Place like ''%''+@Place+''%'' '
		else if (@PlaceMatch=1)
			SET @sql +=' AND g.Place = @Place  '
	  
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Place','VARCHAR(50)',@Place)
END

IF @showStock=1
BEGIN
		SET	@sql+='  '
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@showStock','int',@showStock)

END
IF @showStopped=0
BEGIN
		SET	@sql+=' AND g.stt=1 '
END

if @showStock=1
BEGIN
	set @sql+=' and AD.StockQty>0 '
END


SET @sql +=' ) '


EXEC UP_OT_Paging @sql,@TVP,@pageNo,@pageSize,'GoodsNo,UnitID','','',1,0
end
GO






/****** Object:  StoredProcedure [UP_BD_ImportArea]    Script Date: 12/04/2014 10:04:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportArea]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportArea]
GO

/****** Object:  StoredProcedure [UP_BD_ImportArea]    Script Date: 12/04/2014 10:04:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-04
	描述：地区导入
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportArea]
(			   
	@PAreaNO VARCHAR(50),
	@AreaNO VARCHAR(50),
	@AreaName VARCHAR(100),
	@AreaAbbName VARCHAR(50),
	@Spell VARCHAR(50),
	@Remark VARCHAR(256),
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
-------------------------------------转换输入参数-------------------------------------------------
DECLARE @Path VARCHAR(50)='', @ParID BIGINT=0,@SonNumTemp INT=0, @Lvl INT=1,@SonNum INT=0, @AreaType BIT=1, @Stt BIT=1
IF(@PAreaNO='') 
BEGIN
	SELECT @ParID=1,@Path='00001',@SonNumTemp=SonNum,@Lvl=1 FROM BD_Area WHERE AreaID=1
END
IF(@ParID<>1)
BEGIN
	IF NOT EXISTS(SELECT AreaNO FROM BD_Area WHERE AreaNO=@PAreaNO)
	BEGIN
		SET @ErrMsg='父级地区编号不存在'
        RETURN -1
	END
	ELSE
	BEGIN
		SELECT @ParID=AreaID,@Path=[Path]+'00001',@SonNumTemp=SonNum,@Lvl=Lvl+1 FROM BD_Area WHERE AreaNO=@PAreaNO
	END
END
IF(@SonNumTemp=0)
BEGIN
	IF( (SELECT COUNT(1) FROM BD_Btype WHERE AreaID=@ParID)>0 )
	BEGIN
		SET @ErrMsg='地区信息在往来单位中被使用'
		RETURN -1;
	END
END
ELSE
BEGIN
	SELECT @Path=[Path] FROM BD_Area WHERE AreaID=(SELECT MAX(AreaID) FROM BD_Area WHERE ParID=@ParID)
	SELECT @Path=dbo.UF_OT_GetLastPath(@Path)
END
IF(@AreaNO='') 
BEGIN
	SET @ErrMsg='地区编号不能为空'
    RETURN -1
END
IF( (SELECT COUNT(1) FROM BD_Area WHERE AreaNO=@AreaNO)>0 )
BEGIN
	SET @ErrMsg='地区编号已存在'
    RETURN -1
END
IF(@AreaName='') 
BEGIN
	SET @ErrMsg='地区名称不能为空'
    RETURN -1
END
IF(@Spell='') 
BEGIN
    SELECT @Spell=dbo.UF_OT_GetPY(@AreaName)
END
-------------------------------------转换输入参数-------------------------------------------------

-------------------------------------插入数据-----------------------------------------------------
INSERT INTO BD_Area
	(AreaNO, AreaName, AreaAbbName, Spell, [Path], ParID, Lvl, SonNum, Stt, AreaType, Remark)
	VALUES  
	(@AreaNO, @AreaName, @AreaAbbName, @Spell, @Path, @ParID, @Lvl, @SonNum, @AreaType, @Stt, @Remark)
-------------------------------------插入数据-----------------------------------------------------
	
-------------------------------------更新父级儿子数-----------------------------------------------
UPDATE BD_Area SET SonNum=(SELECT COUNT(1) FROM BD_Area where ParID=@ParID) WHERE AreaID=@ParID
-------------------------------------更新父级儿子数-----------------------------------------------

END

GO





IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_BD_ImportAtype]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_ImportAtype]
GO
/****** Object:  StoredProcedure [UP_BD_ImportAtype]    Script Date: 12/04/2014 10:55:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/12/04
-- Description:	 财务项目信息导入
-- =============================================
CREATE  PROCEDURE [UP_BD_ImportAtype]
    (
		@ParNO VARCHAR(50),
		@FinanceNO VARCHAR(50),
		@FinanceName VARCHAR(100),
		@Remark VARCHAR(256),
		@UserID INT = 0,
        @ErrMsg VARCHAR(max)='' OUTPUT
    )
AS 
BEGIN
    SET NOCOUNT ON   
	DECLARE @ParID INT, @ExistFinanceID INT, @LoanStt INT, @Lvl INT, @TableName NVARCHAR(2000) = '', @IsAllLimit INT = 0
	IF @ParNO = ''
		BEGIN
			SET @ErrMsg ='上级项目编号不能为空'
			RETURN -1
		END
		
	--查询父级ID
	SELECT @ParID = FinanceID, @LoanStt = LoanStt, @Lvl = Lvl FROM BD_Finance WHERE FinanceNO = @ParNO AND Stt = 1
	
	IF @ParID IS NULL
		BEGIN
			SET @ErrMsg ='上级项目编号不存在或已停用'
			RETURN -1
		END

	SELECT @IsAllLimit = dbo.UF_BD_IsAllAtypeLimit(@UserID)
	
	IF @IsAllLimit = 0 OR 
	  (@IsAllLimit = 1 AND NOT EXISTS (SELECT 1 FROM dbo.UF_BD_AtypeLimit(@UserID) L WHERE L.FinanceID = @ParID))
		BEGIN
			SET @ErrMsg ='无上级项目权限'
			RETURN -1
		END
		
    IF @Lvl = 5
		BEGIN
			SET @ErrMsg ='当前分类最多支持5层'
			RETURN -1
		END
					
	--查询是否是可以新增项目的节点
	DECLARE @NewParID INT
	SELECT @NewParID = FinanceID FROM BD_Finance WHERE FinanceID = @ParID AND Lvl >=2 
				   AND ([Path] LIKE '00001%' OR @ParID = 10 OR @ParID = 13 OR @ParID = 41 OR SysRow = 0)
				   
	IF @NewParID IS NULL
		BEGIN
			SET @ErrMsg ='上级项目禁止新增项目;'
			RETURN -1
		END
	
	--查询是否被使用过	
	DECLARE @Sql NVARCHAR(MAX) = ''
	SELECT  @Sql += ' IF EXISTS(SELECT TOP 1 1 FROM ' + o.[name] + ' WHERE ' + c.name + ' = @ParID) 
						 SET @TableName += ''' + o.[name] + ''''
	FROM    sys.columns c INNER JOIN sys.objects o ON ( c.object_id = o.object_id )
	WHERE   c.name LIKE '%FinanceID' AND o.type = 'u' AND o.name <> 'BD_Finance' AND o.name <> 'PD_ListTable' 
	AND o.name <> 'SS_Finance_Jur' AND o.name <> 'SS_FinanceType_Jur'
	PRINT @Sql
	EXEC sp_executesql @Sql,N'@ParID INT,@TableName NVARCHAR(2000) OUT',@ParID, @TableName OUT
	
	PRINT @TableName
	--网店配置是否使用过
	IF @TableName = '' AND EXISTS(SELECT 1 FROM OS_PostConfig WHERE ConfigName LIKE '%FinanceID' AND ConfigValue = @ParID)
		SET @TableName += 'OS_PostConfig'
	PRINT @TableName
	IF @TableName <> ''
		BEGIN
			SET @ErrMsg = '上级项目已被使用，禁止新增项目'
			RETURN -1
		END
	
	--查询是否有期初数据
	SELECT @ParID = FinanceID FROM BD_Funds WHERE FinanceID = @ParID AND QcBalances = 0		
	
	IF @ParID IS NULL
		BEGIN
			SET @ErrMsg = '上级项目已存在期初数据，禁止新增项目'
			RETURN -1
		END

			
	IF @FinanceNO = ''
		BEGIN
			SET @ErrMsg ='项目编号不能为空;'
			RETURN -1
		END
		
	--查询项目编号是否存在
	SELECT @ExistFinanceID = FinanceID FROM BD_Finance WHERE FinanceNO = @FinanceNO
	
	IF @ExistFinanceID IS NOT NULL
		BEGIN
			SET @ErrMsg ='项目编号已存在;'
			RETURN -1
		END
			
	IF @FinanceName = ''
		BEGIN
			SET @ErrMsg ='项目名称不能为空;'
			RETURN -1
		END
		
	--查询项目名称是否存在
	SELECT @ExistFinanceID = FinanceID FROM BD_Finance WHERE FinanceName = @FinanceName
	IF @ExistFinanceID IS NOT NULL
		BEGIN
			SET @ErrMsg ='项目名称已存在;'
			RETURN -1
		END
	
    --得到分类的PATH
	DECLARE @MaxSonPath NUMERIC(25,0), @Path NVARCHAR(25), @allPath VARCHAR(25)='00000' 
	SELECT @MaxSonPath = CAST(RIGHT(MAX([PATH]),5) AS NUMERIC(10,0))+1, @Lvl = MAX(lvl) FROM BD_Finance WHERE ParID = @ParID
	IF(@MaxSonPath IS NULL) 
	  SELECT @Path=([PATH]+'00001'),@Lvl = lvl+1 FROM BD_Finance WHERE FinanceID = @ParID 
	ELSE 
	BEGIN 
	  SET @Path=LEFT(@allpath,5-LEN(@MaxSonPath))+CAST(@MaxSonPath AS VARCHAR(max)) 
	  SELECT @Path=[PATH]+ @Path FROM BD_Finance WHERE FinanceID = @ParID 	 
	END
    
	SET XACT_ABORT ON
    BEGIN TRAN T
		BEGIN 	    	
			INSERT INTO [BD_Finance]
				   ([FinanceNO]
				   ,[FinanceName]
				   ,[Path]
				   ,[ParID]
				   ,[Lvl]
				   ,[SonNum]
				   ,[LoanStt]
				   ,[Remark])
			 VALUES
				   (@FinanceNO
				   ,@FinanceName
				   ,@Path
				   ,@ParID
				   ,@Lvl
				   ,0
				   ,@LoanStt
				   ,@Remark) --新增项目
			 UPDATE BD_Finance SET Sonnum = Sonnum + 1 WHERE FinanceID = @ParID; --更新上级项目子节点数
		 END
	 COMMIT TRAN T 
END
GO





/****** Object:  StoredProcedure [UP_BD_ImportBType]    Script Date: 12/04/2014 10:04:00 ******/IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportBType]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportBType]
GO

/****** Object:  StoredProcedure [UP_BD_ImportBType]    Script Date: 12/04/2014 10:04:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-04
	描述：往来单位导入
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportBType]
(			   
	@BtypeTypeCode VARCHAR(50),
	@BTypeCode VARCHAR(50),
	@BTypeName VARCHAR(100),
	@BtypeAbbName VARCHAR(50),
	@AreaNO VARCHAR(50),
	@Spell VARCHAR(50),
	@TaxNo VARCHAR(50),
	@LinkMan VARCHAR(50),
	@Tel VARCHAR(50),
	@MTel VARCHAR(50),
	@Email VARCHAR(50),
	@PriceLvl TINYINT,
	@Adress VARCHAR(100),
	@Bank VARCHAR(50),
	@BankAcntNo VARCHAR(50),
	@Remark VARCHAR(256),
	@UserID INT=0,				--操作员ID
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
-------------------------------------转换输入参数-------------------------------------------------
DECLARE @BtypeTypeID BIGINT=0, @AreaID BIGINT=0, @Stt BIT=1, @IsBtypeLimit INT=0
SELECT @IsBtypeLimit=dbo.UF_BD_IsAllBtypeLimit(@UserID)
IF @IsBtypeLimit=0
BEGIN
	SET @ErrMsg ='无权限'
	RETURN -1
END
IF @IsBtypeLimit=1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM dbo.UF_BD_BtypeTypeLimit(2) 
			WHERE LimitTag=1 AND BtypeTypeID IN (
				SELECT BtypeTypeID FROM BD_Btype_Type WHERE TypeCode=@BtypeTypeCode
			)
		)
	BEGIN
		SET @ErrMsg ='该类型编号下禁止新增往来单位'
		RETURN -1
	END
END
IF(@BtypeTypeCode='') 
BEGIN
	SET @ErrMsg='类型编号不能为空'
    RETURN -1
END
IF NOT EXISTS(SELECT TypeCode FROM BD_Btype_Type WHERE TypeCode=@BtypeTypeCode)
BEGIN
	SET @ErrMsg='类型编号不存在'
    RETURN -1
END
SELECT @BtypeTypeID=BtypeTypeID FROM BD_Btype_Type WHERE TypeCode=@BtypeTypeCode AND SonNum=0
IF(@BtypeTypeID=0)
BEGIN
	SET @ErrMsg='类型编号不是最末级类型'
    RETURN -1
END
IF(@BTypeCode='') 
BEGIN
	SET @ErrMsg='往来单位编号不能为空'
    RETURN -1
END
IF( (SELECT COUNT(1) FROM BD_BType WHERE BTypeCode=@BTypeCode)>0 )
BEGIN
	SET @ErrMsg='往来单位编号已存在'
    RETURN -1
END
IF(@BTypeName='') 
BEGIN
	SET @ErrMsg='往来单位名称不能为空'
    RETURN -1
END
IF(@AreaNO!='')
BEGIN
	IF NOT EXISTS(SELECT AreaNO FROM BD_Area WHERE AreaNO=@AreaNO)
	BEGIN
		SET @ErrMsg='所属地区编号不存在'
		RETURN -1
	END
	SELECT @AreaID=AreaID FROM BD_Area WHERE AreaNO=@AreaNO AND SonNum=0
	IF(@AreaID='')
	BEGIN
		SET @ErrMsg='所属地区编号不是最末级类型'
		RETURN -1
	END
END
IF(@PriceLvl='' OR @PriceLvl IS NULL)
	SET @PriceLvl=1
IF( @PriceLvl NOT IN (1,2,3,4,5) )
BEGIN
	SET @ErrMsg='预设价不是1,2,3,4,5'
    RETURN -1
END
IF(@Spell='') 
BEGIN
    SELECT @Spell=dbo.UF_OT_GetPY(@BTypeName)
END
-------------------------------------转换输入参数-------------------------------------------------

-------------------------------------插入数据-----------------------------------------------------
INSERT INTO BD_BType
	(BTypeCode, BTypeName, BtypeAbbName, Spell, BtypeTypeID, AreaID, PriceLvl, LinkMan, Tel, MTel, Email, Adress, Bank, BankAcntNo, TaxNo, Stt, Remark)
	VALUES  
	(@BTypeCode, @BTypeName, @BtypeAbbName, @Spell, @BtypeTypeID, @AreaID, @PriceLvl, @LinkMan, @Tel, @MTel, @Email, @Adress, @Bank, @BankAcntNo, @TaxNo, @Stt, @Remark)
-------------------------------------插入数据-----------------------------------------------------

END

GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportBtypePtype]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportBtypePtype
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：Hanlin
	时间：2014-11-24
	描述：商品导入
*/
CREATE  PROCEDURE UP_BD_ImportBtypePtype
    (
      @BTypeCode [VARCHAR](50) ,
      @GoodsNo [varchar](50) ,
      @GoodsNoByUser [varchar](50) ,
      @ErrMsg VARCHAR(max)='' OUTPUT
    )
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @dbname [varchar](30) = 'BD_Goods'

    DECLARE @BtypeID INT
    DECLARE @GoodsID INT
    IF ( @BTypeCode = '' ) 
    BEGIN
        SET @ErrMsg = '往来单位编号不能为空'
        RETURN -1
    END
    ELSE 
    BEGIN
        IF NOT EXISTS ( SELECT  BTypeID
                        FROM    BD_Btype
                        WHERE   BTypeCode = @BTypeCode ) 
        BEGIN
            SET @ErrMsg = '往来单位编号不存在'
            RETURN -1
        END
        ELSE 			
			SET @BtypeID = ( SELECT TOP 1
									BTypeID
						   FROM     BD_Btype
						   WHERE    BTypeCode = @BTypeCode
						 )
	END
	IF ( @GoodsNo = '' ) 
    BEGIN
        SET @ErrMsg = '商品编号不能为空'
        RETURN -1
    END
    ELSE 
    BEGIN
        IF NOT EXISTS ( SELECT  GoodsID
                        FROM    BD_Goods
                        WHERE   GoodsNo = @GoodsNo ) 
        BEGIN
            SET @ErrMsg = '商品编号不存在'
            RETURN -1
        END
        ELSE 			
			SET @GoodsID = ( SELECT TOP 1
									GoodsID
						   FROM     BD_Goods
						   WHERE    GoodsNo = @GoodsNo
						 )
	END	
	IF ( @GoodsNoByUser = '' ) 
    BEGIN
        SET @ErrMsg = '自定义编号不能为空'
        RETURN -1
    END
    ELSE
		IF ((SELECT COUNT(1) FROM BD_Goods_NO WHERE GoodsNO = @GoodsNoByUser AND BTypeID = @BtypeID) > 0)
		BEGIN 
			SET @ErrMsg = '自定义编号设置重复'
			RETURN -1
		END
	
	IF((SELECT COUNT(1) FROM BD_Goods_NO WHERE GoodsID = @GoodsID AND BTypeID = @BtypeID) > 0)
	BEGIN 
		UPDATE BD_Goods_NO SET GoodsNO = @GoodsNoByUser WHERE GoodsID=@GoodsID AND BTypeID = @BtypeID
	END
	ELSE
		INSERT INTO BD_Goods_NO(GoodsID,BTypeID,GoodsNO) VALUES(@GoodsID,@BtypeID,@GoodsNoByUser)
    

GO





/****** Object:  StoredProcedure [UP_BD_ImportDept]    Script Date: 12/04/2014 10:04:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportDept]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportDept]
GO

/****** Object:  StoredProcedure [UP_BD_ImportDept]    Script Date: 12/04/2014 10:04:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-04
	描述：部门导入
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportDept]
(			   
	@PDeptCode VARCHAR(50),
	@DeptCode VARCHAR(50),
	@DeptName VARCHAR(100),
	@DeptAbbName VARCHAR(50),
	@Spell VARCHAR(50),
	@Remark VARCHAR(256),
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
IF OBJECT_ID('tempdb..#tempDept','U') IS NOT NULL DROP TABLE #tempDept
-------------------------------------转换输入参数-------------------------------------------------
DECLARE @Path VARCHAR(50)='', @ParID BIGINT=0,@SonNumTemp INT=0, @Lvl INT=0, @SonNum INT=0, @Stt BIT=1
IF(@PDeptCode='') 
BEGIN
	SELECT @ParID=1,@Path='00001',@SonNumTemp=SonNum,@Lvl=1 FROM BD_Dept WHERE DeptID=1
END
IF(@ParID<>1)
BEGIN
	IF NOT EXISTS(SELECT DeptCode FROM BD_Dept WHERE DeptCode=@PDeptCode)
	BEGIN
		SET @ErrMsg='父级部门编号不存在'
        RETURN -1
	END
	ELSE
	BEGIN
		SELECT @ParID=DeptID,@Path=[Path]+'00001',@SonNumTemp=SonNum,@Lvl=Lvl+1 FROM BD_Dept WHERE DeptCode=@PDeptCode
	END
END
IF(@SonNumTemp=0)
BEGIN
	CREATE TABLE #tempDept(tempStr VARCHAR(100))
	INSERT INTO #tempDept EXEC dbo.UP_BD_CheckUsed @ParID, 0, 'D'
	SELECT @ErrMsg=tempStr FROM #tempDept
	DROP TABLE #tempDept
	IF(@ErrMsg!='')
	BEGIN
		SET @ErrMsg='部门信息在'+@ErrMsg+'中被使用'
		RETURN -1;
	END
END
ELSE
BEGIN
	SELECT @Path=[Path] FROM BD_Dept WHERE DeptID=(SELECT MAX(DeptID) FROM BD_Dept WHERE ParID=@ParID)
	SELECT @Path=dbo.UF_OT_GetLastPath(@Path)
END
IF(@DeptCode='') 
BEGIN
	SET @ErrMsg='部门编号不能为空'
    RETURN -1
END
IF( (SELECT COUNT(1) FROM BD_Dept WHERE DeptCode=@DeptCode)>0 )
BEGIN
	SET @ErrMsg='部门编号已存在'
    RETURN -1
END
IF(@DeptName='') 
BEGIN
	SET @ErrMsg='部门名称不能为空'
    RETURN -1
END

IF(@Spell='') 
BEGIN
    SELECT @Spell=dbo.UF_OT_GetPY(@DeptName)
END

-------------------------------------转换输入参数-------------------------------------------------

-------------------------------------插入数据-----------------------------------------------------
INSERT INTO BD_Dept
	(DeptCode, DeptName, DeptAbbName, Spell, [Path], ParID, Lvl, SonNum, Stt, Remark)
	VALUES  
	(@DeptCode, @DeptName, @DeptAbbName, @Spell, @Path, @ParID, @Lvl, @SonNum, @Stt, @Remark)
-------------------------------------插入数据-----------------------------------------------------

-------------------------------------更新父级儿子数-----------------------------------------------
UPDATE BD_Dept SET SonNum=(SELECT COUNT(1) FROM BD_Dept where ParID=@ParID) WHERE DeptID=@ParID
-------------------------------------更新父级儿子数-----------------------------------------------

END

GO





IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_BD_ImportEtype]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_ImportEtype]
GO
/****** Object:  StoredProcedure [UP_BD_ImportEtype]    Script Date: 12/04/2014 10:40:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/12/04
-- Description:	 职员信息导入
-- =============================================
CREATE  PROCEDURE [UP_BD_ImportEtype]
    (
		@DeptCode VARCHAR(50),
		@ElyCode VARCHAR(20),
		@ElyName VARCHAR(50),
		@Spell VARCHAR(20),
		@MTel VARCHAR(20),
		@Tel VARCHAR(20),
		@QQ VARCHAR(20),
		@Email VARCHAR(50),
		@Remark VARCHAR(256),
		@ErrMsg VARCHAR(max)='' OUTPUT
    )
AS

BEGIN
    SET NOCOUNT ON   
	DECLARE @DeptId INT, @SonNum INT, @ExistElyID INT		
	IF @DeptCode = ''
		BEGIN
			SET @ErrMsg = '部门编号不能为空'
			RETURN -1
		END
		
	--查询部门及子节点数
	SELECT @DeptId = DeptId, @SonNum = SonNum FROM BD_Dept WHERE DeptCode = @DeptCode AND Stt = 1
	
	IF @DeptId IS NULL
		BEGIN
			SET @ErrMsg = '部门编号不存在或已停用'
			RETURN -1
		END
				
	IF @SonNum > 0
		BEGIN
			SET @ErrMsg = '该部门不能新建职员'
			RETURN -1
		END
			
	IF @ElyCode = ''
		BEGIN
			SET @ErrMsg = '职员编号不能为空'
			RETURN -1
		END
		
	--查询职员编号是否存在
	SELECT @ExistElyID = ElyID FROM BD_Employee WHERE ElyCode = @ElyCode
	
	IF @ExistElyID IS NOT NULL
		BEGIN
			SET @ErrMsg = '职员编号已存在'
			RETURN -1
		END
			
	IF @ElyName = ''
		BEGIN
			SET @ErrMsg = '职员名称不能为空'
			RETURN -1
		END
		
    INSERT INTO [BD_Employee]
           ([ElyCode]
           ,[ElyName]
           ,[Spell]
           ,[Tel]
           ,[MTel]
           ,[Email]
           ,[QQ]
           ,[DeptId]
           ,[Remark])
     VALUES
           (@ElyCode
           ,@ElyName
           ,@Spell
           ,@Tel
           ,@MTel
           ,@Email
           ,@QQ
           ,@DeptId
           ,@Remark)
END
GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportGoodsRelation]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportGoodsRelation
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：leiyang
	时间：2015-04-01
	描述：商品导入
*/
CREATE  PROCEDURE UP_BD_ImportGoodsRelation
    (
      @title [VARCHAR](100) ,
      @Pskus [varchar](100) ,
      @SuiteCode [varchar](50) ,
      @goodsno [varchar](50) ,
      @Ppt1Name [varchar](10) ,
      @Ppt2Name [varchar](10) ,
      @Unit [varchar](10) ,
      @UserID Int = 0,
      @ErrMsg VARCHAR(max)='' OUTPUT
    )
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @GoodsID INT
    DECLARE @Ppt1ID INT = 0
    DECLARE @Ppt2ID INT = 0
    DECLARE @UnitID Int = 1
    DECLARE @MerchantCode [varchar](100)
	IF( @SuiteCode = '')
	BEGIN
		IF ( @GoodsNo = '' ) 
			BEGIN
				SET @ErrMsg = '套餐编号或商品编号不能为空'
				RETURN -1
			END
		ELSE 
			IF ( ( SELECT   COUNT(1)
				   FROM     BD_Goods
				   WHERE    GoodsNo = @GoodsNo
				 ) > 0 ) 
				BEGIN
					IF(( SELECT   COUNT(1) FROM  BD_Goods  WHERE GoodsNo = @GoodsNo AND Stt = 1) > 0 )
					BEGIN
						IF(( SELECT   COUNT(1) FROM  BD_Goods  WHERE GoodsNo = @GoodsNo AND IsOS = 1) > 0 )
						BEGIN
							Select @GoodsID = GoodsID from BD_Goods where GoodsNo = @goodsno 
						END
						ELSE
						BEGIN
							SET @ErrMsg = '商品不是网店商品'
							RETURN -1
						END
					END
					ELSE
					BEGIN
						SET @ErrMsg = '商品已经被停用'
						RETURN -1
					END
				END
			 Else
			 Begin
				SET @ErrMsg = '商品不存在'
				RETURN -1
			 ENd

		IF ( @Ppt1Name <> '')
		Begin
			IF NOT EXISTS ( select ppt1.Ppt1ID from BD_Goods A Inner Join  BD_Goods_PptGroup B on a.PptGroupID = b.PptGroupID 
	inner join BD_Goods_Ppt1 ppt1 on b.Ppt1ID = ppt1.Ppt1ID where Value = @Ppt1Name and a.GoodsID = @GoodsID) 
			BEGIN
				SET @ErrMsg = '商品无此颜色属性'
				RETURN -1
			END
			ELSE
			BEGIN
				SET @Ppt1ID = (Select Top 1 ppt1.Ppt1ID from BD_Goods A Inner Join  BD_Goods_PptGroup B on a.PptGroupID = b.PptGroupID 
	inner join BD_Goods_Ppt1 ppt1 on b.Ppt1ID = ppt1.Ppt1ID where Value = @Ppt1Name and a.GoodsID = @GoodsID )
			END
		End
		else
			select @Ppt1ID = 0
		IF ( @Ppt2Name <> '')
		Begin
			IF NOT EXISTS ( select ppt2.Ppt2ID from BD_Goods A Inner Join  BD_Goods_PptGroup B on a.PptGroupID = b.PptGroupID 
	inner join BD_Goods_Ppt2 ppt2 on b.Ppt2ID = ppt2.Ppt2ID where Value = @Ppt2Name and a.GoodsID = @GoodsID) 
			BEGIN
				SET @ErrMsg = '商品无此尺码属性'
				RETURN -1
			END
			ELSE
			BEGIN
				SET @Ppt2ID = (Select Top 1 ppt2.Ppt2ID from BD_Goods A Inner Join  BD_Goods_PptGroup B on a.PptGroupID = b.PptGroupID 
	inner join BD_Goods_Ppt2 ppt2 on b.Ppt2ID = ppt2.Ppt2ID where Value = @Ppt2Name and a.GoodsID = @GoodsID)
			END
		End
		else
			select @Ppt2ID = 0
	    
		IF(@Unit <> '')
		BEGIN
			IF NOT EXISTS( select unitid from BD_Goods A Inner Join BD_Goods_Price B on a.GoodsID = b.GoodsID where a.GoodsID = @GoodsID and b.Unit = @Unit) 
				 BEGIN
					SET @ErrMsg = '单位名称不存在'
					RETURN -1
				 END
			Else 
			Begin
				Set @UnitID = (select top 1 unitid from BD_Goods A Inner Join BD_Goods_Price B on a.GoodsID = b.GoodsID where a.GoodsID = @GoodsID and b.Unit = @Unit)
			END
		END
		Else
		Begin
			select @UnitID = 1
		End
	    
		Set @MerchantCode = Cast(@GoodsID as varchar(20)) + '_' + Cast(@Ppt1ID as varchar(20)) + '_' + Cast(@Ppt2ID as varchar(20)) + '_' + Cast(@UnitID as varchar(20))
		if(not exists(select id from OS_GoodsRelation where MerchantCode = @MerchantCode))
		BEGIN
			SET @ErrMsg = '商品属性组合错误'
			RETURN -1
		END
		
		if not exists (select ImportID from OS_GoodsRelation_Import where MerchantCode = @MerchantCode AND ElyID=@UserID and OSGoodsName = @title and OSGoodsPpt = @Pskus)
		BEGIN
			INSERT INTO DBO.OS_GoodsRelation_Import
			(   OSGoodsName,
				OSGoodsPpt,
				GoodsID,
				Ppt1ID,
				Ppt2ID,
				UnitID,
				MerchantCode,
				ElyID
			)
			VALUES
			( @title,
			  @Pskus,
			  @GoodsID,
			  @Ppt1ID,
			  @Ppt2ID,
			  @UnitID,
			  @MerchantCode,
			  @UserID
			)
		END
	END
	ELSE
	BEGIN
		IF ( ( SELECT   COUNT(1)
				   FROM     OS_GoodsSuite
				   WHERE    SuiteCode = @SuiteCode
				 ) > 0 ) 
		BEgin
			if not exists (select ImportID from OS_GoodsRelation_Import where MerchantCode = @SuiteCode AND ElyID=@UserID and OSGoodsName = @title and OSGoodsPpt = @Pskus)
			BEGIN
				INSERT INTO DBO.OS_GoodsRelation_Import
				(   OSGoodsName,
					OSGoodsPpt,
					GoodsID,
					Ppt1ID,
					Ppt2ID,
					UnitID,
					MerchantCode,
					ElyID,
					[SuiteCode]
				)
				VALUES
				( @title,
				  @Pskus,
				  0,
				  @Ppt1ID,
				  @Ppt2ID,
				  @UnitID,
				  @SuiteCode,
				  @UserID,
				  @SuiteCode
				)
			END
		END
		ELSE
		BEGIN
			SET @ErrMsg = '商品套餐不存在'
			RETURN -1
		END
	END
	
GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportGoodsRelation_NoPpt]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportGoodsRelation_NoPpt
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：leiyang
	时间：2015-04-01
	描述：商品导入
*/
CREATE  PROCEDURE UP_BD_ImportGoodsRelation_NoPpt
    (
      @title [VARCHAR](100) ,
      @Pskus [varchar](100) ,
      @SuiteCode [varchar](50) ,
      @goodsno [varchar](50) ,
      @UserID Int = 0,
      @ErrMsg VARCHAR(max)='' OUTPUT
    )
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @GoodsID INT
    DECLARE @Ppt1ID INT = 0
    DECLARE @Ppt2ID INT = 0
    DECLARE @UnitID Int = 1
    DECLARE @MerchantCode [varchar](100)
	IF(@SuiteCode = '')
	BEGIN
		IF ( @GoodsNo = '' ) 
			BEGIN
				SET @ErrMsg = '商品编号不能为空'
				RETURN -1
			END
		ELSE 
			IF ( ( SELECT   COUNT(1)
				   FROM     BD_Goods
				   WHERE    GoodsNo = @GoodsNo
				 ) > 0 ) 
				BEGIN
					IF(( SELECT   COUNT(1) FROM  BD_Goods  WHERE GoodsNo = @GoodsNo AND Stt = 1) > 0 )
					BEGIN
						IF(( SELECT   COUNT(1) FROM  BD_Goods  WHERE GoodsNo = @GoodsNo AND IsOS = 1) > 0 )
						BEGIN
							Select @GoodsID = GoodsID from BD_Goods where GoodsNo = @goodsno 
						END
						ELSE
						BEGIN
							SET @ErrMsg = '商品不是网店商品'
							RETURN -1
						END
					END
					ELSE
					BEGIN
						SET @ErrMsg = '商品已经被停用'
						RETURN -1
					END
				END
			 Else
			 Begin
				SET @ErrMsg = '商品不存在'
				RETURN -1
			 ENd
	    
		Set @MerchantCode = @GoodsNo
		
		if not exists (select ImportID from OS_GoodsRelation_Import where MerchantCode = @MerchantCode AND ElyID=@UserID and OSGoodsName = @title and OSGoodsPpt = @Pskus)
		BEGIN
			INSERT INTO DBO.OS_GoodsRelation_Import
			(   OSGoodsName,
				OSGoodsPpt,
				GoodsID,
				Ppt1ID,
				Ppt2ID,
				UnitID,
				MerchantCode,
				ElyID
			)
			VALUES
			( @title,
			  @Pskus,
			  @GoodsID,
			  @Ppt1ID,
			  @Ppt2ID,
			  @UnitID,
			  @MerchantCode,
			  @UserID
			)
		END
	END
	ELSE
	BEGIN
		IF ( ( SELECT   COUNT(1)
				   FROM     OS_GoodsSuite
				   WHERE    SuiteCode = @SuiteCode
				 ) > 0 ) 
		BEgin
			if not exists (select ImportID from OS_GoodsRelation_Import where MerchantCode = @SuiteCode AND ElyID=@UserID and OSGoodsName = @title and OSGoodsPpt = @Pskus)
			BEGIN
				INSERT INTO DBO.OS_GoodsRelation_Import
				(   OSGoodsName,
					OSGoodsPpt,
					GoodsID,
					Ppt1ID,
					Ppt2ID,
					UnitID,
					MerchantCode,
					ElyID,
					[SuiteCode]
				)
				VALUES
				( @title,
				  @Pskus,
				  0,
				  @Ppt1ID,
				  @Ppt2ID,
				  @UnitID,
				  @SuiteCode,
				  @UserID,
				  @SuiteCode
				)
			END
		END
		ELSE
		BEGIN
			SET @ErrMsg = '商品套餐不存在'
			RETURN -1
		END
	END
	
GO





IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_BD_ImportKtype]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_ImportKtype]
GO
/****** Object:  StoredProcedure [UP_BD_ImportKtype]    Script Date: 12/04/2014 10:23:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/12/04
-- Description:	 仓库信息导入
-- =============================================
CREATE  PROCEDURE [UP_BD_ImportKtype]
    (
		@WhsTypeCode VARCHAR(50),
		@WhsNO VARCHAR(50),
		@WhsName VARCHAR(100),
		@WhsAbbName VARCHAR(50),
		@Spell VARCHAR(50),
		@PostCode VARCHAR(10),
		@LinkMan VARCHAR(20),
		@Tel VARCHAR(20),
		@Address VARCHAR(100),
		@Remark VARCHAR(256),
		@UserID INT = 0,
        @ErrMsg VARCHAR(max)='' OUTPUT
    )
AS 

BEGIN
    SET NOCOUNT ON   
	DECLARE @WhsTypeID INT, @SonNum INT, @ExistWhsID INT, @NewWhsID INT, @IsAllLimit INT = 0	
	
	IF @WhsTypeCode = ''
		BEGIN
			SET @ErrMsg ='类型编码不能为空'
			RETURN -1
		END

	--查询仓库分类ID及子节点数
	SELECT @WhsTypeID = WhsTypeID, @SonNum = SonNum FROM BD_Whs_Type WHERE TypeCode = @WhsTypeCode AND Stt = 1
	
	IF @WhsTypeID IS NULL
		BEGIN
			SET @ErrMsg ='类型编码不存在或已停用'
			RETURN -1
		END

	SELECT @IsAllLimit = dbo.UF_BD_IsAllKtypeLimit(@UserID)
	
	IF @IsAllLimit = 0 OR 
	  (@IsAllLimit = 1 AND NOT EXISTS (SELECT 1 FROM UF_BD_KtypeTypeLimit(@UserID) L WHERE L.WhsTypeID = @WhsTypeID AND LimitTag = 1))
		BEGIN
			SET @ErrMsg ='无仓库分类权限'
			RETURN -1
		END
		
	IF @SonNum > 0
		BEGIN
			SET @ErrMsg ='该仓库分类不能新建仓库'
			RETURN -1
		END
			
	IF @WhsNO = ''
		BEGIN
			SET @ErrMsg ='仓库编号不能为空'
			RETURN -1
		END
	
	--查询仓库编号是否存在
	SELECT @ExistWhsID = WhsID FROM BD_Whs WHERE WhsNO = @WhsNO
		
	IF @ExistWhsID IS NOT NULL
		BEGIN
			SET @ErrMsg ='仓库编号已存在'
			RETURN -1
		END
			
	IF @WhsName = ''
		BEGIN
			SET @ErrMsg ='仓库名称不能为空'
			RETURN -1
		END
	
    
	SET XACT_ABORT ON
    BEGIN TRAN T
		BEGIN 	    	
			INSERT INTO [BD_Whs]
				   ([WhsNO]
				   ,[WhsName]
				   ,[WhsAbbName]
				   ,[Spell]
				   ,[WhsTypeID]
				   ,[LinkMan]
				   ,[Tel]
				   ,[Address]
				   ,[PostCode]
				   ,[Remark])
			 VALUES
				   (@WhsNO
				   ,@WhsName
				   ,@WhsAbbName
				   ,@Spell
				   ,@WhsTypeID
				   ,@LinkMan
				   ,@Tel
				   ,@Address
				   ,@PostCode
				   ,@Remark) --新增仓库
			SELECT @NewWhsID = @@IDENTITY 
			INSERT INTO [BD_Whs_Position]
				   ([WhsPtNO]
				   ,[WhsPtName]
				   ,[WhsID]
				   ,[WhsPtType]
				   ,[Remark])
			 VALUES
				   (@WhsNO+'MRHW'
				   ,@WhsName+'默认货位'
				   ,@NewWhsID
				   ,1
				   ,@Remark) --新增仓库默认货位
		END
	 COMMIT TRAN T 
END
GO





IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_BD_ImportMacAddr]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_ImportMacAddr]
GO
/****** Object:  StoredProcedure [UP_BD_ImportMacAddr]    Script Date: 1/29/2015 17:56:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/1/29
-- Description:	 Mac地址导入
-- =============================================
CREATE  PROCEDURE [UP_BD_ImportMacAddr]
    (
		@MacAddr VARCHAR(50) = '',
		@Remark VARCHAR(256) = '',
		@UserID INT = 0,
        @ErrMsg VARCHAR(max)='' OUTPUT
    )
AS 

BEGIN
    SET NOCOUNT ON   
	DECLARE @ID INT	= 0
	
	IF @MacAddr = ''
		BEGIN
			SET @ErrMsg ='Mac地址不能为空'
			RETURN -1
		END

	--查询是否存在该Mac地址
	SELECT @ID = ID FROM SS_MacAddr_Jur WHERE MacAddr = @MacAddr
	
	IF @ID <> 0
		BEGIN
			SET @ErrMsg ='Mac地址已存在'
			RETURN -1
		END    	
		
	INSERT INTO [SS_MacAddr_Jur]
           ([MacAddr]
           ,[Remark]
           ,[Creator])
     VALUES
           (@MacAddr
           ,@Remark
           ,@UserID) --新增Mac地址
END
GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportOpeningARAP]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportOpeningARAP
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：Hanlin
	时间：2014-11-24
	描述：期初应收应付导入
*/
CREATE  PROCEDURE UP_BD_ImportOpeningARAP
(
	@BTypeCode VARCHAR(100),
	@ArTotal VARCHAR(20),
    @ApTotal VARCHAR(20) ,
    @BrTotal VARCHAR(20) ,
    @BpTotal VARCHAR(20),
    @ErrMsg VARCHAR(max)='' OUTPUT
)
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @BTypeID INT=0,@ArValue DECIMAL(20,8),@ApValue DECIMAL(20,8),@BrValue DECIMAL(20,8),@BpValue DECIMAL(20,8)
	SET @ArValue=CASE @ArTotal WHEN '' THEN 0 ELSE CAST(@ArTotal AS DECIMAL(14,2)) END
	SET @ApValue=CASE @ApTotal WHEN '' THEN 0 ELSE CAST(@ApTotal AS DECIMAL(14,2)) END	
	SET @BrValue=CASE @BrTotal WHEN '' THEN 0 ELSE CAST(@BrTotal AS DECIMAL(14,2)) END
	SET @BpValue=CASE @BpTotal WHEN '' THEN 0 ELSE CAST(@BpTotal AS DECIMAL(14,2)) END
	
    IF ( @BTypeCode = '' ) 
        BEGIN
            SET @ErrMsg = '往来单位编号不能为空'
            RETURN -1
        END
    ELSE
		SELECT @BTypeID=BTypeID FROM BD_Btype WHERE BTypeCode=@BTypeCode
		
	IF @BTypeID=0
	BEGIN
        SET @ErrMsg = '往来单位编号不存在'
        RETURN -1
    END
    
    DELETE FROM BD_ARAP WHERE BTypeID=@BTypeID
    
    IF(@ArValue=0 AND @ApValue=0 AND @BrValue=0 AND @BpValue=0)
		RETURN
	ELSE
		INSERT INTO BD_ARAP
		        ( BTypeID ,
		          QcAR ,
		          QcAP ,
		          QcBR ,
		          QcBP 
		        )
		VALUES  ( @BTypeID ,
				  @ArValue,
				  @ApValue,
				  @BrValue,
				  @BpValue			        
		        )

GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportOpeningFinance]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportOpeningFinance
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：Hanlin
	时间：2014-11-24
	描述：期初财务导入
*/
CREATE  PROCEDURE UP_BD_ImportOpeningFinance
(
	@FinanceNO VARCHAR(100),
	@QcBalance NUMERIC(20,8) ,
    @Type INT=1,
    @ErrMsg VARCHAR(max)='' OUTPUT    
)
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @FinanceID INT=0,@TotalDit INT=2,@path VARCHAR(50),@Sonnum INT=0
	SET @QcBalance=ROUND(@QcBalance,@TotalDit)
    IF ( @FinanceNO = '' ) 
        BEGIN
            SET @ErrMsg = '项目编号不能为空'
            RETURN -1
        END
    ELSE
		SELECT @FinanceID=FinanceID,@path=Path,@Sonnum=SonNum FROM BD_Finance WHERE FinanceNO=@FinanceNO
		
	IF @FinanceID=0
	BEGIN
        SET @ErrMsg = '项目编号不存在'
        RETURN -1
    END
    
    IF @Type=1 AND @path NOT LIKE '00001%'
	BEGIN
        SET @ErrMsg = '项目不是现金银行类项目'
        RETURN -1
    END
    
    IF @Type=0 AND @path NOT LIKE '00002%' AND @path NOT LIKE '00003%'
	BEGIN
        SET @ErrMsg = '项目不是收入支出类项目'
        RETURN -1
    END
    
    IF @Sonnum<>0
	BEGIN
        SET @ErrMsg = '项目不是最末级项目'
        RETURN -1
    END

    IF EXISTS(SELECT 1 FROM BD_Funds WHERE FinanceID=@FinanceID)
		UPDATE BD_Funds SET QcBalances= @QcBalance WHERE FinanceID=@FinanceID
	ELSE
		INSERT INTO BD_Funds
		        ( FinanceID, QcBalances, QmBalances )
		VALUES  ( @FinanceID, @QcBalance,0)
		
GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportOpeningGoodsSerial]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportOpeningGoodsSerial
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：Hanlin
	时间：2014-11-24
	描述：期初库存商品导入
*/
CREATE  PROCEDURE UP_BD_ImportOpeningGoodsSerial
(
	@KUserCode VARCHAR(100),
	@PtUserCode [VARCHAR](100) ,
    @PUserCode [VARCHAR](100) ,
	@Ppt1Name VARCHAR(50),
	@Ppt2Name VARCHAR(50),
	@BatchNumber NVARCHAR(50),        -- 批号
	@ProductDate NVARCHAR(50),        -- 生产日期
	@EndDate NVARCHAR(50),            -- 到期日期
	@Price DECIMAL(20,8),
	@Qty DECIMAL(20,8),
    @ErrMsg VARCHAR(max)='' OUTPUT,
    @StockDetailID INT=0 OUTPUT
)
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @HasWhsPt INT=1,@PriceDit INT=8,@QtyDit INT=4,@TotalDit INT=2,@WhsID INT=0,@GoodsID INT=0,@WhsPtID INT=0,@Ppt1ID INT=0,@Ppt2ID INT=0,@PptGroupID INT=0
    DECLARE @CostMethod INT = 1
    SELECT @HasWhsPt=CfgValue  FROM SS_SysCfg WHERE CfgName='HasWhsPt'
    IF ( @KUserCode = '' ) 
        BEGIN
            SET @ErrMsg = '仓库编号不能为空'
            RETURN -1
        END
    ELSE
		SELECT @WhsID=WhsID FROM BD_Whs WHERE WhsNO=@KUserCode
		
	IF @WhsID=0
	BEGIN
        SET @ErrMsg = '仓库编号不存在'
        RETURN -1
    END
    
    IF @HasWhsPt=1 
    BEGIN
		IF @PtUserCode = '' 
        BEGIN
            SET @ErrMsg = '货位编号不能为空'
            RETURN -1
        END
        ELSE 
			SELECT @WhsPtID=WhsPtID FROM BD_Whs_Position p WHERE WhsID=@WhsID AND WhsPtNO=@PtUserCode
			
        IF @WhsPtID=0
		BEGIN
			SET @ErrMsg = '货位编号不存在或者与仓库不匹配'
			RETURN -1
		END
    END
    ELSE
    BEGIN
		IF @PtUserCode <> '' 
        BEGIN
            SET @ErrMsg = '没有启用货位，请不要填写货位'
            RETURN -1
        END
		SELECT @WhsPtID=WhsPtID FROM BD_Whs_Position WHERE WhsID=@WhsID AND WhsPtType=1
	END
		
    IF ( @PUserCode = '' ) 
    BEGIN
        SET @ErrMsg = '商品编号不能为空'
        RETURN -1
    END
    ELSE 
		SELECT @GoodsID=GoodsID,@CostMethod=CostMethod FROM  BD_Goods  WHERE    GoodsNo = @PUserCode
		
    IF @GoodsID=0
    BEGIN
        SET @ErrMsg = '商品编号不存在'
        RETURN -1
    END
	IF NOT EXISTS(SELECT 1 FROM dbo.BD_Goods WHERE IsSerial=1 AND GoodsID=@GoodsID)
	BEGIN
		SET @ErrMsg = '非序列号商品不能导入序列号'
		RETURN -1
	END
	
	SELECT @PptGroupID=PptGroupID FROM BD_Goods g WHERE GoodsNo=@PUserCode
	IF @PptGroupID=0
	BEGIN
		IF @Ppt1Name<>'' OR @Ppt2Name<>''
		BEGIN
			SET @ErrMsg = '商品没有设置属性,请不要填写'
			RETURN -1
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM BD_Goods_PptGroup p 
					LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
					WHERE PptGroupID=@PptGroupID AND ISNULL(p1.Value,'')=@Ppt1Name)
		BEGIN
			SET @ErrMsg = '属性一与商品不匹配'
			RETURN -1
		END
		ELSE
			SELECT @Ppt1ID=Ppt1ID FROM BD_Goods_Ppt1 WHERE Value=@Ppt1Name
			
		IF NOT EXISTS(SELECT 1 FROM BD_Goods_PptGroup p 
						LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
						WHERE PptGroupID=@PptGroupID AND ISNULL(p2.Value,'')=@Ppt2Name)
		BEGIN
			SET @ErrMsg = '属性二与商品不匹配'
			RETURN -1
		END
		ELSE
			SELECT @Ppt2ID=Ppt2ID FROM BD_Goods_Ppt2 WHERE Value=@Ppt2Name
	END
	
	IF @ProductDate <> '' AND @EndDate <> '' AND @ProductDate > @EndDate
	BEGIN
		SET @ErrMsg = '生产日期大于到期日期'
		RETURN -1
	END
		
	DECLARE @Total DECIMAL(22,10)=0,@StockID INT=0
	SET @Price=ROUND(@Price,@PriceDit)
	SET @Qty=ROUND(@Qty,@QtyDit)
	SET @Total=ROUND(@Price*@Qty,@TotalDit)
	
	IF NOT EXISTS(SELECT 1 FROM BD_OpeningStock WHERE GoodsID=@GoodsID AND WhsID=@WhsID)
	BEGIN
		INSERT INTO BD_OpeningStock( WhsID, GoodsID, Qty, Price, Total )
		VALUES  (@WhsID, @GoodsID, @Qty, @Price, @Total)
		SELECT @StockID=SCOPE_IDENTITY()
	END
	ELSE
	BEGIN
		SELECT @StockID=StockID FROM BD_OpeningStock WHERE GoodsID=@GoodsID AND WhsID=@WhsID
		UPDATE BD_OpeningStock SET Qty+=@Qty,Total+=@Total,Price=ROUND(Cast(Total+@Total AS DECIMAL(22,10))/Cast(Qty+@Qty AS DECIMAL(22,10)),@PriceDit) WHERE  StockID=@StockID
	END
	
	-- 成本算法 移动加权
	IF @CostMethod = 1
	BEGIN
		IF EXISTS(SELECT 1 FROM BD_OpeningStock_Detail WHERE GoodsID=@GoodsID AND WhsPtID=@WhsPtID AND Ppt1ID=@Ppt1ID AND Ppt2ID=@Ppt2ID AND BatchNumber = @BatchNumber)
		BEGIN
			SELECT @StockDetailID=DetailID FROM BD_OpeningStock_Detail WHERE GoodsID=@GoodsID AND WhsPtID=@WhsPtID AND Ppt1ID=@Ppt1ID AND Ppt2ID=@Ppt2ID
			UPDATE BD_OpeningStock_Detail SET Qty+=@Qty WHERE GoodsID=@GoodsID AND WhsPtID=@WhsPtID AND Ppt1ID=@Ppt1ID AND Ppt2ID=@Ppt2ID
		END
		ELSE
		BEGIN
			INSERT INTO BD_OpeningStock_Detail( StockID ,WhsPtID ,GoodsID ,Ppt1ID ,Ppt2ID , Qty , BatchNumber ,ProductDate ,EndDate)
			VALUES  ( @StockID ,@WhsPtID ,@GoodsID ,@Ppt1ID ,@Ppt2ID , @Qty, @BatchNumber ,@ProductDate ,@EndDate)
			SELECT @StockDetailID =SCOPE_IDENTITY()
		END
	END
	
	-- 成本算法 手工指定
	IF @CostMethod = 2
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM BD_OpeningStock_Detail WHERE StockID = @StockID 
																						AND GoodsID=@GoodsID 
																						AND @WhsPtID=@WhsPtID 
																						AND Ppt1ID = @Ppt1ID 
																						AND Ppt2ID = @Ppt2ID 
																						AND CostPrice = @Price 
																						AND BatchNumber = @BatchNumber)
		BEGIN
			INSERT INTO BD_OpeningStock_Detail( StockID ,WhsPtID ,GoodsID ,Ppt1ID ,Ppt2ID , Qty ,BatchNumber ,ProductDate ,EndDate,CostPrice)
			VALUES  ( @StockID ,@WhsPtID ,@GoodsID ,@Ppt1ID ,@Ppt2ID , @Qty ,@BatchNumber ,@ProductDate ,@EndDate,@Price)
			SELECT @StockDetailID =SCOPE_IDENTITY()
		END
	END
	
	RETURN 0
GO




IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportOpeningGoodsStock]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportOpeningGoodsStock
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：Hanlin
	时间：2014-11-24
	描述：期初库存商品导入
*/
CREATE  PROCEDURE UP_BD_ImportOpeningGoodsStock
(
	@KUserCode VARCHAR(100),
	@PtUserCode [VARCHAR](100) ,
    @PUserCode [VARCHAR](100) ,
	@Ppt1Name VARCHAR(50),
	@Ppt2Name VARCHAR(50),
	@BatchNumber NVARCHAR(50) = '',   -- 批号
	@ProductDate NVARCHAR(MAX) = '',  -- 生产日期
	@EndDate NVARCHAR(MAX) = '',      -- 结束日期
	@Price DECIMAL(20,8),
	@Qty DECIMAL(20,8),
    @ErrMsg VARCHAR(max)='' OUTPUT
)
--@Encode$--
AS 
    SET NOCOUNT ON
-------------------------------------转换输入参数---------------------------------------------

    DECLARE @HasWhsPt INT=1,@PriceDit INT=8,@QtyDit INT=4,@TotalDit INT=2,@WhsID INT=0,@GoodsID INT=0,@WhsPtID INT=0,@Ppt1ID INT=0,@Ppt2ID INT=0,@PptGroupID INT=0	
    -- 成本算法
    DECLARE @CostMethod INT = 1
    SELECT @HasWhsPt=CfgValue  FROM SS_SysCfg WHERE CfgName='HasWhsPt'
    IF ( @KUserCode = '' ) 
        BEGIN
            SET @ErrMsg = '仓库编号不能为空'
            RETURN -1
        END
    ELSE
		SELECT @WhsID=WhsID FROM BD_Whs WHERE WhsNO=@KUserCode
		
	IF @WhsID=0
	BEGIN
        SET @ErrMsg = '仓库编号不存在'
        RETURN -1
    END
    
    IF @HasWhsPt=1 
    BEGIN
		IF @PtUserCode = '' 
        BEGIN
            SET @ErrMsg = '货位编号不能为空'
            RETURN -1
        END
        ELSE 
			SELECT @WhsPtID=WhsPtID FROM BD_Whs_Position p WHERE WhsID=@WhsID AND WhsPtNO=@PtUserCode
			
        IF @WhsPtID=0
		BEGIN
			SET @ErrMsg = '货位编号不存在或者与仓库不匹配'
			RETURN -1
		END
    END
    ELSE
    BEGIN
		IF @PtUserCode <> '' 
        BEGIN
            SET @ErrMsg = '没有启用货位，请不要填写货位'
            RETURN -1
        END
		SELECT @WhsPtID=WhsPtID FROM BD_Whs_Position WHERE WhsID=@WhsID AND WhsPtType=1
	END
		
    IF ( @PUserCode = '' ) 
    BEGIN
        SET @ErrMsg = '商品编号不能为空'
        RETURN -1
    END
    ELSE 
		SELECT @GoodsID=GoodsID,@CostMethod=CostMethod FROM  BD_Goods  WHERE    GoodsNo = @PUserCode
		
    IF @GoodsID=0
    BEGIN
        SET @ErrMsg = '商品编号不存在'
        RETURN -1
    END
	IF EXISTS(SELECT 1 FROM dbo.BD_Goods WHERE IsSerial=1 AND GoodsID=@GoodsID)
	BEGIN
		SET @ErrMsg = '序列号商品只能使用序列号导入'
		RETURN -1
	END
	
	SELECT @PptGroupID=PptGroupID FROM BD_Goods g WHERE GoodsNo=@PUserCode
	IF @PptGroupID=0
	BEGIN
		IF @Ppt1Name<>'' OR @Ppt2Name<>''
		BEGIN
			SET @ErrMsg = '商品没有设置属性,请不要填写'
			RETURN -1
		END
	END
	ELSE
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM BD_Goods_PptGroup p 
					LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
					WHERE PptGroupID=@PptGroupID AND ISNULL(p1.Value,'')=@Ppt1Name)
		BEGIN
			SET @ErrMsg = '属性一与商品不匹配'
			RETURN -1
		END
		ELSE
			SELECT @Ppt1ID=Ppt1ID FROM BD_Goods_Ppt1 WHERE Value=@Ppt1Name
			
		IF NOT EXISTS(SELECT 1 FROM BD_Goods_PptGroup p 
						LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
						WHERE PptGroupID=@PptGroupID AND ISNULL(p2.Value,'')=@Ppt2Name)
		BEGIN
			SET @ErrMsg = '属性二与商品不匹配'
			RETURN -1
		END
		ELSE
			SELECT @Ppt2ID=Ppt2ID FROM BD_Goods_Ppt2 WHERE Value=@Ppt2Name
	END
	
	IF @ProductDate <> '' AND @EndDate <> '' AND @ProductDate > @EndDate
	BEGIN
		SET @ErrMsg = '生产日期大于到期日期'
		RETURN -1
	END
		
	DECLARE @Total DECIMAL(22,10)=0,@StockID INT=0
	SET @Price=ROUND(@Price,@PriceDit)
	SET @Qty=ROUND(@Qty,@QtyDit)
	SET @Total=ROUND(@Price*@Qty,@TotalDit)
	
	IF @Qty=0 AND @Total=0
		RETURN

	IF EXISTS(SELECT 1 FROM BD_OpeningStock_Detail WHERE GoodsID=@GoodsID 
														AND WhsPtID=@WhsPtID 
														AND Ppt1ID = @Ppt1ID 
														AND Ppt2ID = @Ppt2ID 
														AND CostPrice = CASE WHEN @CostMethod=1 THEN 0 ELSE  @Price end  
														AND ProductDate = @ProductDate
														AND EndDate = @EndDate
														AND BatchNumber = @BatchNumber)
	BEGIN
		SET @ErrMsg = '该行数据与表中数据重复'
		RETURN
	END
	
	IF NOT EXISTS(SELECT 1 FROM BD_OpeningStock WHERE GoodsID=@GoodsID AND WhsID=@WhsID)
	BEGIN
		INSERT INTO BD_OpeningStock( WhsID, GoodsID, Qty, Price, Total )
		VALUES  (@WhsID, @GoodsID, @Qty, @Price, @Total)
		SELECT @StockID=SCOPE_IDENTITY()
	END
	ELSE
	BEGIN
		SELECT @StockID=StockID FROM BD_OpeningStock WHERE GoodsID=@GoodsID AND WhsID=@WhsID
		UPDATE BD_OpeningStock SET Qty+=@Qty,Total+=@Total,Price=ROUND(Cast(Total+@Total AS DECIMAL(22,10))/Cast(Qty+@Qty AS DECIMAL(22,10)),@PriceDit) WHERE  StockID=@StockID
	END

	INSERT INTO BD_OpeningStock_Detail( StockID ,WhsPtID ,GoodsID ,Ppt1ID ,Ppt2ID , Qty ,BatchNumber ,ProductDate ,EndDate,CostPrice)
	VALUES  ( @StockID ,@WhsPtID ,@GoodsID ,@Ppt1ID ,@Ppt2ID , @Qty ,@BatchNumber ,@ProductDate ,@EndDate,CASE WHEN @CostMethod=1 THEN 0 ELSE  @Price end )
		
GO





/****** Object:  StoredProcedure [UP_BD_ImportPpt1]    Script Date: 12/04/2014 10:04:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportPpt1]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportPpt1]
GO

/****** Object:  StoredProcedure [UP_BD_ImportPpt1]    Script Date: 12/04/2014 10:04:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-05
	描述：属相1导入
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportPpt1]
(			   
	@PptNO VARCHAR(20),
	@Value VARCHAR(10),
	@Remark VARCHAR(256),
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
-------------------------------------转换输入参数-------------------------------------------------
IF(@PptNO='') 
BEGIN
	SET @ErrMsg='属性条码不能为空'
    RETURN -1
END
IF( (SELECT COUNT(1) FROM BD_Goods_Ppt1 WHERE PptNO=@PptNO)>0 )
BEGIN
	SET @ErrMsg='属性条码已存在'
    RETURN -1
END
IF(@Value='') 
BEGIN
	SET @ErrMsg='属性名称不能为空'
    RETURN -1
END
IF( (SELECT COUNT(1) FROM BD_Goods_Ppt1 WHERE Value=@Value)>0 )
BEGIN
	SET @ErrMsg='属性名称已存在'
    RETURN -1
END
-------------------------------------转换输入参数-------------------------------------------------

-------------------------------------插入数据-----------------------------------------------------
INSERT INTO BD_Goods_Ppt1
	(PptNO, Value, Remark)
	VALUES  
	(@PptNO, @Value, @Remark)
-------------------------------------插入数据-----------------------------------------------------

END

GO





/****** Object:  StoredProcedure [UP_BD_ImportPpt2]    Script Date: 12/04/2014 10:04:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportPpt2]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportPpt2]
GO

/****** Object:  StoredProcedure [UP_BD_ImportPpt2]    Script Date: 12/04/2014 10:04:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-05
	描述：属相2导入
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportPpt2]
(			   
	@PptNO VARCHAR(20),
	@Value VARCHAR(10),
	@Remark VARCHAR(256),
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
-------------------------------------转换输入参数-------------------------------------------------
IF(@PptNO='') 
BEGIN
	SET @ErrMsg='属性条码不能为空'
    RETURN -1
END
IF( (SELECT COUNT(1) FROM BD_Goods_Ppt2 WHERE PptNO=@PptNO)>0 )
BEGIN
	SET @ErrMsg='属性条码已存在'
    RETURN -1
END
IF(@Value='') 
BEGIN
	SET @ErrMsg='属性名称不能为空'
    RETURN -1
END
IF( (SELECT COUNT(1) FROM BD_Goods_Ppt2 WHERE Value=@Value)>0 )
BEGIN
	SET @ErrMsg='属性名称已存在'
    RETURN -1
END
-------------------------------------转换输入参数-------------------------------------------------

-------------------------------------插入数据-----------------------------------------------------
INSERT INTO BD_Goods_Ppt2
	(PptNO, Value, Remark)
	VALUES  
	(@PptNO, @Value, @Remark)
-------------------------------------插入数据-----------------------------------------------------

END

GO





/****** Object:  StoredProcedure [UP_BD_ImportPrice]    Script Date: 12/04/2014 10:04:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportPrice]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportPrice]
GO

/****** Object:  StoredProcedure [UP_BD_ImportPrice]    Script Date: 12/04/2014 10:04:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-05
	描述：物价导入
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportPrice]
(			   
	@GoodsNo VARCHAR(50),
	@Unit VARCHAR(10),
	@Price1 VARCHAR(30),
	@Price2 VARCHAR(30),
	@Price3 VARCHAR(30),
	@Price4 VARCHAR(30),
	@Price5 VARCHAR(30),
	@Price6 VARCHAR(30),
	@Price7 VARCHAR(30),
	@Price8 VARCHAR(30),
	@Price9 VARCHAR(30),
	@Price10 VARCHAR(30),
	@Price11 VARCHAR(30),
	@Price12 VARCHAR(30),
	@Price13 VARCHAR(30),
	@Price14 VARCHAR(30),
	@Price15 VARCHAR(30),
	@UserID VARCHAR(30),
	@PreLimit VARCHAR(30) = '',
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
-------------------------------------转换输入参数-------------------------------------------------
DECLARE @GoodsID BIGINT=0, @UnitID TINYINT=0, @Sql NVARCHAR(max) = ''
IF(@GoodsNo='') 
BEGIN
	SET @ErrMsg='商品编号不能为空'
    RETURN -1
END
SELECT TOP 1 @GoodsID=GoodsID FROM BD_Goods WHERE GoodsNo=@GoodsNo
IF(@GoodsID=0)
BEGIN
	SET @ErrMsg='商品编号不存在'
    RETURN -1
END
IF(@Unit='') 
BEGIN
	SET @ErrMsg='计量单位不能为空'
    RETURN -1
END
SELECT TOP 1 @UnitID=UnitID FROM BD_Goods_Price WHERE GoodsID=@GoodsID AND Unit=@Unit
IF(@UnitID=0)
BEGIN
	SET @ErrMsg='计量单位不存在'
    RETURN -1
END
DECLARE @PriceCount INT = 1, @PriceTmp VARCHAR(30) = '', @PriceUPSql VARCHAR(MAX) = ''
DECLARE @PreLimitTable TABLE (RowID INT, IsHasLimit INT)
IF @PreLimit <> ''
BEGIN
	INSERT INTO @PreLimitTable 
	SELECT ROW_NUMBER() OVER(ORDER BY IDENT_CURRENT(1)) AS 'RowID',typeid AS IsHasLimit 
	FROM dbo.UF_OT_Split_Int(@PreLimit,',')
END

WHILE @PriceCount < 16
BEGIN
    IF @PriceCount = 1
		SET @PriceTmp = @Price1
    ELSE IF @PriceCount = 2
		SET @PriceTmp = @Price2
    ELSE IF @PriceCount = 3
		SET @PriceTmp = @Price3
    ELSE IF @PriceCount = 4
		SET @PriceTmp = @Price4
    ELSE IF @PriceCount = 5
		SET @PriceTmp = @Price5
    ELSE IF @PriceCount = 6
		SET @PriceTmp = @Price6
    ELSE IF @PriceCount = 7
		SET @PriceTmp = @Price7
    ELSE IF @PriceCount = 8
		SET @PriceTmp = @Price8
    ELSE IF @PriceCount = 9
		SET @PriceTmp = @Price9
    ELSE IF @PriceCount = 10
		SET @PriceTmp = @Price10
    ELSE IF @PriceCount = 11
		SET @PriceTmp = @Price11
    ELSE IF @PriceCount = 12
		SET @PriceTmp = @Price12
    ELSE IF @PriceCount = 13
		SET @PriceTmp = @Price13
    ELSE IF @PriceCount = 14
		SET @PriceTmp = @Price14
    ELSE IF @PriceCount = 15
		SET @PriceTmp = @Price15
	IF @UserID = 1 OR EXISTS (SELECT 1 FROM @PreLimitTable WHERE RowID = @PriceCount AND IsHasLimit = 1)
	BEGIN
		IF(@PriceTmp<>'') 
		BEGIN
			IF( CHARINDEX('-',@PriceTmp)>0 )
			BEGIN
				SET @ErrMsg='预设价'+CAST(@PriceCount AS VARCHAR(2))+'不能为负数'
				RETURN -1
			END
			SET @PriceUPSql += 'Price' + CAST(@PriceCount AS VARCHAR(2)) +'='+CAST(CAST(ROUND(CAST(@PriceTmp AS DECIMAL(20,9)),8) AS DECIMAL(20,8)) AS VARCHAR(1000))+','
		END
		ELSE
			SET @PriceUPSql += 'Price' + CAST(@PriceCount AS VARCHAR(2)) +'=0,'
    END
	SET @PriceCount += 1
END
IF LEN(@PriceUPSql)=0
BEGIN
	SET @ErrMsg='导入成功'
	RETURN 1
END
-------------------------------------转换输入参数-------------------------------------------------

-------------------------------------插入数据-----------------------------------------------------
SET @Sql = N' UPDATE BD_Goods_Price SET '+SUBSTRING(@PriceUPSql, 1,LEN(@PriceUPSql)-1)+N' WHERE GoodsID=@GoodsID AND UnitID=@UnitID '
PRINT(@Sql)	  
EXECUTE sys.sp_executesql @Sql, N'@GoodsID BIGINT=0, @UnitID TINYINT=0',@GoodsID,@UnitID
-------------------------------------插入数据-----------------------------------------------------

END

GO





/****** Object:  StoredProcedure [UP_BD_ImportPriceTrail]    Script Date: 12/04/2014 10:04:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportPriceTrail]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportPriceTrail]
GO

/****** Object:  StoredProcedure [UP_BD_ImportPriceTrail]    Script Date: 12/04/2014 10:04:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-05
	描述：价格跟踪导入
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportPriceTrail]
(			   
	@BTypeCode VARCHAR(50),
	@GoodsNo VARCHAR(50),
	@Unit VARCHAR(10),
	@PchPrice VARCHAR(30),
	@PchDis VARCHAR(30),
	@SellPrice VARCHAR(30),
	@SellDis VARCHAR(30),
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
-------------------------------------转换输入参数-------------------------------------------------
DECLARE @BTypeID BIGINT=0, @GoodsID BIGINT=0, @UnitID TINYINT=0, @dPchPrice DECIMAL(20,8)=0, @dPchDis DECIMAL(20,8)=0, @dSellPrice DECIMAL(20,8)=0, @dSellDis DECIMAL(20,8)=0
IF(@BTypeCode='') 
BEGIN
	SET @ErrMsg='往来单位编号不能为空'
    RETURN -1
END
SELECT TOP 1 @BTypeID=BTypeID FROM BD_Btype WHERE BTypeCode=@BTypeCode
IF(@BTypeID=0)
BEGIN
	SET @ErrMsg='往来单位编号不存在'
    RETURN -1
END
IF(@GoodsNo='') 
BEGIN
	SET @ErrMsg='商品编号不能为空'
    RETURN -1
END
SELECT TOP 1 @GoodsID=GoodsID FROM BD_Goods WHERE GoodsNo=@GoodsNo
IF(@GoodsID=0)
BEGIN
	SET @ErrMsg='商品编号不存在'
    RETURN -1
END
IF(@Unit='') 
BEGIN
	SET @ErrMsg='计量单位不能为空'
    RETURN -1
END
SELECT TOP 1 @UnitID=UnitID FROM BD_Goods_Price WHERE GoodsID=@GoodsID AND Unit=@Unit
IF(@UnitID=0)
BEGIN
	SET @ErrMsg='计量单位不存在'
    RETURN -1
END
IF(@PchPrice<>'') 
BEGIN
	IF( CHARINDEX('-',@PchPrice)>0 )
	BEGIN
		SET @ErrMsg='最近采购价不能为负数'
		RETURN -1
	END
	SET @dPchPrice=CAST(ROUND(CAST(@PchPrice AS DECIMAL(20,9)),8) AS DECIMAL(20,8))
END
IF(@PchDis<>'')
BEGIN
	IF( CHARINDEX('-',@PchDis)>0 )
	BEGIN
		SET @ErrMsg='最近采购折扣不能为负数'
		RETURN -1
	END
	SET @dPchDis=CAST(ROUND(CAST(@PchDis AS DECIMAL(20,5)),4) AS DECIMAL(20,8))
	IF( @dPchDis >= 10)
	BEGIN
		SET @ErrMsg='最近采购折扣不能大于等于10'
		RETURN -1
	END
END
IF(@SellPrice<>'') 
BEGIN
	IF( CHARINDEX('-',@SellPrice)>0 )
	BEGIN
		SET @ErrMsg='最近销售价不能为负数'
		RETURN -1
	END
	SET @dSellPrice=CAST(ROUND(CAST(@SellPrice AS DECIMAL(20,9)),8) AS DECIMAL(20,8))
END
IF(@SellDis<>'') 
BEGIN
	IF( CHARINDEX('-',@SellDis)>0 )
	BEGIN
		SET @ErrMsg='最近销售折扣不能为负数'
		RETURN -1
	END
	SET @dSellDis=CAST(ROUND(CAST(@SellDis AS DECIMAL(20,5)),4) AS DECIMAL(20,8))
	IF( @dSellDis >= 10)
	BEGIN
		SET @ErrMsg='最近销售折扣不能大于等于10'
		RETURN -1
	END
END
-------------------------------------转换输入参数-------------------------------------------------

-------------------------------------插入数据-----------------------------------------------------
IF( (SELECT COUNT(1) FROM PD_PriceTrail WHERE BtypeID=@BTypeID AND GoodsID=@GoodsID AND UnitID=@UnitID)>0 )
BEGIN
	UPDATE PD_PriceTrail 
	SET PchPrice=@dPchPrice,
		SellPrice=@dSellPrice,
		PchDis=@dPchDis,
		SellDis=@dSellDis 
	WHERE BtypeID=@BTypeID AND GoodsID=@GoodsID AND UnitID=@UnitID 
END
ELSE
BEGIN
	INSERT INTO PD_PriceTrail 
		(BtypeID, GoodsID, UnitID, PchPrice, PchDis, SellPrice, SellDis)
		VALUES
		(@BTypeID, @GoodsID, @UnitID, @dPchPrice, @dPchDis, @dSellPrice, @dSellDis)
END
-------------------------------------插入数据-----------------------------------------------------

END

GO





IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_BD_ImportPTtype]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_ImportPTtype]
GO
/****** Object:  StoredProcedure [UP_BD_ImportPTtype]    Script Date: 12/04/2014 09:54:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/12/04
-- Description:	 货位信息导入
-- =============================================
CREATE  PROCEDURE [UP_BD_ImportPTtype]
    (
      @WhsNO VARCHAR(50) ,
      @WhsPtNO VARCHAR(50) ,
      @WhsPtName VARCHAR(100) ,
      @Remark VARCHAR(256) ,
	  @UserID INT = 0,
      @ErrMsg VARCHAR(MAX) = '' OUTPUT
    )
AS

BEGIN
    SET NOCOUNT ON   
	DECLARE @WhsID INT, @ExistWhsPtID INT, @IsAllLimit INT = 0
	
	IF @WhsNO = ''
		BEGIN
			SET @ErrMsg ='仓库编号不能为空'
			RETURN -1
		END
	
	--查询仓库ID
	SELECT @WhsID = WhsID FROM BD_Whs WHERE WhsNO = @WhsNO AND Stt = 1
		
	IF @WhsID IS NULL
		BEGIN
			SET @ErrMsg ='仓库编号不存在或已停用'
			RETURN -1
		END

	SELECT @IsAllLimit = dbo.UF_BD_IsAllKtypeLimit(@UserID)
	
	IF @IsAllLimit = 0 OR 
	  (@IsAllLimit = 1 AND NOT EXISTS (SELECT 1 FROM UF_BD_KtypeLimit(@UserID) L WHERE L.WhsID = @WhsID))
		BEGIN
			SET @ErrMsg ='无仓库权限'
			RETURN -1
		END
			
	IF @WhsPtNO = ''
		BEGIN
			SET @ErrMsg ='货位编号不能为空'
			RETURN -1
		END
	
	--查询货位编号是否存在
	SELECT @ExistWhsPtID = WhsPtID FROM BD_Whs_Position WHERE WhsPtNO = @WhsPtNO
		
	IF @ExistWhsPtID IS NOT NULL
		BEGIN
			SET @ErrMsg ='货位编号已存在'
			RETURN -1
		END
			
	IF @WhsPtName = ''
		BEGIN
			SET @ErrMsg ='货位名称不能为空'
			RETURN -1
		END
		
    INSERT INTO [BD_Whs_Position]
           ([WhsPtNO]
           ,[WhsPtName]
           ,[WhsID]
           ,[WhsPtType]
           ,[Remark])
     VALUES
           (@WhsPtNO
           ,@WhsPtName
           ,@WhsID
           ,0
           ,@Remark)
END
GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportPtype]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportPtype
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：Hanlin
	时间：2014-11-24
	描述：商品导入
*/
CREATE  PROCEDURE UP_BD_ImportPtype
    (
      @TypeCode [VARCHAR](50) ,
      @GoodsNo [varchar](50) ,
      @GoodsName [varchar](100) ,
      @GroupName [varchar](50) ,
      @CostMethod [varchar](50) ,
      @DateType [varchar](50) ,
      @ValidDays INT=0 ,
      @NearbyDays INT=0 ,      
      @Model [varchar](50) ,
      @GoodsAbbName [varchar](50) ,
      @Brand [VARCHAR](50) ,
      @Spec [VARCHAR](50) ,
      @Spell [VARCHAR](50) ,
      @Place [varchar](50) ,
      @KG float ,
      @IsOS [varchar](10) ,
      @Unit1 [varchar](10) ,
      @BarCode1 [VARCHAR](100) ,
      @Unit2 [VARCHAR](10) ,
      @Convfactor2 float ,
      @BarCode2 [varchar](100) ,
      @Unit3 [varchar](10) ,
      @Convfactor3 float ,
      @BarCode3 [VARCHAR](100) ,
      @Remark [VARCHAR](256) ,
      @ErrMsg VARCHAR(max)='' OUTPUT
    )
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @dbname [varchar](30) = 'BD_Goods'

    DECLARE @GoodsTypeID INT
    DECLARE @PptGroupID INT
    IF ( @TypeCode = '' ) 
    BEGIN
        SET @ErrMsg = '类型编号不能为空'
        RETURN -1
    END
    ELSE 
        IF NOT EXISTS ( SELECT  GoodsTypeID
                        FROM    BD_Goods_Type
                        WHERE   TypeCode = @TypeCode ) 
        BEGIN
            SET @ErrMsg = '类型编号不存在'
            RETURN -1
        END
        ELSE 
			IF  NOT EXISTS ( SELECT  GoodsTypeID
                        FROM    BD_Goods_Type
                        WHERE   TypeCode = @TypeCode And SonNum = 0 ) 
            Begin
				SET @ErrMsg = '类型不是末级分类'
				RETURN -1
            END
            ElSE          
			BEGIN
				SET @GoodsTypeID = ( SELECT TOP 1
										GoodsTypeID
							   FROM     BD_Goods_Type
							   WHERE    TypeCode = @TypeCode
							 )
			END

    IF ( @GoodsNo = '' ) 
        BEGIN
            SET @ErrMsg = '商品编号不能为空'
            RETURN -1
        END
    ELSE 
        IF ( ( SELECT   COUNT(1)
               FROM     BD_Goods
               WHERE    GoodsNo = @GoodsNo
             ) > 0 ) 
            BEGIN
                SET @ErrMsg = '商品编号已存在'
                RETURN -1
            END

    IF ( @GoodsName = '' ) 
        BEGIN
            SET @ErrMsg = '商品名称不能为空'
            RETURN -1
        END
    declare @SysCostMethod int
    select @SysCostMethod = CfgValue from SS_SysCfg where ID=112
    IF(@SysCostMethod = 1 or @SysCostMethod = 3)
    BEGIN
		IF (@CostMethod = '' or @CostMethod = '移动加权平均')
		BEGIN
			Set @CostMethod = 1
		END 
		ELSE IF(@SysCostMethod = 3 and @CostMethod = '手工指定')   
		BEGIN
			Set @CostMethod = 2
		END 
		ELSE IF(@SysCostMethod = 1 and @CostMethod = '手工指定')
		BEGIN
			SET @ErrMsg = '系统设置的成本算法是移动加权'
			RETURN -1
		END
		Else
		BEGIN
			SET @ErrMsg = '请填写正确的成本算法'
				RETURN -1
		END
    END 
    ELSE
    BEGIN
		IF (@CostMethod = '' or @CostMethod = '手工指定')
		BEGIN
			Set @CostMethod = 2
		END 
		ELSE IF(@CostMethod = '移动加权平均')   
		BEGIN
			SET @ErrMsg = '系统设置的成本算法是手工指定'
			RETURN -1
		END 
		Else
		BEGIN
			SET @ErrMsg = '请填写正确的成本算法'
				RETURN -1
		END
    END
    
    IF(@DateType = '' or @DateType = '不录入生产及到期日期')
		BEGIN
			Set @DateType = 1
		END 
    ELSE IF(@DateType = '录入生产日期')   
    BEGIN
		Set @DateType = 2
    END 
    ELSE IF(@DateType = '录入到期日期')   
    BEGIN
		Set @DateType = 3
    END 
    Else
    BEGIN
		SET @ErrMsg = '请填写正确的生产及到期日期类型'
            RETURN -1
    END
    
    IF(@ValidDays < 0)
    BEGIN
		Set @ValidDays = 0
    END
    ELSE IF (@ValidDays > 9999)
    BEGIN
		Set @ValidDays = 9999
    END
    IF(@NearbyDays < 0)
    BEGIN
		Set @NearbyDays = 0
    END
    ELSE IF (@NearbyDays > 9999)
    BEGIN
		Set @NearbyDays = 9999
    END
    
    IF ( @GroupName <> '')
    Begin
		IF NOT EXISTS ( SELECT   PptGroupID
               FROM     BD_Goods_PptGroup
               WHERE    GroupName = @GroupName) 
        BEGIN
            SET @ErrMsg = '属性组不存在'
            RETURN -1
        END
        ELSE
        BEGIN
			SET @PptGroupID = ( SELECT TOP 1
										PptGroupID
							   FROM     BD_Goods_PptGroup
							   WHERE    GroupName = @GroupName
							 )
        END
    End
    else
		select @PptGroupID = 0
    IF(@KG < 0) 
    BEGIN
		SET @ErrMsg = '重量不能为负数'
        RETURN -1
    END
    IF(@Unit1 = '') SET @Unit1= 'pcs'
    IF(@BarCode1 <> '')
    BEGIN
		IF(( SELECT   COUNT(1)
               FROM     BD_Goods_Price
               WHERE    BarCode = @BarCode1
             ) > 0 )
             BEGIN
				SET @ErrMsg = '基本条码已经存在'
				RETURN -1
             END
        IF(@BarCode1 = @BarCode2 OR @BarCode1 = @BarCode3)
		BEGIN
			SET @ErrMsg = '条码不能相同'
			RETURN -1
        END
    END
    IF((@Unit2 <> '' AND @Unit1=@Unit2) or(@Unit2<>'' and @Unit3 <> '' AND (@Unit1=@Unit3 or @Unit2 = @Unit3)))
    BEGIN
		SET @ErrMsg = '相同商品单位不能相同'
		RETURN -1
    END
    IF(@Unit2 <> '' and @Convfactor2 = 0) 
    BEGIN
		SET @ErrMsg = '辅助单位1换算关系不能为0或者为空'
        RETURN -1
    END
    IF(@Unit2 <> '' and @Convfactor2 < 0) 
    BEGIN
		SET @ErrMsg = '辅助单位1换算关系不能为负数'
        RETURN -1
    END
    IF(@Unit2<>'' and @BarCode2 <> '')
    BEGIN
		IF(( SELECT   COUNT(1)
               FROM     BD_Goods_Price
               WHERE    BarCode = @BarCode2
             ) > 0 )
             BEGIN
				SET @ErrMsg = '辅助单位1条码已经存在'
				RETURN -1
             END
        IF(@BarCode2 = @BarCode1 OR @BarCode2 = @BarCode3)
		BEGIN
			SET @ErrMsg = '条码不能相同'
			RETURN -1
        END
    END
    IF(@Unit2<>'' AND @Unit3 <> '' and @Convfactor3 = 0) 
    BEGIN
		SET @ErrMsg = '辅助单位2换算关系不能为0或者为空'
        RETURN -1
    END
    IF(@Unit2<>'' AND @Unit3 <> '' and @Convfactor3 < 0) 
    BEGIN
		SET @ErrMsg = '辅助单位2换算关系不能为负数'
        RETURN -1
    END
    IF(@Unit2 <> '' And @Unit3<>'' and @BarCode3 <> '')
    BEGIN
		IF(( SELECT   COUNT(1)
               FROM     BD_Goods_Price
               WHERE    BarCode = @BarCode3
             ) > 0 )
             BEGIN
				SET @ErrMsg = '辅助单位2条码已经存在'
				RETURN -1
             END
        IF(@BarCode3 = @BarCode1 OR @BarCode3 = @BarCode2)
		BEGIN
			SET @ErrMsg = '条码不能相同'
			RETURN -1
        END
    END
    
  --自动处理拼音码  
  IF @Spell = ''
  BEGIN
	SET @Spell = [dbo].[UF_OT_GetPY](@GoodsName)
	IF LEN(@Spell)<=40
		SET @Spell = @Spell
	ELSE
		SET @Spell = LEFT(@Spell,40)
  END
    

  INSERT INTO BD_Goods
          ( GoodsNo ,
            GoodsTypeID ,
            GoodsName ,
            GoodsAbbName ,
            CostMethod,
            DateType,
            ValidDays,
            NearbyDays,
            Spell ,
            Brand,
            Spec ,
            Model ,
            Place ,
            KG ,
            PptGroupID ,
            Graph1 ,
            Graph2 ,
            Graph3 ,
            Graph4 ,
            Graph5 ,
            CreateDate ,
            ElyID ,
            UpdateDate ,
            UpdateOprId ,
            Stt ,
            Del ,
            Remark ,
            UpdateTag ,
            IsUpload ,
            UPriceType,
            IsOS
          )
  VALUES  ( @GoodsNo , -- GoodsNo - varchar(50)
            @GoodsTypeID , -- GoodsTypeID - bigint
            @GoodsName, -- GoodsName - varchar(100)
            @GoodsAbbName , -- GoodsAbbName - varchar(50)
            @CostMethod,
            @DateType,
            @ValidDays,
            @NearbyDays,
            @Spell , -- Spell - varchars(50)
            @Brand,
            @Spec , -- Spec - varchar(50)
            @Model , -- Model - varchar(50)
            @Place , -- Place - varchar(50)
            @KG , -- KG - decimal
            @PptGroupID , -- PptGroupID - int
            0 , -- Graph1 - int
            0 , -- Graph2 - int
            0 , -- Graph3 - int
            0 , -- Graph4 - int
            0 , -- Graph5 - int
            getdate() , -- CreateDate - datetime
            0 , -- ElyID - int
            getdate() , -- UpdateDate - datetime
            0 , -- UpdateOprId - int
            1 , -- Stt - bit
            0 , -- Del - bit
            @Remark , -- Remark - varchar(256)
            0 , -- UpdateTag - int
            0 , -- IsUpload - bit
            1,  -- UPriceType - tinyint
            case when @IsOS = '是' then 1 else 0 end
          )
  declare @GoodsID INT
  SET @GoodsID = (SELECT Top 1 GoodsID 
					FROM BD_Goods 
					WHERE GoodsNo = @GoodsNo)
  INSERT INTO BD_Goods_Price
		(
			GoodsID,
			UnitID,
			Unit,
			Convfactor,
			BarCode
		)
	VALUES (@GoodsID,1,@Unit1,1,@BarCode1)
	if(@Unit2 <> '')
	BEGIN
		INSERT INTO BD_Goods_Price
			(
				GoodsID,
				UnitID,
				Unit,
				Convfactor,
				BarCode
			)
		VALUES (@GoodsID,2,@Unit2,@Convfactor2,@BarCode2)
	END
	if(@Unit2 <> '' and @Unit3 <> '')
	BEGIN
		INSERT INTO BD_Goods_Price
			(
				GoodsID,
				UnitID,
				Unit,
				Convfactor,
				BarCode
			)
		VALUES (@GoodsID,3,@Unit3,@Convfactor3,@BarCode3)
	END

GO





IF EXISTS ( SELECT  1
            FROM    sys.objects
            WHERE   object_id = OBJECT_ID(N'[UP_BD_ImportPtypeDftWhs]')
                    AND type IN( N'P') )
    DROP PROCEDURE UP_BD_ImportPtypeDftWhs
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO
/*
	作者：Hanlin
	时间：2014-11-24
	描述：商品导入
*/
CREATE  PROCEDURE UP_BD_ImportPtypeDftWhs
    (
      @GoodsNo [VARCHAR](50) ,
      @WhsNO [varchar](50) ,
      @WhsPtNO [varchar](50) ,
      @ErrMsg VARCHAR(max)='' OUTPUT
    )
--@Encode$--
AS 
    SET NOCOUNT ON

-------------------------------------转换输入参数---------------------------------------------

    DECLARE @dbname [varchar](30) = 'BD_Goods'

    DECLARE @WhsID INT
    DECLARE @GoodsID INT
    DECLARE @WhsPtID INT
    SET @WhsPtID = 0
	IF ( @GoodsNo = '' ) 
    BEGIN
        SET @ErrMsg = '商品编号不能为空'
        RETURN -1
    END
    ELSE 
    BEGIN
        IF NOT EXISTS ( SELECT  GoodsID
                        FROM    BD_Goods
                        WHERE   GoodsNo = @GoodsNo ) 
        BEGIN
            SET @ErrMsg = '商品编号不存在'
            RETURN -1
        END
        ELSE 			
			SET @GoodsID = ( SELECT TOP 1
									GoodsID
						   FROM     BD_Goods
						   WHERE    GoodsNo = @GoodsNo
						 )
	END	
	
	IF ( @WhsNO = '' ) 
    BEGIN
        SET @ErrMsg = '仓库编号不能为空'
        RETURN -1
    END
    ELSE 
    BEGIN
        IF NOT EXISTS ( SELECT  WhsID
                        FROM    BD_Whs
                        WHERE   WhsNO = @WhsNO ) 
        BEGIN
            SET @ErrMsg = '仓库编号不存在'
            RETURN -1
        END
        ELSE 			
			SET @WhsID = ( SELECT TOP 1
									WhsID
						   FROM     BD_Whs
						   WHERE    WhsNO = @WhsNO
						 )
	END
	
	IF ( @WhsPtNO <> '' ) 
    BEGIN     
		IF ( NOT EXISTS(SELECT WhsPtID FROM BD_Whs_Position WHERE WhsPtNO = @WhsPtNO AND WhsID = @WhsID))
		BEGIN 
			SET @ErrMsg = '设置的仓库下没有该货位信息'
			RETURN -1
		END
		ELSE
		Set @WhsPtID = (SELECT TOP 1
									WhsPtID
						   FROM     BD_Whs_Position
						   WHERE    WhsPtNO = @WhsPtNO AND WhsID = @WhsID)		
	END
	
	IF((SELECT COUNT(1) FROM BD_Goods_DftWhs WHERE GoodsID = @GoodsID AND WhsID = @WhsID) > 0)
	BEGIN 
		UPDATE BD_Goods_DftWhs SET WhsPtID = @WhsPtID WHERE GoodsID = @GoodsID AND WhsID = @WhsID
	END
	ELSE
		INSERT INTO BD_Goods_DftWhs(GoodsID,WhsID,WhsPtID) VALUES(@GoodsID,@WhsID,@WhsPtID)
    

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_ImportStockLimit]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_ImportStockLimit]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：Hanlin
	日期：2015-3-14
	描述：库存上下限
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_ImportStockLimit]
(			   
	@WhsNo VARCHAR(100),
	@GoodsNo VARCHAR(50),
	@UpperBound VARCHAR(20),
	@LowerBound VARCHAR(20),
	@UserID INT=0,				--操作员ID
	@ErrMsg VARCHAR(MAX)='' OUTPUT
)
AS
SET NOCOUNT ON
BEGIN

	DECLARE @WhsID BIGINT=0, @GoodsID BIGINT=0,@UpperBoundD DECIMAL(16,4),@LowerBoundD DECIMAL(16,4)
	IF @UpperBound=''
		SET @UpperBound='0'
	SET @UpperBoundD=@UpperBound
	IF @LowerBound=''
		SET @LowerBound='0'
	SET @LowerBoundD=@LowerBound

	IF @WhsNo='全部仓库'
		SET @WhsID=99999
	ELSE
		SELECT @WhsID=WhsID FROM BD_Whs WHERE WhsNO=@WhsNo
	IF(@WhsID=0)
	BEGIN
		SET @ErrMsg='仓库编号不存在'
		RETURN -1
	END
	SELECT @GoodsID=GoodsID FROM BD_Goods WHERE GoodsNo=@GoodsNo
	IF(@GoodsID=0) 
	BEGIN
		SET @ErrMsg='仓库编号不存在'
		RETURN -1
	END

	IF dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2 AND( @WhsID=99999 OR NOT EXISTS(SELECT 1 FROM dbo.UF_BD_KtypeLimit(@UserID) WHERE WhsID=@WhsID))
	BEGIN
		SET @ErrMsg='没有该仓库的权限'
		RETURN -1
	END
	IF(@UpperBound<@LowerBoundD)
	BEGIN
		SET @ErrMsg='上限不能小于下限'
		RETURN -1
	END
	
	IF EXISTS(SELECT 1 FROM PD_GoodsStock_Bound WHERE GoodsID= @GoodsID AND WhsID=@WhsID)
		UPDATE PD_GoodsStock_Bound SET UpperBound=@UpperBound,LowerBound=@LowerBound WHERE GoodsID= @GoodsID AND WhsID=@WhsID
	ELSE	
		INSERT INTO PD_GoodsStock_Bound( GoodsID ,WhsID ,UpperBound ,LowerBound) VALUES  (@GoodsID,@WhsID,@UpperBoundD,@LowerBoundD)
END

GO





IF exists (SELECT * FROM sysobjects WHERE id = object_id(N'[UP_BD_Insert_BD_BType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [UP_BD_Insert_BD_BType]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2020-02-07
	描述：手机版新增往来单位信息	
*/

CREATE PROCEDURE UP_BD_Insert_BD_BType
(
	@flag					INT,					--1.大类新增 2.大类修改 3.大类删除 4.子类新增 5.子类修改 6.子类删除
	@BTypeTypeId			INT = 0,				--大类ID
	@TypeCode				VARCHAR(500) = '',		--大类编号
	@TypeName				VARCHAR(500) = '',		--大类名称
	@ParId					INT = 0,				--大类的父类ID
	@BTypeName				VARCHAR(500) = '',		--子类编号
	@BTypeCode				VARCHAR(500) = '',		--子类名称,
	@Spell					VARCHAR(500) = '',		--子类拼音码
	@BTypeAbbName			VARCHAR(500) = '',		--子类简名
	@AreaID					INT = 0,				--地区ID
	@PriceLvl				INT = 1,				--预设价
	@LinkMan				VARCHAR(500) = '',		--联系人
	@Tel					VARCHAR(500) = '',		--电话
	@MTel					VARCHAR(500) = '',		--手机
	@Email					VARCHAR(500) = '',		--电子邮件
	@Bank					VARCHAR(500) = '',		--开户银行
	@BankAcntNo				VARCHAR(500) = '',		--银行账号
	@TaxNo					VARCHAR(500) = '',		--税号
	@Boss					VARCHAR(500) = '',
	@Remark					VARCHAR(500) = '',		--备注
	@Adress					VARCHAR(500) = '',		--地址
	@PaidCircle				INT = 0,				--结算周期
	@StatementPeriod		INT = 0,				--延长期
	@PriceTrack				INT = 0,				--启用价格跟踪
	@PaidDeadline			INT = 0					--结算截止日
)
AS
SET NOCOUNT ON

DECLARE @newPath	VARCHAR(MAX),
		@oldPath	VARCHAR(MAX),
		@newSonNum	INT

--大类的操作
IF @flag = 1 OR @flag = 2 OR @flag = 3
BEGIN
	IF @flag = 1	--大类新增	
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Btype_Type WHERE TypeCode = @TypeCode)
		BEGIN
			RAISERROR('大类信息已存在',16,1)
			RETURN -1
		END
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Btype_Type WHERE TypeName = @TypeName)
		BEGIN
			RAISERROR('大类信息已存在',16,1)
			RETURN -1
		END
		
		IF @ParId = 1 --一级目录，直接新增
		BEGIN
			SELECT @newPath = max(path+1) FROM dbo.BD_Btype_Type WHERE ParID = 1
			
			IF LEN(@newPath)=1
				SET @newPath = '0000'+@newPath
			ELSE IF LEN(@newPath)=2
				SET @newPath = '000'+@newPath
			ELSE IF LEN(@newPath)=3
				SET @newPath = '00'+@newPath
			ELSE IF LEN(@newPath)=4
				SET @newPath = '0'+@newPath
			ELSE IF LEN(@newPath)=5	
				SET @newPath = @newPath
				
			INSERT INTO dbo.BD_Btype_Type
	        ( 
				TypeCode ,
				TypeName ,
				Path ,
				ParID ,
				Lvl ,
				SonNum ,
				Stt
	        )VALUES( 
				@TypeCode , -- TypeCode - varchar(50)
				@TypeName , -- TypeName - varchar(100)
				@newPath , -- Path - varchar(25)
				1 , -- ParID - int
				1 , -- Lvl - int
				0 , -- SonNum - int
				1  -- Stt - bit
			)
			
			IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('新增大类信息失败',16,1)
				RETURN -2
			END
		END
		ELSE	-- 其他级别
		BEGIN
			IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Btype_Type WHERE TypeCode = @TypeCode)
			BEGIN
				RAISERROR('大类信息已存在',16,1)
				RETURN -1
			END
			
			IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Btype_Type WHERE TypeName = @TypeName)
			BEGIN
				RAISERROR('大类信息已存在',16,1)
				RETURN -1
			END
		
			SELECT	@oldPath = path,
					@newPath = SonNum + 1,
					@newSonNum = SonNum
			FROM	BD_Btype_Type 
			WHERE	BtypeTypeID = @BtypeTypeID
			
			IF LEN(@newPath)=1
				SET @newPath = '0000'+@newPath
			ELSE IF LEN(@newPath)=2
				SET @newPath = '000'+@newPath
			ELSE IF LEN(@newPath)=3
				SET @newPath = '00'+@newPath
			ELSE IF LEN(@newPath)=4
				SET @newPath = '0'+@newPath
			ELSE IF LEN(@newPath)=5	
				SET @newPath = @newPath
				
			--加上父类的ID
			SET @newPath = @oldPath + @newPath
			
			INSERT INTO dbo.BD_Btype_Type
	        ( 
				TypeCode ,
				TypeName ,
				Path ,
				ParID ,
				Lvl ,
				SonNum ,
				Stt
	        )VALUES( 
				@TypeCode , -- TypeCode - varchar(50)
				@TypeName , -- TypeName - varchar(100)
				@newPath , -- Path - varchar(25)
				@BtypeTypeID , -- ParID - int
				LEN(@newPath)/5 , -- Lvl - int
				0 , -- SonNum - int
				1  -- Stt - bit
			)
			
			IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('新增大类信息失败',16,1)
				RETURN -2
			END
			
			--修改父类的SonNum
			UPDATE dbo.BD_Btype_Type SET SonNum = SonNum + 1 WHERE BtypeTypeID = @BTypeTypeId			
		END
	END
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.BD_Btype_Type WHERE BtypeTypeID = @BTypeTypeId)
	BEGIN
		RAISERROR('父类不存在',16,1)
		RETURN -1
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Btype WHERE BTypeCode = @BTypeCode)
	BEGIN
		RAISERROR('相同编号的往来单位已存在',16,1)
		RETURN -2
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Btype WHERE BTypeName = @BTypeName)
	BEGIN
		RAISERROR('相同编号的往来单位已存在',16,1)
		RETURN -2
	END

	--更改任我行提供的存储过程，使之支持传0(支持空所属地区)
	IF @AreaID!=0
	BEGIN
		IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.BD_Area WHERE AreaID = @AreaID)
		BEGIN
			RAISERROR('地区信息不存在',16,1)
			RETURN -3
		END
	END

	INSERT INTO dbo.BD_Btype
	(
		BTypeName ,
		BTypeCode ,
		Spell ,
		BTypeAbbName ,
		BtypeTypeID ,
		AreaID ,
		PriceLvl ,
		LinkMan ,
		Tel ,
		MTel ,
		Email ,
		Bank ,
		BankAcntNo ,
		TaxNo ,
		Boss ,
		Remark ,
		Adress ,
		PaidCircle ,
		StatementPeriod ,
		PriceTrack ,
		PaidDeadline 
	) VALUES(
		@BTypeName ,
		@BTypeCode ,
		@Spell ,
		@BTypeAbbName ,
		@BtypeTypeID ,
		@AreaID ,
		@PriceLvl ,
		@LinkMan ,
		@Tel ,
		@MTel ,
		@Email ,
		@Bank ,
		@BankAcntNo ,
		@TaxNo ,
		@Boss ,
		@Remark ,
		@Adress ,
		@PaidCircle ,
		@StatementPeriod ,
		@PriceTrack ,
		@PaidDeadline 
	)
	
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('写入信息失败',16,1)
		RETURN -4
	END
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF exists (SELECT * FROM sysobjects WHERE id = object_id(N'[UP_BD_Insert_BD_Goods]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [UP_BD_Insert_BD_Goods]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2020-02-08
	描述：手机版新增商品信息
*/

CREATE PROCEDURE UP_BD_Insert_BD_Goods
(
	@flag					INT,					--1.大类新增 2.大类修改 3.大类删除 4.子类新增 5.子类修改 6.子类删除
	@GoodsTypeId			INT = 0,				--父类ID
	@TypeCode				VARCHAR(500) = '',		--大类编号
	@TypeName				VARCHAR(500) = '',		--大类名称
	@ParId					INT = 0,				--大类的父类ID
	@GoodsNo				VARCHAR(500) = '',		--子类编号
	@GoodsName				VARCHAR(500) = '',		--子类名称
	@GoodsAbbName			VARCHAR(500) = '',		--简名
	@Spell					VARCHAR(500) = '',		--拼音码
	@Spec					VARCHAR(500) = '',		--规格
	@Model					VARCHAR(500) = '',		--型号
	@Place					VARCHAR(500) = '',		--产地
	@KG						INT = 0,				--重量
	@PptGroupID				INT = 0,
	@Graph1					INT = 0,
	@Graph2					INT = 0,
	@Graph3					INT = 0,
	@Graph4					INT = 0,
	@Graph5					INT = 0,
	@Remark					VARCHAR(500) = '',		--备注	
	@UPriceType				INT = 0,
	@Brand					VARCHAR(500) = '',		--品牌	
	@IsSerial				INT = 0,				--启用序列号
	@PIC					VARCHAR(500) = '',		--负责人
	@CostMethod				INT = 1,				--成本算法
	@DateType				INT = 1,				--属性设置
	@ValidDays				INT = 0,				--有效期
	@NearbyDays				INT = 0,				--近效期
	@PriceDetails			TVP_BD_Goods_Price_Type	READONLY --价格信息
)
AS
SET NOCOUNT ON

DECLARE @newPath	VARCHAR(MAX),
		@oldPath	VARCHAR(MAX),
		@newSonNum	INT

IF @flag = 1 OR @flag = 2 OR @flag = 3
BEGIN
	IF @flag = 1	--大类新增
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Goods_Type WHERE TypeCode = @TypeCode)
		BEGIN
			RAISERROR('大类信息已存在',16,1)
			RETURN -1
		END
		
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Goods_Type WHERE TypeName = @TypeName)
		BEGIN
			RAISERROR('大类信息已存在',16,1)
			RETURN -1
		END	
		
		IF @ParId = 1 --一级目录，直接新增
		BEGIN
			SELECT @newPath = max(path+1) FROM dbo.BD_Goods_Type WHERE ParID = 1
			
			IF LEN(@newPath)=1
				SET @newPath = '0000'+@newPath
			ELSE IF LEN(@newPath)=2
				SET @newPath = '000'+@newPath
			ELSE IF LEN(@newPath)=3
				SET @newPath = '00'+@newPath
			ELSE IF LEN(@newPath)=4
				SET @newPath = '0'+@newPath
			ELSE IF LEN(@newPath)=5	
				SET @newPath = @newPath
				
			INSERT INTO dbo.BD_Goods_Type
	        ( 
				TypeCode ,
				TypeName ,
				Path ,
				ParID ,
				Lvl ,
				SonNum ,
				Stt
	        )VALUES( 
				@TypeCode , -- TypeCode - varchar(50)
				@TypeName , -- TypeName - varchar(100)
				@newPath , -- Path - varchar(25)
				1 , -- ParID - int
				1 , -- Lvl - int
				0 , -- SonNum - int
				1  -- Stt - bit
			)
			
			IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('新增大类信息失败',16,1)
				RETURN -2
			END
		END
	END
	ELSE	--其他级别
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Goods_Type WHERE TypeCode = @TypeCode)
			BEGIN
				RAISERROR('大类信息已存在',16,1)
				RETURN -1
			END
			
			IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Goods_Type WHERE TypeName = @TypeName)
			BEGIN
				RAISERROR('大类信息已存在',16,1)
				RETURN -1
			END
		
			SELECT	@oldPath = path,
					@newPath = SonNum + 1,
					@newSonNum = SonNum
			FROM	BD_Goods_Type 
			WHERE	GoodsTypeID = @GoodsTypeID
			
			IF LEN(@newPath)=1
				SET @newPath = '0000'+@newPath
			ELSE IF LEN(@newPath)=2
				SET @newPath = '000'+@newPath
			ELSE IF LEN(@newPath)=3
				SET @newPath = '00'+@newPath
			ELSE IF LEN(@newPath)=4
				SET @newPath = '0'+@newPath
			ELSE IF LEN(@newPath)=5	
				SET @newPath = @newPath
				
			--加上父类的ID
			SET @newPath = @oldPath + @newPath
			
			INSERT INTO dbo.BD_Goods_Type
	        ( 
				TypeCode ,
				TypeName ,
				Path ,
				ParID ,
				Lvl ,
				SonNum ,
				Stt
	        )VALUES( 
				@TypeCode , -- TypeCode - varchar(50)
				@TypeName , -- TypeName - varchar(100)
				@newPath , -- Path - varchar(25)
				@GoodsTypeID , -- ParID - int
				LEN(@newPath)/5 , -- Lvl - int
				0 , -- SonNum - int
				1  -- Stt - bit
			)
			
			IF @@ROWCOUNT = 0
			BEGIN
				RAISERROR('新增大类信息失败',16,1)
				RETURN -2
			END
			
			--修改父类的SonNum
			UPDATE dbo.BD_Goods_Type SET SonNum = SonNum + 1 WHERE GoodsTypeID = @GoodsTypeID
	END
END
ELSE
BEGIN
	IF NOT EXISTS(SELECT TOP 1 1 FROM dbo.BD_Goods_Type WHERE GoodsTypeID = @GoodsTypeID)
	BEGIN
		RAISERROR('父类不存在',16,1)
		RETURN -1
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Goods WHERE GoodsNo = @GoodsNo)
	BEGIN
		RAISERROR('相同编号的商品已存在',16,1)
		RETURN -2
	END
	
	IF EXISTS(SELECT TOP 1 1 FROM dbo.BD_Goods WHERE GoodsName = @GoodsName)
	BEGIN
		RAISERROR('相同编号的商品已存在',16,1)
		RETURN -2
	END
	
	INSERT INTO dbo.BD_Goods
	( 
		GoodsNo ,
		GoodsTypeID ,
		GoodsName ,
		GoodsAbbName ,
		Spell ,
		Spec ,
		Model ,
		Place ,
		KG ,
		PptGroupID ,
		Graph1 ,
		Graph2 ,
		Graph3 ,
		Graph4 ,
		Graph5 ,
		CreateDate ,
		ElyID ,
		UpdateDate ,
		UpdateOprId ,
		Stt ,
		Del ,
		Remark ,
		UpdateTag ,
		IsUpload ,
		UPriceType ,
		Brand ,
		IsOS ,
		IsSerial ,
		PIC ,
		CostMethod ,
		DateType ,
		ValidDays ,
		NearbyDays
	)VALUES(
		@GoodsNo , -- GoodsNo - varchar(50)
		@GoodsTypeID , -- GoodsTypeID - bigint
		@GoodsName , -- GoodsName - varchar(100)
		@GoodsAbbName , -- GoodsAbbName - varchar(50)
		@Spell , -- Spell - varchar(50)
		@Spec , -- Spec - varchar(50)
		@Model , -- Model - varchar(50)
		@Place , -- Place - varchar(50)
		@KG , -- KG - decimal
		0 , -- PptGroupID - int
		0 , -- Graph1 - int
		0 , -- Graph2 - int
		0 , -- Graph3 - int
		0 , -- Graph4 - int
		0 , -- Graph5 - int
		GETDATE() , -- CreateDate - datetime
		0 , -- ElyID - int
		GETDATE() , -- UpdateDate - datetime
		0 , -- UpdateOprId - int
		1 , -- Stt - bit
		0 , -- Del - bit
		@Remark , -- Remark - varchar(256)
		0 , -- UpdateTag - int
		0 , -- IsUpload - tinyint
		@UPriceType , -- UPriceType - tinyint
		@Brand , -- Brand - varchar(50)
		0 , -- IsOS - bit
		@IsSerial , -- IsSerial - bit
		@PIC , -- PIC - varchar(50)
		@CostMethod , -- CostMethod - tinyint
		@DateType , -- DateType - tinyint
		@ValidDays , -- ValidDays - int
		@NearbyDays  -- NearbyDays - int
	)
	
	IF @@ROWCOUNT = 0
	BEGIN
		RAISERROR('写入信息失败',16,1)
		RETURN -4
	END
	
	DECLARE @GoodsId INT
	SET @GoodsId = SCOPE_IDENTITY()
	
	--写入价格信息
	CREATE TABLE #PriceTable
	(
		UnitId				INT IDENTITY(1,1),	--自增长
		Unit				VARCHAR(100),		--单位名称
		Convfactor			NUMERIC(24,10),		--换算率
		BarCode				VARCHAR(100),		--条形码
		Price1				NUMERIC(24,10),		--预设价1
		Price2				NUMERIC(24,10),		--预设价2
		Price3				NUMERIC(24,10),		--预设价3
		Price4				NUMERIC(24,10),		--预设价4
		Price5				NUMERIC(24,10)		--预设价5	
	)
	
	INSERT INTO #PriceTable
    ( 
		Unit ,
		Convfactor ,
		BarCode ,
		Price1 ,
		Price2 ,
		Price3 ,
		Price4 ,
		Price5
    )
	SELECT	Unit ,
			Convfactor ,
			BarCode ,
			Price1 ,
			Price2 ,
			Price3 ,
			Price4 ,
			Price5
	FROM	@PriceDetails
	
	--写入最终商品价格表
	INSERT INTO dbo.BD_Goods_Price
    ( 
		GoodsID ,
		UnitID ,
		Unit ,
		Convfactor ,
		BarCode ,
		Price_Rtl ,
		Price1 ,
		Price2 ,
		Price3 ,
		Price4 ,
		Price5 ,
		Price6 ,
		Price7 ,
		Price8 ,
		Price9 ,
		Price10 ,
		Price11 ,
		Price12 ,
		Price13 ,
		Price14 ,
		Price15 ,
		Price16 ,
		Price17 ,
		Price18 ,
		Price19 ,
		Price20 ,
		Stt
    )
    SELECT	@GoodsId,
			UnitId,
			Unit ,
			Convfactor ,
			BarCode,
			0,
			Price1 ,
			Price2 ,
			Price3 ,
			Price4 ,
			Price5 ,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			1
    FROM	#PriceTable
    ORDER BY UnitId
	
	DROP TABLE #PriceTable
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO	



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-4-28
	描述：新增或者修改地区信息
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_InsertAreaInfo]
(
	@AreaID INT,
	@AreaNO 	VARCHAR(10),
	@AreaName 	VARCHAR(50),
	@AreaAbbName	VARCHAR(50),
	@Spell	VARCHAR(50),
	@ParID	INT,
	@Remark VARCHAR(200)
)

AS
SET NOCOUNT ON

IF(@AreaID=0)
BEGIN

	DECLARE @MaxSonPath NUMERIC(25,0),@lvl INT,@Path VARCHAR(50),@allPath VARCHAR(25)='0000000000000000000000000'
	SELECT @MaxSonPath=CAST(MAX(path) AS NUMERIC(25,0))+1,@lvl =MAX(lvl) FROM BD_Area WHERE ParID=@ParID
	IF(@maxSonpath IS NULL)
	SELECT @MaxSonPath=(PATH+'00001'),@lvl =lvl+1 FROM BD_Area WHERE AreaID=@ParID
	SET @Path=LEFT(@allpath,@lvl*5-LEN(@MaxSonPath))+CAST(@MaxSonPath AS VARCHAR(max))

	UPDATE BD_Area SET SonNum+=1 WHERE AreaID=@ParID
	INSERT INTO BD_Area
	        ( AreaNO ,
	          AreaName ,
	          AreaAbbName ,
	          Spell ,
	          ParID ,
	          Lvl ,
	          Path,
	          Remark
	        )
	VALUES  ( @AreaNO , 
			  @AreaName , 
			  @AreaAbbName ,
			  @Spell ,
			  @ParID ,
			  @lvl,
			  @path,
			  @Remark
			)
END
ELSE
BEGIN
	UPDATE BD_Area
	SET		AreaNO =	@AreaNO , 
			AreaName =	@AreaName , 
			AreaAbbName= @AreaAbbName ,
			Spell =		@Spell ,
			Remark	=   @Remark 
	WHERE AreaID=@AreaID
END
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-4-28
	描述：新增或者修改往来单位信息
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_InsertBtypeInfo]
(
	@BTypeID INT,
	@BTypeCode VARCHAR(10),
	@BTypeName VARCHAR(50),
	@BtypeAbbName VARCHAR(50),
	@Spell VARCHAR(50),
	@BtypeTypeID INT,
	@AreaID INT,
	@PriceLvl INT,
	@LinkMan VARCHAR(50),
	@Tel VARCHAR(50),
	@MTel VARCHAR(20),
	@Email VARCHAR(50),
	@Adress VARCHAR(100),
	@Bank VARCHAR(50),
	@BankAcntNo VARCHAR(50),
	@TaxNo VARCHAR(50),
	@Boss VARCHAR(50),
	@Remark VARCHAR(100) 
)

AS
SET NOCOUNT ON

IF(@btypeid=0)
BEGIN
	INSERT INTO BD_Btype
			( BTypeCode ,
			  BTypeName ,
			  BtypeAbbName ,
			  Spell ,
			  BtypeTypeID ,
			  AreaID ,
			  PriceLvl ,
			  LinkMan ,
			  Tel ,
			  MTel ,
			  Email ,
			  Adress ,
			  Bank ,
			  BankAcntNo ,
			  TaxNo ,
			  Boss ,
			  Remark 
			)
	VALUES  ( @BTypeCode ,
			  @BTypeName ,
			  @BtypeAbbName ,
			  @Spell ,
			  @BtypeTypeID ,
			  @AreaID ,
			  @PriceLvl ,
			  @LinkMan ,
			  @Tel ,
			  @MTel ,
			  @Email ,
			  @Adress ,
			  @Bank ,
			  @BankAcntNo ,
			  @TaxNo ,
			  @Boss ,
			  @Remark 
			)
END
ELSE
BEGIN
	UPDATE BD_Btype
	SET		BTypeCode=@BTypeCode ,
			BTypeName=@BTypeName ,
			BtypeAbbName=@BtypeAbbName ,
			Spell =@Spell,
			BtypeTypeID =@BtypeTypeID,
			AreaID =@AreaID,
			PriceLvl =@PriceLvl,
			LinkMan =@LinkMan,
			Tel =@Tel,
			MTel =@Mtel,
			Email =@Email,
			Adress =@Adress,
			Bank =@Bank,
			BankAcntNo =@BankAcntNo,
			TaxNo =@TaxNo,
			Boss =@Boss,
			Remark=@Remark 
	WHERE BTypeID=@BTypeID
END
GO



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

/*------------------------------------------
    作者：李文博
	日期：2014-05-15
	描述：科目TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_InsertListFromDetail
(
	@FinanceID INT,
	@TotalName	VARCHAR(50), 
	@TotalValue	VARCHAR(50),
	@Order INT,
	@IndexTable	VARCHAR(50),
	@detailTable	VARCHAR(50),
	@billType		INT,
	@BillNo			INT
	
)

AS

DECLARE @SQL VARCHAR(MAX)
SET @SQL='  IF EXISTS(SELECT 1 FROM '+@detailTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' Having Sum('+@TotalValue+')<>0)
			BEGIN
				INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,'+@TotalName+',[Order])
				SELECT 	A.BillNo,'+CAST(@billType AS VARCHAR(10))+',A.BillDate,'+CAST(@FinanceID AS VARCHAR(10))+',0,A.ElyID,A.DeptID,Sum('+@TotalValue+'),0,'+CAST(@Order AS VARCHAR(10))+'
				FROM '+@IndexTable+' A 
				INNER JOIN '+@detailTable+' B ON A.BillNo=B.BillNo  WHERE B.BillNo='+CAST(@BillNo AS VARCHAR(10))+'
				GROUP BY A.BillNo,
							 A.BillDate,
							 A.ElyID,
							 A.DeptId
			END '
EXEC(@SQL)
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_BD_LoginUpdate]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_LoginUpdate]
GO
/****** Object:  StoredProcedure [UP_BD_ImportEtype]    Script Date: 12/04/2014 10:40:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		
-- Create date:  2019/05/20
-- Description:	 登录后更新最后登录人信息
-- =============================================
CREATE  PROCEDURE [UP_BD_LoginUpdate]
    (
		@UserID		INT,
		@dbName		VARCHAR(50)
    )
AS

DECLARE @sql NVARCHAR(2000), @ztcount INT
IF ISNULL(@dbname,'')<>''
BEGIN
	SET @sql='SELECT @ztcount=count(1) FROM ['+@dbName+'].dbo.d9ztinfo'
	EXECUTE sp_executesql @sql,N'@ztcount int OUTPUT',@ztcount OUTPUT
	IF @ztcount=0
	BEGIN
		SET @sql='insert into ['+@dbName+'].dbo.D9ZTInfo
					(ZTCode, ZTName, Frozen, Version, IsOpen, ReadOnly, Authorkey, CreateTime, isTryOut, isStop, Pcid, PublicKey, APPID,usercount,Ztnumber)
				select usercode,fullname,0,VersionNo,0,0,'''',getdate(),0,0,'''','''','''' ,1,RIGHT(LEFT(VersionNo,4),3)
				from D9Master.dbo.D9AccountList where dbname='''+@dbName+''' '
		EXEC(@sql)
	END
	
	
	SET @sql=' UPDATE ['+@dbName+'].dbo.SS_Operator SET LoginCount = (LOGINCOUNT+1) WHERE ElyID = '+CAST(@UserID AS VARCHAR(10))+'
               UPDATE D9Master.DBO.D9AccountList SET lastLoginTime=GETDATE(),lastLoginUser='+CAST(@UserID AS VARCHAR(10))+'
                WHERE dbname='''+@dbName+''' '
	EXEC(@sql)
END


GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-4-25
	描述：查询地区信息树型结构
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryAreatypeList]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@Type VARCHAR(10)='tree',
	@Style VARCHAR(10)='Next',
	@FullName VARCHAR(100)='',
	@UserCode VARCHAR(50)='',
	@showStopped BIT=1
)

AS
SET NOCOUNT ON

DECLARE @sql NVARCHAR(max)

SELECT @sql='
;WITH PagingData AS
(
	SELECT AreaID ,
		   AreaNO ,
		   AreaName ,
		   AreaAbbName ,
		   Spell ,
		   Path ,
		   ParID ,
		   SonNum,
		   Lvl ,
		   AreaType ,
		   Stt,
		   Remark,
		   (
				SELECT STUFF((
					SELECT ''\''+AreaName 
					FROM BD_Area a 
					WHERE b.Path LIKE a.PATH+''%'' AND a.AreaID<>b.Areaid ORDER BY Lvl FOR XML PATH('''')
				),1,1,'''') 
			)AS NPath
	FROM BD_Area b'
IF @Type='tree'
BEGIN
	IF @Style='Next'
		SET @SQL+='
	WHERE ParID=@ParId AND AreaID<>1
 '
	ELSE
		SET @SQL+='
	WHERE ParID=(SELECT ParId From BD_Area Where AreaID=@ParId) AND AreaID<>1
 '
END
ELSE
SET @SQL+='
	WHERE Path Like(SELECT Path FROM BD_Area WHERE AreaID=@ParId)+''%''
		AND SonNum=0 AND AreaID<>1
 '
IF @UserCode <> ''
	SET @sql +=' AND AreaNO Like ''%''+@UserCode+''%'' '
IF @FullName <> ''
	SET @sql +=' AND AreaName Like ''%''+@FullName+''%'' '
IF @showStopped=0 AND @Type='tree'
	SET @sql +=' AND Stt=1'	
			
SET @sql +='
)
'

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@ParId','INT',@ParId)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'AreaNO ','','AreaNO ',1,0

GO



/*====================== PROCEDURE: [UP_BD_QueryAreatypeList_demo] ======================*/ 
IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_QueryAreatypeList_demo]') AND type in (N'P', N'PC')) 
DROP PROCEDURE [UP_BD_QueryAreatypeList_demo] 
GO 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
/*------------------------------------------
    作者：韩林
	日期：2014-4-25
	描述：查询地区信息树型结构
	exec [UP_BD_QueryAreatypeList_demo] 1,1,10
	exec [UP_BD_QueryAreatypeList] 1,1,10
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryAreatypeList_demo]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(100)='',
	@UserCode VARCHAR(50)='',
	@showStopped BIT=1
)

AS
SET NOCOUNT ON
begin

DECLARE @sql NVARCHAR(max)

SELECT @sql='
;WITH PagingData AS
(
	SELECT AreaID ,
		   AreaNO ,
		   AreaName ,
		   AreaAbbName ,
		   Spell ,
		   Path ,
		   ParID ,
		   SonNum,
		   Lvl ,
		   AreaType ,
		   Stt,
		   Remark
	FROM BD_Area
	WHERE ParID=@ParId
 '
IF @UserCode <> ''
	SET @sql +=' AND AreaNO Like ''%''+@UserCode+''%'' '
IF @FullName <> ''
	SET @sql +=' AND AreaName Like ''%''+@FullName+''%'' '
IF @showStopped=0
	SET @sql +=' AND Stt=1'	

SET @sql +=') '
/*
SET @sql +='
)

SELECT * from (SELECT COUNT(1) AS ''Rowcount'' FROM AreaType) r
CROSS JOIN
(
	SELECT	ROW_NUMBER() OVER(ORDER BY AreaNO) AS rowid,
	*
	FROM AreaType
	
)area
WHERE area.rowid>(@PageNo-1)*@PageSize
	AND area.rowid<=@PageNo*@PageSize
'
PRINT(@sql)
EXEC sp_executesql @sql,N'@PageNo INT,@PageSize INT,@ParId INT,@FullName VarChar(100),@UserCode VarChar(50) ',@PageNo,@PageSize,@ParId,@FullName,@UserCode
*/
DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@ParId','INT',@ParId)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'AreaNO','','',1,1
end
go



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-4-25
	描述：查询往来单位线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryBtypeList]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(20)='',
	@showStopped BIT=1,
	@UserID INT=1
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50)='',@sql NVARCHAR(max)='',@sqlb NVARCHAR(max)='', @LimitSql NVARCHAR(MAX)='', @WhereSql NVARCHAR(MAX)=''
SELECT @parpath=PATH FROM BD_Btype_Type WHERE BtypeTypeID=@ParId

IF dbo.UF_BD_IsAllBtypeLimit(@UserID) = 0 AND @ParId<>4
BEGIN
 SET @WhereSql = ' WHERE 1=2 '
END ELSE
BEGIN
 SET @WhereSql = ' WHERE 1=1 '
END

IF dbo.UF_BD_IsAllBtypeLimit(@UserID) = 1 AND @ParId<>4
	SET @LimitSql = 'INNER JOIN dbo.UF_BD_BtypeLimit(@UserID) bl ON bl.BTypeID =b.BTypeID'

SELECT @sql='
;WITH PagingData AS 
(
	SELECT	  BTypeCode ,
			  BTypeName ,
			  BTypeAbbName ,
			  b.BTypeID,
			  b.Spell ,
			  b.BtypeTypeID ,
			  TypeName,
			  b.AreaID ,
			  ba.AreaName,
			  b.PriceLvl ,
			  Case WHEN b.pricelvl is null then null else pn.displayname END AS PriceName,
			  LinkMan ,
			  Tel ,
			  MTel ,
			  Email ,
			  Adress ,
			  Bank ,
			  BankAcntNo ,
			  TaxNo ,
			  Boss ,
			  b.Remark,
			  b.Stt
	FROM BD_Btype b
	'+ @LimitSql +'
	INNER JOIN BD_Btype_Type BT ON BT.BtypeTypeID=b.BtypeTypeID
	LEFT JOIN BD_Area ba ON b.AreaID=ba.AreaID
	LEFT JOIN dbo.UF_OT_GoodsPriceLimit(@UserID) p on b.pricelvl=p.pricelvl
	LEFT JOIN BD_PriceName pn ON p.pricelvl=pn.priceid
	'+ @WhereSql +' AND BT.Path LIKE @parpath+''%'' '

IF @UserCode <> ''
	SET @sql +=' AND BTypeCode Like ''%''+@UserCode+''%'' '
IF @FullName <> ''
	SET @sql +=' AND BTypeName Like ''%''+@FullName+''%'' '
IF @showStopped=0
	SET @sql +=' AND b.Stt=1 '	
SET @sql +='
)
'

/***********定义要关联的基础资料sql***********/
SET @sqlb=N'SELECT STUFF((
					SELECT ''\''+TypeName 
					FROM BD_Btype_Type a 
					WHERE BT.Path LIKE a.PATH+''%''  ORDER BY Lvl FOR XML PATH('''')
				),1,1,'''') AS Path ,BtypeTypeID as BID from BD_Btype_Type BT'

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserID','INT',@UserID)


---------------------------------------------------------------------------------------------------
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.BtypeTypeID=_DATA_a.BID',@sqlb)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'BTypeCode ','','BTypeCode ',1,1

GO



IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[UP_BD_QueryBtypeList_BI]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE UP_BD_QueryBtypeList_BI
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：liuke
	日期：2014-12-19
	描述：查询往来单位线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryBtypeList_BI]
(
	@ParID INT=1,
	@PageNo INT=0,
	@PageSize INT=0,
	@RoleID INT=1,
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50)='',@sql NVARCHAR(MAX)='',@limit INT=0,@RightType INT=0 
SELECT @limit=dbo.UF_BD_IsAllBtypeLimit(@OperatorID) --授权人权限 
SELECT @RightType=BtypeLimitTag FROM SS_Role WHERE RoleID=@RoleID --被授权组权限

IF(@ParID=1) --取第一个节点的path
BEGIN
	IF(@limit=2 OR (@limit=1 AND @RightType=2)) --展示全部分类，直接取第一个节点的path
	BEGIN
		SELECT TOP 1 @parpath=[Path] FROM BD_Btype_Type 
		WHERE BtypeTypeID<>1 AND Lvl=1 
		ORDER BY TypeCode 
	END
	ELSE
	BEGIN
		IF (@limit=1 AND @RightType=0) --部分权限(授权人);无权限(被授权组)-------授权人分类集合的第一个节点的path
		BEGIN
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Btype_Type t 
			INNER JOIN dbo.UF_BD_BtypeTypeLimit(@OperatorID) lt ON lt.BtypeTypeID = t.BtypeTypeID 
			WHERE t.BtypeTypeID<>1 AND t.Lvl=1 
			ORDER BY t.TypeCode 
		END
		IF (@limit=0 AND @RightType=1) --无权限(授权人);部分权限(被授权组)-------被授权组分类集合的第一个节点的path
		BEGIN
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Btype_Type t 
			INNER JOIN SS_BtypeType_Jur j ON j.BtypeTypeID = t.BtypeTypeID AND j.RoleID=@RoleID
			WHERE t.BtypeTypeID<>1 AND t.Lvl=1 
			ORDER BY t.TypeCode 
		END
		IF (@limit=1 AND @RightType=1) --部分权限(授权人);部分权限(被授权组)-------授权人和被授权组并集分类集合的第一个节点的path
		BEGIN
			;WITH typeidlist AS 
			(
				SELECT DISTINCT BtypeTypeID FROM (
					SELECT BtypeTypeID FROM SS_BtypeType_Jur WHERE RoleID=@RoleID 
					UNION ALL
					SELECT BtypeTypeID FROM dbo.UF_BD_BtypeTypeLimit(@OperatorID) 
				) o 
			)
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Btype_Type t 
			INNER JOIN typeidlist td ON td.BtypeTypeID = t.BtypeTypeID
			WHERE t.BtypeTypeID<>1 AND t.Lvl=1 
			ORDER BY t.TypeCode 
		END
	END
END
ELSE
BEGIN
	SELECT TOP 1 @parpath=[Path] FROM BD_Btype_Type WHERE BtypeTypeID=@ParID 
END
	
SET @sql=';WITH typeid_temp AS 
(
	SELECT BtypeTypeID FROM BD_Btype_Type WHERE [Path] LIKE @parpath+''%'' AND SonNum=0 
)
,PagingData AS 
(
	SELECT o.BTypeID,o.BTypeCode,o.BTypeName,o.BtypeTypeID,CAST( CASE WHEN kj.RoleID IS NULL THEN 0 ELSE 1 END AS BIT)[multi],o.Stt 
	FROM BD_Btype o 
	INNER JOIN typeid_temp td ON td.BtypeTypeID=o.BtypeTypeID 
	LEFT JOIN SS_Btype_Jur kj ON kj.BTypeID=o.BTypeID AND kj.BtypeTypeID=o.BtypeTypeID AND kj.RoleID=@RoleID 
)'
IF (@limit=1 AND @RightType=0) --部分权限(授权人);无权限(被授权组)-------授权人集合
BEGIN
	SET @sql=';WITH typeid_temp AS 
(
	SELECT BtypeTypeID FROM BD_Btype_Type WHERE [Path] LIKE @parpath+''%'' AND SonNum=0 
)
,PagingData AS 
(
	SELECT o.BTypeID,o.BTypeCode,o.BTypeName,o.BtypeTypeID,CAST(0 AS BIT)[multi],o.Stt 
	FROM BD_Btype o 
	INNER JOIN typeid_temp td ON td.BtypeTypeID=o.BtypeTypeID 
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) lt ON lt.BTypeID=o.BTypeID 
)'
END
IF (@limit=0 AND @RightType=1) --无权限(授权人);部分权限(被授权组)-------被授权组集合
BEGIN
	SET @sql=';WITH path_temp AS (
	SELECT t.[Path] FROM SS_BtypeType_Jur o 
	INNER JOIN BD_Btype_Type t ON t.BtypeTypeID = o.BtypeTypeID 
	WHERE o.RoleID=@RoleID AND o.LimitTag=1 
)
,typeid_temp AS (
	SELECT DISTINCT t.BtypeTypeID FROM BD_Btype_Type t,path_temp 
    WHERE t.BtypeTypeID<>1 AND t.[Path] like path_temp.[Path]+''%'' 
)
,typeid_nocheck AS
(
	SELECT td.BtypeTypeID FROM BD_Btype_Type t 
	INNER JOIN typeid_temp td ON td.BtypeTypeID = t.BtypeTypeID 
	WHERE t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 
)
,typeid_check AS 
(
	SELECT j.BtypeTypeID FROM BD_Btype_Type t 
	INNER JOIN SS_BtypeType_Jur j ON j.BtypeTypeID = t.BtypeTypeID 
	WHERE j.RoleID=@RoleID AND t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 AND j.LimitTag=2 
)
,PagingData AS 
(
	SELECT bd.BTypeID,bd.BTypeCode,bd.BTypeName,bd.BtypeTypeID,CAST(0 AS BIT)[multi],bd.Stt 
	FROM BD_Btype bd 
	INNER JOIN typeid_nocheck b1 ON b1.BtypeTypeID = bd.BtypeTypeID 
	UNION ALL 
	SELECT bd.BTypeID,bd.BTypeCode,bd.BTypeName,bd.BtypeTypeID,CAST(1 AS BIT)[multi],bd.Stt 
	FROM BD_Btype bd 
	INNER JOIN typeid_check b2 ON b2.BtypeTypeID = bd.BtypeTypeID 
	INNER JOIN SS_Btype_Jur j ON j.BTypeID = bd.BTypeID AND j.RoleID=@RoleID 
)'
END
IF (@limit=1 AND @RightType=1) --部分权限(授权人);部分权限(被授权组)-------授权人和被授权组并集集合
BEGIN
	SET @sql=';WITH path_temp AS (
	SELECT t.[Path] FROM SS_BtypeType_Jur o 
	INNER JOIN BD_Btype_Type t ON t.BtypeTypeID = o.BtypeTypeID 
	WHERE o.RoleID=@RoleID AND o.LimitTag=1 
)
,typeid_temp AS (
	SELECT DISTINCT t.BtypeTypeID FROM BD_Btype_Type t,path_temp 
    WHERE t.BtypeTypeID<>1 AND t.[Path] like path_temp.[Path]+''%'' 
)
,typeid_nocheck AS
(
	SELECT o.BtypeTypeID FROM BD_Btype_Type t 
	INNER JOIN typeid_temp o ON o.BtypeTypeID = t.BtypeTypeID 
	WHERE t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 
)
,typeid_check AS 
(
	SELECT j.BtypeTypeID FROM BD_Btype_Type t 
	INNER JOIN SS_BtypeType_Jur j ON j.BtypeTypeID = t.BtypeTypeID 
	WHERE j.RoleID=@RoleID AND t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 AND j.LimitTag=2 
)
,alldataid_cf AS 
(
	SELECT bd.BTypeID,0[multi] 
	FROM BD_Btype bd 
	INNER JOIN typeid_nocheck b1 ON b1.BtypeTypeID = bd.BtypeTypeID 
	UNION ALL 
	SELECT bd.BTypeID,1[multi] 
	FROM BD_Btype bd 
	INNER JOIN typeid_check b2 ON b2.BtypeTypeID = bd.BtypeTypeID 
	INNER JOIN SS_Btype_Jur j ON j.BTypeID = bd.BTypeID AND j.RoleID=@RoleID 
	UNION ALL 
	SELECT o.BTypeID,0[multi] FROM BD_Btype o 
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) lt ON lt.BTypeID = o.BTypeID 
	INNER JOIN BD_Btype_Type t ON t.BtypeTypeID = o.BtypeTypeID 
	WHERE t.[Path] LIKE @parpath+''%''
)
,alldataid AS 
(
	SELECT BTypeID,MAX(multi)[multi] FROM alldataid_cf 
	GROUP BY BTypeID 
)
,PagingData AS 
(
	SELECT o.BTypeID,o.BTypeCode,o.BTypeName,o.BtypeTypeID,CAST(d.multi AS BIT)[multi],o.Stt 
	FROM BD_Btype o 
	INNER JOIN alldataid d ON d.BTypeID = o.BTypeID 
)'
END

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@RoleID','INT',@RoleID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

IF(@limit=0 AND (@RightType=2 OR @RightType=0))
	EXEC SP_EXECUTESQL N'SELECT ''''[ROWCOUNT],''''ROWID,BTypeID,BTypeCode,BTypeName,BtypeTypeID,CAST(0 AS BIT)[multi],Stt FROM BD_Btype WHERE 1<>1 '
ELSE
	EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'BTypeCode ASC','','BTypeCode ASC',1,1

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-4-25
	描述：查询往来单位线性类表
	exec UP_BD_QueryBtypeList_demo 1,1,15
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryBtypeList_demo]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(20)='',
	@showStopped BIT=1
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50),@sql NVARCHAR(max),@sqla NVARCHAR(max),@sqlb NVARCHAR(max)
SELECT @parpath=PATH FROM BD_Btype_Type WHERE BtypeTypeID=@ParId

SELECT @sql='
;WITH PagingData AS 
(
	SELECT	  BTypeCode ,
			  BTypeName ,
			  BTypeAbbName ,
			  BTypeID,
			  b.Spell ,
			  b.BtypeTypeID ,
			  b.AreaID ,
			  PriceLvl ,
			  LinkMan ,
			  Tel ,
			  MTel ,
			  Email ,
			  Adress ,
			  Bank ,
			  BankAcntNo ,
			  TaxNo ,
			  Boss ,
			  b.Remark,
			  b.Stt
	FROM BD_Btype b
	'

IF @UserCode <> ''
	SET @sql +=' AND BTypeCode Like ''%''+@UserCode+''%'' '
IF @FullName <> ''
	SET @sql +=' AND BTypeName Like ''%''+@FullName+''%'' '
IF @showStopped=0
	SET @sql +=' AND b.Stt=1'			
SET @sql +='
)
'
/***********定义要关联的基础资料sql***********/
SET @sqla=N'select BtypeTypeID as BID,TypeName from BD_Btype_Type'
SET @sqlb=N'select AreaID as AID,AreaName from BD_Area'

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)

/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.BtypeTypeID=_DATA_a.BID',@sqla)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_b','Data.AreaID=_DATA_b.AID',@sqlb)



EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'BTypeCode','','',1,1

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询采购明细
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryBuyDetails]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BuyBillIn Int = 1,
	@BuyBillOut Int = 1,
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@FullName VARCHAR(100)='',
	@UserCode VARCHAR(100)='',
	@Ppt1 VARCHAR(100)='',
	@Ppt2 VARCHAR(100)='',
	@Summary VARCHAR(256)='',
	@Description VARCHAR(100)='',
	@Remark VARCHAR(100)='',
	@OrderType1 INT=4,				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额
	@OrderType2 INT=7,				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额			
	@AuQtyFlag INT= 0
)

AS
SET NOCOUNT ON

DECLARE @sql nvarchar(MAX)='',@SqlWhs nvarchar(max),@SqlDept nvarchar(max),@SqlEly nvarchar(max),@SqlPost nvarchar(max),@SqlUnit nvarchar(2000),
		@SqlUnit1 nvarchar(1000),@SqlUnit2 nvarchar(1000),@SqlUnit3 nvarchar(1000),@SqlBtype nvarchar(max),@SqlCreator nvarchar(max),@SqlIn nvarchar(Max),@SqlOut nVarchar(max),@OrderName nvarchar(100)
select  @SqlIn = ' select bill.BillNo,BillDate,101 as BillTypeID,''采购入库单'' as BillName,BillCode,BTypeID,DeptID,ElyID,detail.WhsID,Creator as CreatorID,CreateTime,PosElyID,PosTime,Summary,Description,
		detail.GoodsID,detail.Ppt1ID,detail.Ppt2ID,detail.UnitID,Convfactor,detail.Discount,detail.Qty,detail.BSQty,detail.Price,detail.Total,detail.DiscPrice,detail.DiscTotal,detail.Remark  
		from PD_PchBill bill INNER JOIN PD_PchDetail detail on bill.BillNo = detail.BillNo 
		where IsDraft = 0 '
select @SqlOut = ' select bill.BillNo,BillDate,102 as BillTypeID,''采购退货单'' as BillName,BillCode,BTypeID,DeptID,ElyID,detail.WhsID,Creator as CreatorID,CreateTime,PosElyID,PosTime,Summary,Description,
		detail.GoodsID,detail.Ppt1ID,detail.Ppt2ID,detail.UnitID,Convfactor,detail.Discount,detail.Qty,detail.BSQty,detail.Price,detail.Total,detail.DiscPrice,detail.DiscTotal ,detail.Remark 
		from PD_PchRetBill bill INNER JOIN PD_PchRetDetail detail on bill.BillNo = detail.BillNo 
		where IsDraft = 0 '
if (@BuyBillIn = 1)  
begin  
 if(@BuyBillOut = 1)  
  Select @Sql += @SqlIn+ ' UNION ALL ' ;  
 else  
  Select @Sql += @SqlIn ;  
end  
if (@BuyBillOut = 1)  
 Select @Sql += @SqlOut;  

SELECT @sql='
;WITH Bill AS 
('	+@sql+'
),
 PagingData AS
 (
	select bill.BillNo,BillDate,BillTypeID,BillName,BillCode,bill.BTypeID,DeptID,bill.ElyID,WhsID,CreatorID,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,PosElyID,CONVERT(varchar(100), PosTime, 120) AS PosTime,Summary,Description,
		bill.GoodsID,bill.Ppt1ID,bill.Ppt2ID,G.GoodsNo,G.GoodsName,GP1.Value as Ppt1Name,GP2.Value as Ppt2Name,BT.BTypeCode,BT.BTypeName,UnitID,bill.Convfactor,Discount,bill.Qty,bill.BSQty,Price,Total,DiscPrice,DiscTotal,bill.Remark  
		from Bill bill '
	if(@BTypeID <> '')
		set @sql = @sql + ' INNER JOIN dbo.UF_OT_Split_Int(@BTypeID,'','') B ON bill.BTypeID=B.TypeID '
	if(@DeptID <> '')
		set @sql = @sql + ' INNER JOIN (Select d2.DeptID as TypeID from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'') D ON bill.DeptID=D.TypeID '
	if(@WhsID <> '')
		set @sql = @sql + ' INNER JOIN dbo.UF_OT_Split_Int(@WhsID,'','') W ON bill.WhsID=W.TypeID'
	if(@ElyID <> '')
		set @sql = @sql + '  INNER JOIN dbo.UF_OT_Split_Int(@ElyID,'','') E ON bill.ElyID=E.TypeID '
	set @sql = @sql +' LEFT JOIN BD_GOODS G on bill.GoodsID = G.GoodsID 
					   LEFT JOIN BD_Goods_Ppt1 GP1 on bill.Ppt1ID = GP1.Ppt1ID 
					   LEFT JOIN BD_Goods_Ppt2 GP2 ON bill.Ppt2ID = GP2.Ppt2ID 
					   LEFT JOIN BD_Btype BT ON bill.BTypeID = BT.BTypeID 
					   where 1=1 '
	if(@DateType = 0)
		Set @sql = @sql + ' And BillDate BETWEEN @BeginDate AND DATEADD(day,1,@EndDate) '  
	else
		Set @sql = @sql + ' And CreateTime BETWEEN @BeginDate AND DATEADD(day,1,@EndDate) '  
	if(@Summary <> '')
		Set @sql = @sql + ' And Summary Like''%''+@Summary+''%'''
	if(@Description <> '')
		Set @sql = @sql + ' And Description Like''%''+@Description+''%'''
	if(@Remark <> '')
		Set @sql = @sql + ' And bill.Remark Like''%''+@Remark+''%'''	
	if(@FullName <> '')
		Set @sql = @sql + ' And G.GoodsName Like''%''+@FullName+''%'''
	if(@UserCode <> '')
		Set @sql = @sql + ' And G.GoodsNo Like''%''+@UserCode+''%'''
	if(@Ppt1 <> '')
		Set @sql = @sql + ' And GP1.Value Like''%''+@Ppt1+''%'''
	if(@Ppt2 <> '')
		Set @sql = @sql + ' And GP2.Value Like''%''+@Ppt2+''%'''		
 set @sql = @sql +' )
'

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

---排序字段
select @OrderName = case @OrderType1 
					 when 0 then 'BillCode'
					 when 1 then 'BillTypeID'
					 when 2 then 'BillDate'				
					 when 3 then 'CreateTime'				
					 when 4 then 'PosTime'				
					 when 5 then 'BTypeCode'				
					 when 6 then 'BTypeName'				
					 when 7 then 'GoodsNo'				
					 when 8 then 'GoodsName'				
					 when 9 then 'Qty'				
					 when 10 then 'Price'				
					 when 11 then 'Total'				
					 when 12 then 'Discount'				
					 when 13 then 'DiscPrice'
					 when 14 then 'DiscTotal'
					 else 'PosTime'	 end								
select @OrderName = @OrderName + ',' + case @OrderType2 
					 when 0 then 'BillCode'
					 when 1 then 'BillTypeID'
					 when 2 then 'BillDate'				
					 when 3 then 'CreateTime'				
					 when 4 then 'PosTime'				
					 when 5 then 'BTypeCode'				
					 when 6 then 'BTypeName'				
					 when 7 then 'GoodsNo'				
					 when 8 then 'GoodsName'				
					 when 9 then 'Qty'				
					 when 10 then 'Price'				
					 when 11 then 'Total'				
					 when 12 then 'Discount'				
					 when 13 then 'DiscPrice'
					 when 14 then 'DiscTotal'
					 else 'PosTime'	 end

/***********定义要关联的基础资料sql***********/
SET @SqlWhs = N'SELECT WhsID AS WID ,WhsNO,WhsName from BD_Whs'
SET @SqlDept = N'SELECT DeptID AS DID,DeptCode,DeptName from BD_Dept'
SET @SqlEly = N'SELECT ElyID AS EID,ElyCode,ElyName from BD_Employee'
SET @SqlCreator = N'SELECT ElyID AS CEID,ElyName as Creator from BD_Employee'
SET @SqlPost = N'SELECT ElyID AS PEID,ElyName as PostName from BD_Employee'
SET @SqlUnit = N'SELECT UnitID as UNID,GoodsID as GDID,Unit from BD_Goods_Price '
if(@AuQtyFlag <> 0)
begin
	Set @SqlUnit1 = N'SELECT Unit as Unit1,Convfactor as Convfactor1,GoodsID as GDID1 From BD_Goods_Price where UnitID = 1'
	Set @SqlUnit2 = N'SELECT Unit as Unit2,case when Convfactor IS NULL then 1 else Convfactor end as Convfactor2,GoodsID as GDID2 From BD_Goods_Price where UnitID = 2'
	Set @SqlUnit3 = N'SELECT Unit as Unit3,case when Convfactor IS NULL then 1 else Convfactor end as Convfactor3,GoodsID as GDID3 From BD_Goods_Price where UnitID = 3'
end
--SET @SqlBtype = N'SELECT BTypeID AS BID,BTypeCode,BTypeName from BD_Btype'

------------------添加参数---------------------------------------

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DateType', 'Int', @DateType)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate', 'Date', @BeginDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate', 'Date', @EndDate)
--INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OrderName', 'VarChar(100)', @OrderName)
IF @BTypeID<>''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BTypeID', 'VarChar(MAX)', @BTypeID)
IF @DeptID<>''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID', 'VarChar(MAX)', @DeptID)
IF @ElyID<>''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ElyID', 'VarChar(MAX)', @ElyID)
IF @WhsID<>''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@WhsID', 'VarChar(MAX)', @WhsID)
IF @FullName<>'' OR @UserCode<>''
begin
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName', 'VarChar(100)', @FullName)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode', 'VarChar(50)', @UserCode)
end
IF @Ppt1 <> ''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Ppt1', 'VarChar(100)', @Ppt1)
IF @Ppt2 <> ''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Ppt2', 'VarChar(100)', @Ppt2)
IF @Summary<>''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Summary', 'VarChar(256)', @Summary)
IF @Description<>''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Description', 'VarChar(100)', @Description)
IF @Remark<>''
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Remark', 'VarChar(256)', @Remark)
	
/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Whs', 'Data.WhsID = _DATA_Whs.WID', @SqlWhs)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Dept', 'Data.DeptID = _DATA_Dept.DID', @SqlDept)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ely', 'Data.ElyID = _DATA_Ely.EID', @SqlEly)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_CEly', 'Data.CreatorID = _DATA_CEly.CEID', @SqlCreator)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_PEly', 'Data.PosElyID = _DATA_PEly.PEID', @SqlPost)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice', 'Data.UnitID = _DATA_GPrice.UNID and Data.GoodsID = _DATA_GPrice.GDID', @SqlUnit)
if(@AuQtyFlag <> 0)
begin
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice1', 'Data.GoodsID = _DATA_GPrice1.GDID1 ', @SqlUnit1)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice2', 'Data.GoodsID = _DATA_GPrice2.GDID2 ', @SqlUnit2)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice3', 'Data.GoodsID = _DATA_GPrice3.GDID3 ', @SqlUnit3)
end
--INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Btype', 'Data.BtypeID = _DATA_Btype.BID', @SqlBtype)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,@OrderName,'',@OrderName,1,1

GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：孙志远
	日期：2015-10-09
	描述：查询自定义基础资料线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryCustomBaseList]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@QueryIndex INT=-1,
	@QueryData varchar(50)=''
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50),@sql nvarchar(max)
IF @ParId = 1
BEGIN
	SELECT top 1 @parpath=CustTypeID FROM BD_Custom_Type 
END
ELSE
BEGIN
	SELECT  @parpath=CustTypeID FROM BD_Custom_Type WHERE CustTypeID=@ParId
END

if(@parpath is null)
BEGIN
	SELECT TOP 0 0 FROM BD_Custom  ---返回一一个空记录，不让页面报错
	RETURN 
END
SELECT @sql =
';WITH PagingData AS 
(
	SELECT	G.CustID,G.CustTypeID,CT.TypeName,G.custcode,G.custname
	FROM BD_Custom G 
	Left join BD_Custom_Type CT on G.CustTypeID = CT.CustTypeID 
	where G.CustTypeID = @parpath'
	
SET @sql +=' )	'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@QueryData','VARCHAR(20)',@QueryData)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'CustCode','',''--,1,1 

GO



/****** Object:  StoredProcedure [UP_BD_QueryDeptList]    Script Date: 04/25/2014 10:00:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_QueryDeptList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_QueryDeptList]
GO

/****** Object:  StoredProcedure [UP_BD_QueryDeptList]    Script Date: 04/25/2014 10:00:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-4-25
	描述：查询部门信息
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryDeptList]
(
	@parID INT=0,
	@pageNo INT=0,
	@pageSize INT=0,
	@fullName VARCHAR(50)='',
	@userCode VARCHAR(50)='',
	@showStopped BIT=0,/*是否显示停用信息*/
	@type int = 1,	/*1部门信息;2线性列表*/
	@Style VARCHAR(10)='Next'
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)

SELECT @sql='
	;WITH PagingData AS
	(
	SELECT [DeptID]
		  ,[DeptCode]
		  ,[DeptName]
		  ,[DeptAbbName]
		  ,[Spell]
		  ,[Path]
		  ,[ParID]
		  ,[Lvl]
		  ,[SonNum]
		  ,[Stt]
		  ,[Remark]
		  ,(
				SELECT STUFF((
					SELECT ''\''+DeptName 
					FROM BD_Dept o 
					WHERE d.[Path] LIKE o.[Path]+''%'' AND o.DeptID<>d.DeptID ORDER BY Lvl FOR XML PATH('''')
				),1,1,'''') 
		   ) AS NPath 
	  FROM [BD_Dept] d
	  WHERE '
	
IF @type = 1
BEGIN
	IF @Style='Next'
		SET @sql +='ParID=@parID '
	ELSE 
		SET @sql +='ParID=(SELECT ParID From BD_Dept WHERE DeptID=@parID and DeptID <> 1)'
	IF @showStopped=0
		SET @sql +='AND Stt=1 '
END 

IF @type = 2
BEGIN
	SET @sql +='PATH Like(SELECT Path FROM BD_Dept WHERE DeptID=@parID)+''%'' '
	IF @userCode <> ''
		SET @sql +='AND DeptCode Like ''%''+@userCode+''%'' '
	IF @fullName <> ''
		SET @sql +='AND DeptName Like ''%''+@fullName+''%'' '
	SET @sql+='AND SonNum=0 '
END 



SET @sql +=') '
--SET @sql +='
--) 

--SELECT *,(SELECT COUNT(1) FROM DB_DeptInfo) AS [rowcount] 
--FROM 
--(
--	SELECT	ROW_NUMBER() OVER(ORDER BY DeptCode) AS rowid,* 
--	FROM DB_DeptInfo 
--)db 
--WHERE db.rowid>(@pageNo-1)*@pageSize 
--	AND db.rowid<=@pageNo*@pageSize 
--'
--PRINT(@sql)
--EXEC sp_executesql @sql,N'@parID INT,@pageNo INT,@pageSize INT,@FullName VarChar(100),@UserCode VarChar(50)',@parID,@pageNo,@pageSize,@fullName,@userCode

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@parID','INT',@parID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@fullName','VARCHAR(100)',@fullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@userCode','VARCHAR(50)',@userCode)

EXEC UP_OT_Paging @sql,@TVP,@pageNo,@pageSize,'DeptCode','','',1,1
end

--EXEC UP_BD_QueryDeptList


GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-4-30
	描述：查询商品线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryDraftBill]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate Datetime,
	@EndDate Datetime,
	@BillTypeID varchar(500) ='',
	@BillNO varchar(50) = '',
	@BTypeID varchar(500) = '',
	@DTypeID varchar(500) = '',
	@ETypeID varchar(500) = '',
	@KTypeID varchar(500) = '',
	@ATypeID varchar(500) = '',
	@GoodsNO varchar(50) = '',
	@GoodsName varchar(500) = '',
	@LogistBillNo Int = 0,
	@Summary varchar(100) = '',
	@Description varchar(100) = ''
)

AS
SET NOCOUNT ON

DECLARE @sql nvarchar(max),@SqlWhs nvarchar(max),@SqlDept nvarchar(max),@SqlEly nvarchar(max),
		@SqlBillType nvarchar(max),@SqlBtype nvarchar(max),@SqlCreator nvarchar(max)
SELECT @sql =
';WITH PagingData AS 
(
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,WhsID,101 as BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_PchBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,WhsID,102 as BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_PchRetBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,WhsID,201 as BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_SellBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,WhsID,202 as BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_SellRetBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,0 as BtypeID,DeptID,ElyID,0 as WhsID,301 as BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_AllotBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,0 as BtypeID,DeptID,ElyID,WhsID,302 as BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_AdjPriceBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,WhsID,BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_InOutWhsBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,0 as BtypeID,DeptID,ElyID,WhsID,BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From PD_LossSpillBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,0 as WhsID,BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From MF_PayRecBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,0 as WhsID,BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From MF_FeeRecBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,0 as BtypeID,DeptID,ElyID,0 as WhsID,406 as BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From MF_TransferBill where IsDraft = 1
	UNION ALL
	SELECT BillNo,BillCode,BillDate,BtypeID,DeptID,ElyID,0 as WhsID,BillTypeID,Creator,Total,CONVERT(varchar(100),CreateTime,120) as CreateTime,Summary,Description From MF_ARAPBill where IsDraft = 1 '

SET @sql +=' )	'

/***********定义要关联的基础资料sql***********/
SET @SqlWhs = N'SELECT WhsID AS WID,WhsNO ,WhsName from BD_Whs'
SET @SqlDept = N'SELECT DeptID AS DID,DeptCode, DeptName from BD_Dept'
SET @SqlEly = N'SELECT ElyID AS EID, ElyCode,ElyName from BD_Employee'
SET @SqlCreator = N'SELECT ElyID AS CEID,ElyCode as CElyCode ,ElyName as CElyName from BD_Employee'
SET @SqlBtype = N'SELECT BTypeID AS BID,BTypeCode,BTypeName from BD_Btype'
SET @SqlBillType = N'select BillTypeID as BTID,BillName from PD_BillType'

DECLARE  @TVP AS TVP_Paging_Param
/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Whs', 'Data.WhsID = _DATA_Whs.WID', @SqlWhs)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Dept', 'Data.DeptID = _DATA_Dept.DID', @SqlDept)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ely', 'Data.ElyID = _DATA_Ely.EID', @SqlEly)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_CEly', 'Data.Creator = _DATA_CEly.CEID', @SqlCreator)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Btype', 'Data.BtypeID = _DATA_Btype.BID', @SqlBtype)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_BillType', 'Data.BillTypeID = _DATA_BillType.BTID', @SqlBillType)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'BillCode','','BillDate'

GO



/****** Object:  StoredProcedure [UP_BD_QueryEmployeeList]    Script Date: 04/25/2014 10:10:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_QueryEmployeeList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_QueryEmployeeList]
GO

/****** Object:  StoredProcedure [UP_BD_QueryEmployeeList]    Script Date: 04/25/2014 10:10:14 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-4-25
	描述：查询职员信息
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryEmployeeList]
(
	@ParID INT=1,
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(50)='',
	@showStopped BIT=1
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)

SELECT @sql='
;WITH PathData AS(
	SELECT DeptId 
	FROM BD_Dept 
	WHERE [Path] LIKE 
					(
						SELECT [Path] 
						FROM BD_Dept 
						WHERE DeptId=@ParID
					)+''%''
)
,PagingData AS
(
SELECT o.[ElyID]
      ,o.[ElyCode]
      ,o.[ElyName]
      ,o.[Spell]
      ,o.[Sex]
      ,o.[Birthday]
      ,o.[IdCard]
      ,o.[Addr]
      ,o.[PostCode]
      ,o.[Tel]
      ,o.[MTel]
      ,o.[Email]
      ,o.[QQ]
      ,o.[EntryDate]
      ,o.[DeptId]
      ,o.[DemitDate]
      ,o.[Stt]
      ,o.[Remark]
      ,c.[DeptName]
	  ,(
			SELECT STUFF((
				SELECT ''\''+DeptName 
				FROM BD_Dept o 
				WHERE c.[Path] LIKE o.[Path]+''%'' AND o.DeptId<>c.DeptId ORDER BY Lvl FOR XML PATH('''')
			),1,1,'''') 
	   )+''\''+c.[DeptName] AS NPath 
  FROM [BD_Employee] o 
  INNER JOIN [BD_Dept] c ON o.DeptId=c.DeptId 
  WHERE o.ElyID<>1 '
IF @ParID <> 1
	--SET @sql +='AND o.DeptId=@ParID '
	--SET @sql +='AND o.DeptId IN(SELECT DeptId FROM PathData) '
	SET @sql +='AND EXISTS (SELECT 1 FROM PathData WHERE DeptId=o.DeptId) '
IF @UserCode <> ''
	SET @sql +='AND o.ElyCode Like ''%''+@UserCode+''%'' '
IF @FullName <> ''
	SET @sql +='AND o.ElyName Like ''%''+@FullName+''%'' '
IF @showStopped=0
	SET @sql +='AND o.Stt=1 '
SET @sql +=') '
--SET @sql +='
--)

--SELECT *,(SELECT COUNT(1) FROM DB_EmployeeInfo) AS [rowcount] 
--FROM 
--(
--	SELECT	ROW_NUMBER() OVER(ORDER BY ElyCode) AS rowid,* 
--	FROM DB_EmployeeInfo
--)db 
--WHERE db.rowid>(@PageNo-1)*@PageSize 
--	AND db.rowid<=@PageNo*@PageSize 
--'
--PRINT(@sql)
--EXEC sp_executesql @sql,N'@ParID INT,@PageNo INT,@PageSize INT,@FullName VarChar(100),@UserCode VarChar(50)',@ParID,@PageNo,@PageSize,@FullName,@UserCode

--exec [UP_BD_QueryEmployeeList] 1,1,10,'','001',1

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@ParId','INT',@ParId)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'ElyCode','','',1,0
end





GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：WangWei
	日期：2014-4-25
	描述：查询财务项目表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryFinanceList]
(
	@ParId INT=0,
	@showStopped BIT=0
	,@OperatorID INT
)

AS
SET NOCOUNT ON


DECLARE @parpath VARCHAR(50),@sql nvarchar(max)
SET @parpath=''
if @ParId<>0
BEGIN
	SELECT TOP 1 @parpath=[PATH] FROM BD_Finance WHERE FinanceID=@ParId
END

	DECLARE @isALL INT =0
	SELECT @isALL=dbo.UF_BD_IsAllAtypeLimit(@OperatorID) --是否所有权限


SELECT @sql='
;WITH Data AS 
(
	SELECT	   b.[FinanceID]
			  ,b.[FinanceNO]
			  ,(dbo.UF_OT_StringReplace(b.Lvl,3)+b.[FinanceNO]) as FinanceCode
			  ,b.[FinanceName]
			  ,b.[Path]
			  ,b.[ParID]
			  ,b.[Lvl]
			  ,b.[SonNum]
			  ,b.[Remark]
			  ,b.[Stt]
			  ,b.[SysRow]
			  ,b.LoanStt
	FROM BD_Finance b'
	IF @isALL=1
	BEGIN
	SELECT @sql+=' 
			 INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) al ON b. FinanceID=al.FinanceID	'	
	END
IF @isALL=0
	SELECT @sql+=' WHERE 1=0 '
else
BEGIN
	
	SELECT @sql+='
		WHERE b.[Path] LIKE @parpath+''%'' AND Lvl>=2 '
	IF @showStopped=0  --Stt==2表示永远不显示
		SET @sql +=' AND Stt=1'			
	ELSE
		SET @sql +=' AND (Stt=1 OR stt=0)'		
END	
		 
SET @sql +='
)


SELECT	(SELECT COUNT(1) FROM Data) AS [rowcount]
		,ROW_NUMBER() OVER(ORDER BY [path]) AS rowid
		,*
		
FROM Data
ORDER BY [path]
'
--PRINT(@sql)
EXEC sp_executesql @sql,N'@parpath VarChar(50),@OperatorID INT ',@parpath=@parpath,@OperatorID =@OperatorID


GO



IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[UP_BD_QueryFinanceList_BI]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE UP_BD_QueryFinanceList_BI
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：liuke
	日期：2014-12-19
	描述：查询财务项目表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryFinanceList_BI]
(
	@ParID INT=1,
	@RoleID INT,
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50)='',@sql NVARCHAR(MAX)='',@limit INT=0,@RightType INT=0 
SELECT @limit=dbo.UF_BD_IsAllAtypeLimit(@OperatorID) --授权人权限 
SELECT @RightType=FinanceLimitTag FROM SS_Role WHERE RoleID=@RoleID --被授权组权限

IF(@ParID=1) --取第一个节点的path
BEGIN
	IF(@limit=2 OR (@limit=1 AND @RightType=2)) --展示全部分类，直接取第一个节点的path
	BEGIN
		SELECT TOP 1 @parpath=[Path] FROM BD_Finance 
		WHERE FinanceID<>1 AND Lvl=1 
		ORDER BY FinanceNO 
	END
	ELSE
	BEGIN
		IF (@limit=1 AND @RightType=0) --部分权限(授权人);无权限(被授权组)-------授权人分类集合的第一个节点的path
		BEGIN
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Finance t 
			INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) lt ON lt.FinanceID = t.FinanceID 
			WHERE t.FinanceID<>1 AND t.Lvl=1 
			ORDER BY t.FinanceNO 
		END
		IF (@limit=0 AND @RightType=1) --无权限(授权人);部分权限(被授权组)-------被授权组分类集合的第一个节点的path
		BEGIN
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Finance t 
			INNER JOIN SS_Finance_Jur j ON j.FinanceID = t.FinanceID AND j.RoleID=@RoleID
			WHERE t.FinanceID<>1 AND t.Lvl=1 
			ORDER BY t.FinanceNO 
		END
		IF (@limit=1 AND @RightType=1) --部分权限(授权人);部分权限(被授权组)-------授权人和被授权组并集分类集合的第一个节点的path
		BEGIN
			;WITH typeidlist AS 
			(
				SELECT DISTINCT FinanceID FROM (
					SELECT FinanceID FROM SS_Finance_Jur WHERE RoleID=@RoleID 
					UNION ALL
					SELECT FinanceID FROM dbo.UF_BD_AtypeLimit(@OperatorID) 
				) o 
			)
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Finance t 
			INNER JOIN typeidlist td ON td.FinanceID = t.FinanceID
			WHERE t.FinanceID<>1 AND t.Lvl=1 
			ORDER BY t.FinanceNO 
		END
	END
END
ELSE
BEGIN
	SELECT TOP 1 @parpath=[Path] FROM BD_Finance WHERE FinanceID=@ParID 
END

SET @sql='
;WITH PagingData AS 
(
	SELECT f.FinanceID,f.FinanceNO,(dbo.UF_OT_StringReplace(f.Lvl,3)+f.[FinanceNO]) as FinanceCode,f.FinanceName,f.ParID,f.[Path],f.SonNum,CAST( CASE WHEN j.RoleID IS NULL THEN 0 ELSE 1 END AS BIT)[multi],f.Stt 
	FROM BD_Finance f 
	LEFT JOIN SS_Finance_Jur j ON j.FinanceID = f.FinanceID AND j.RoleID=@RoleID '
IF (@limit=1 AND @RightType=0) --部分权限(授权人);无权限(被授权组)-------授权人集合
BEGIN
	SET @sql=';WITH PagingData AS 
(
	SELECT f.FinanceID,f.FinanceNO,(dbo.UF_OT_StringReplace(f.Lvl,3)+f.[FinanceNO]) as FinanceCode,f.FinanceName,f.ParID,f.[Path],f.SonNum,CAST(0 AS BIT)[multi],f.Stt 
	FROM BD_Finance f 
	INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) lt ON lt.FinanceID=f.FinanceID '
END
IF (@limit=0 AND @RightType=1) --无权限(授权人);部分权限(被授权组)-------被授权组集合
BEGIN
	SET @sql=';WITH PagingData AS 
(
	SELECT f.FinanceID,f.FinanceNO,(dbo.UF_OT_StringReplace(f.Lvl,3)+f.[FinanceNO]) as FinanceCode,f.FinanceName,f.ParID,f.[Path],f.SonNum,CAST(1 AS BIT)[multi],f.Stt 
	FROM BD_Finance f 
	INNER JOIN SS_Finance_Jur j ON j.FinanceID = f.FinanceID AND j.RoleID=@RoleID '
END
IF (@limit=1 AND @RightType=1) --部分权限(授权人);部分权限(被授权组)-------授权人和被授权组并集集合
BEGIN
	SET @sql=';WITH alldataid_cf AS 
(
	SELECT FinanceID,0[multi] FROM dbo.UF_BD_AtypeLimit(@OperatorID) 
	UNION ALL 
	SELECT FinanceID,1[multi] FROM SS_Finance_Jur WHERE RoleID=@RoleID 
)
,alldataid AS 
(
	SELECT FinanceID,MAX(multi)[multi] FROM alldataid_cf 
	GROUP BY FinanceID 
)
,PagingData AS 
(
	SELECT f.FinanceID,f.FinanceNO,(dbo.UF_OT_StringReplace(f.Lvl,3)+f.[FinanceNO]) as FinanceCode,f.FinanceName,f.ParID,f.[Path],f.SonNum,CAST(d.multi AS BIT)[multi],f.Stt 
	FROM BD_Finance f 
	INNER JOIN alldataid d ON d.FinanceID = f.FinanceID '
END
SET @sql+='
	WHERE f.[Path] LIKE @parpath+''%'' AND f.Lvl>=2 
)
SELECT (SELECT COUNT(1) FROM PagingData) AS [ROWCOUNT],ROW_NUMBER() OVER(ORDER BY [path]) AS ROWID,* 
FROM PagingData 
ORDER BY [path] 
'

PRINT(@sql)
IF(@limit=0 AND (@RightType=2 OR @RightType=0))
	EXEC SP_EXECUTESQL N'SELECT ''''[ROWCOUNT],''''ROWID,FinanceID,FinanceNO,''''FinanceCode,FinanceName,ParID,[Path],SonNum,CAST(0 AS BIT)[multi],Stt FROM BD_Finance WHERE 1<>1 '
ELSE
	EXEC SP_EXECUTESQL @sql,N'@parpath VarChar(50),@RoleID INT,@OperatorID INT',@parpath,@RoleID,@OperatorID

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-4-30
	描述：查询商品线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryGoodsList]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@QueryIndex INT=-1,
	@QueryData varchar(50)='',
	@CostMethod INT=0, --0：全部，1：移动加权，2：手工指定
	@showStopped BIT=1
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50),@sql nvarchar(max)
SELECT  @parpath=PATH FROM BD_Goods_Type WHERE GoodsTypeID=@ParId
if(@parpath is null)
BEGIN
	SELECT TOP 0 0 FROM BD_Goods  ---返回一一个空记录，不让页面报错
	RETURN 
END
SELECT @sql =
';WITH PagingData AS 
(
	SELECT	G.GoodsID,GoodsNo,GoodsName,GoodsAbbName,Spell,Spec,Brand,Model,Place,KG,G.Stt,(case G.Stt when 1 then '''' else ''停用'' end) as SFlag,
		(case G.CostMethod when 1 then ''移动加权平均'' else ''手工指定'' end) as CostMethodShow,G.ValidDays,
		GP.Unit,GP.BarCode,GP.Price1,GP.Price2,GP.Price3,GP.Price4,GP.Price5,GP.Price6,GP.Price7,GP.Price8,GP.Price9,GP.Price10,GP.Price11,GP.Price12,GP.Price13,GP.Price14,GP.Price15,G.Remark,G.GoodsTypeID,G.IsUpload as isuplaod
	FROM BD_Goods G 
	Left join BD_Goods_Price GP on G.GoodsID = GP.GoodsID '
	IF @QueryIndex = 5 and @QueryData<>''
		SET @sql +=' Inner Join (Select distinct GoodsID from BD_Goods_Price where  BarCode like ''%'' + @QueryData + ''%'') gp1 on gp.GoodsID =  gp1.GoodsID '
	SET @sql +=' INNER JOIN BD_Goods_Type typeid on typeid.GoodsTypeID=G.GoodsTypeID
	WHERE typeid.Path LIKE @parpath+''%'' And Gp.UnitID = 1 '
	IF @showStopped=0
		SET @sql +=' AND G.Stt=1 '	
	IF @QueryIndex = 0 and @QueryData<>''
		SET @sql +=' and (G.GoodsNo like ''%'' + @QueryData + ''%'' or G.GoodsName like ''%'' + @QueryData + ''%'' or G.Model like ''%'' + @QueryData + ''%'' or G.Spec like ''%'' + @QueryData + ''%'')'
	IF @QueryIndex = 1 and @QueryData<>''
		SET @sql +=' and G.GoodsNo like ''%'' + @QueryData + ''%'''
	IF @QueryIndex = 2 and @QueryData<>''
		SET @sql +=' and G.GoodsName like ''%'' + @QueryData + ''%'''
	IF @QueryIndex = 3 and @QueryData<>''
		SET @sql +=' and G.Spec like ''%'' + @QueryData + ''%'''
	IF @QueryIndex = 4 and @QueryData<>''
		SET @sql +=' and G.Model like ''%'' + @QueryData + ''%'''
	IF @CostMethod <> 0
		Set @sql += ' and G.CostMethod =  @CostMethod '
	--IF @QueryIndex = 5 and @QueryData<>''
	--	SET @sql +=' and GP.BarCode like ''%'' + @QueryData + ''%'''	
SET @sql +=' )	'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@QueryData','VARCHAR(20)',@QueryData)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@CostMethod','INT',@CostMethod)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'GoodsNo','','',1,1 

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-4-30
	描述：查询商品多编号线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryGoodsNOList]
(
	@BTypeID INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@UserCode varchar(50)='',
	@FullName varchar(50)=''
)

AS
SET NOCOUNT ON

DECLARE @sql nvarchar(max)
SELECT @sql =
';WITH PagingData AS 
(
	SELECT @BTypeID AS BTypeID,(SELECT BTypeName FROM BD_Btype WHERE BTypeID=@BTypeID) BTypeName,a.GoodsID,a.GoodsName,a.GoodsNo AS MGoodsNo,b.GoodsNO 
	FROM BD_Goods a LEFT JOIN BD_Goods_NO b ON a.GoodsID = b.GoodsID  AND b.BtypeID=@BTypeID
    where a.STT = 1'
    IF @BTypeID=0
		SET @sql +=' AND 1=2'
	if @UserCode <> ''
	  SET @sql += ' AND A.GoodsNo like ''%''+@UserCode+''%'''
	if @FullName <> ''
	  SET @sql += ' AND A.GoodsName like ''%''+@FullName+''%'''
SET @sql +=') '	

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BTypeID','INT',@BTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(50)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(20)',@UserCode)
EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'MGoodsNo','','' 
--print @sql
--EXEC sp_executesql @sql,N'@BTypeID INT,@PageNo INT,@PageSize INT,@UserCode Varchar(50),@FullName Varchar(50)',@BTypeID,@PageNo,@PageSize,@UserCode,@FullName

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-4-30
	描述：查询商品线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryGoodsUpLoadList]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@IsUpload Int=0,
	@Stt int = 0, --0为不显示停用，1为显示停用
	@priceType int = 1, --切换价格信息
	@IsOS int = 0
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50),@sql nvarchar(max)
SELECT  @parpath=PATH FROM BD_Goods_Type WHERE GoodsTypeID=@ParId
declare @priceStr varchar(max)=''
declare @priceStr1 varchar(max)=''
declare @priceStr2 varchar(max)=''
if(@IsUpload = 0)
begin
	select @priceStr = case @priceType when 1 then 'Gp.Price1'
								   when 2 then 'Gp.Price2' 
								   when 3 then 'Gp.Price3' 
								   when 4 then 'Gp.Price4' 
								   when 5 then 'Gp.Price5' 
								   else 'Gp.Price1' end
	select @priceStr1 = case @priceType when 1 then 'Gp2.Price1'
								   when 2 then 'Gp2.Price2' 
								   when 3 then 'Gp2.Price3' 
								   when 4 then 'Gp2.Price4' 
								   when 5 then 'Gp2.Price5' 
								   else 'Gp2.Price1' end	
	select @priceStr2 = case @priceType when 1 then 'Gp3.Price1'
								   when 2 then 'Gp3.Price2' 
								   when 3 then 'Gp3.Price3' 
								   when 4 then 'Gp3.Price4' 
								   when 5 then 'Gp3.Price5' 
								   else 'Gp3.Price1' end									   						   
End		
Else
Begin
	Select @priceStr = ' case UPriceType when 1 then Gp.Price1 when 2 then Gp.Price2 when 3 then Gp.Price3 when 4 then Gp.Price4 when 5 then Gp.Price5 else Gp.Price1 end '
	Select @priceStr1 = ' case UPriceType when 1 then Gp2.Price1 when 2 then Gp2.Price2 when 3 then Gp2.Price3 when 4 then Gp2.Price4 when 5 then Gp2.Price5 else Gp2.Price1 end '
	Select @priceStr2 = ' case UPriceType when 1 then Gp3.Price1 when 2 then Gp3.Price2 when 3 then Gp3.Price3 when 4 then Gp3.Price4 when 5 then Gp3.Price5 else Gp3.Price1 end '
End						   
SELECT @sql =
';WITH PagingData AS 
(
	SELECT	G.GoodsID as outerid,GoodsNo as goodsno,GoodsName as fullname,GoodsAbbName as name,'+@priceStr+' as price,'+@priceStr1+' as price1,'+@priceStr2+' as price2,Spec as standard,Model as type,Place as area,Gp1.Unit as unit,
	G.GoodsTypeID as parouterid,Gp2.Unit as unit1,Gp2.Convfactor as unitrate1,Gp3.Unit as unit2,Gp3.Convfactor as unitrate2,GP1.BarCode as BarCode,
	GP2.BarCode as BarCode1,GP3.BarCode as BarCode2,0 as isdelete,G.Stt,G.IsOS,G.KG,case G.Stt when 0 then 1 else 0 end as isstop '
	+ case when @IsUpload = 1 then ',CASE IsUpload WHEN 1 THEN ''否'' ELSE ''是'' END AS IsReplace' else '' end + '
	FROM BD_Goods G		
	Left join BD_Goods_Price GP on G.GoodsID = GP.GoodsID '
	SET @sql +=' INNER JOIN BD_Goods_Type typeid on typeid.GoodsTypeID=G.GoodsTypeID
	Left join BD_Goods_Price GP1 on G.GoodsID = GP1.GoodsID and Gp1.UnitID = 1
	Left join BD_Goods_Price GP2 on G.GoodsID = GP2.GoodsID and Gp2.UnitID = 2
	Left join BD_Goods_Price GP3 on G.GoodsID = GP3.GoodsID and Gp3.UnitID = 3
	WHERE typeid.Path LIKE @parpath+''%'' And Gp.UnitID = 1 ' 
	+ case when @IsOS = 0 then '' else ' And IsOS = 1 ' end
	+ case when @IsUpload = 0 then ' And IsUpload= @IsUpload ' else ' And IsUpload <> 0 '	end
	+ case when @Stt = 0 and  @IsUpload = 0 then ' AND G.Stt=1 ' else '' end
SET @sql +=' )	'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@IsUpload','INT',@IsUpload)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'goodsno','','',1,1 

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博
	日期：2014-04-30
	描述：查询存货仓库线性表
-------------------------------------------*/
CREATE PROCEDURE UP_BD_QueryKtypeList
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(20)='',
	@showStopped BIT=1,
	@OperatorID INT
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50) = '',@sql NVARCHAR(max) = '', @LimitSql NVARCHAR(MAX) = '', @WhereSql NVARCHAR(MAX) = ''

SELECT @parpath=PATH FROM BD_Whs_Type WHERE WhsTypeID=@ParId

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0
BEGIN
 SET @WhereSql = ' WHERE 1=2 '
END ELSE
BEGIN
 SET @WhereSql = ' WHERE 1=1 '
END

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
	SET @LimitSql = 'INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =k.WhsID '
	

SELECT @sql='
;WITH PagingData AS 
(
	SELECT	    k.WhsID,
				WhsNO,
			    WhsName,
				WhsAbbName,
				Spell,
				k.WhsTypeID,
				TypeName,
				AreaID,
				Responsible,
				LinkMan,
				Tel,
				[Address],
				PostCode,
				Stt,
				Remark
	FROM BD_Whs k 
	'+ @LimitSql +'
	INNER JOIN 
	(
		SELECT   WhsTypeID,
				 TypeName
		FROM BD_Whs_Type 
		WHERE Path LIKE @parpath+''%''
	)typeid ON typeid.WhsTypeID=k.WhsTypeID
	'+ @WhereSql
IF @UserCode <> ''
	SET @sql +=' AND WhsNO Like ''%''+@UserCode+''%'''
IF @FullName <> ''
	SET @sql +=' AND WhsName Like ''%''+@FullName+''%'''	
IF @showStopped=0
	SET @sql +=' AND Stt=1'	

SET @sql +=') '
	
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(50)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(20)',@UserCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'WhsNO ASC','','ROWID ASC',1,0

GO



IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[UP_BD_QueryKtypeList_BI]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE UP_BD_QueryKtypeList_BI
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：liuke
	日期：2014-12-19
	描述：查询存货仓库
-------------------------------------------*/
CREATE PROCEDURE UP_BD_QueryKtypeList_BI
(
	@ParID INT=1,
	@PageNo INT=0,
	@PageSize INT=0,
	@RoleID INT=1,
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50)='',@sql NVARCHAR(MAX)='',@limit INT=0,@RightType INT=0 
SELECT @limit=dbo.UF_BD_IsAllKtypeLimit(@OperatorID) --授权人权限
SELECT @RightType=WhsLimitTag FROM SS_Role WHERE RoleID=@RoleID --被授权组权限

IF(@ParID=1) --取第一个节点的path
BEGIN
	IF(@limit=2 OR (@limit=1 AND @RightType=2)) --展示全部分类，直接取第一个节点的path
	BEGIN
		SELECT TOP 1 @parpath=[Path] FROM BD_Whs_Type 
		WHERE WhsTypeID<>1 AND Lvl=1 
		ORDER BY TypeCode 
	END
	ELSE
	BEGIN
		IF (@limit=1 AND @RightType=0) --部分权限(授权人);无权限(被授权组)-------授权人分类集合的第一个节点的path
		BEGIN
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Whs_Type t 
			INNER JOIN UF_BD_KtypeTypeLimit(@OperatorID) lt ON lt.WhsTypeID = t.WhsTypeID 
			WHERE t.WhsTypeID<>1 AND t.Lvl=1 
			ORDER BY t.TypeCode 
		END
		IF (@limit=0 AND @RightType=1) --无权限(授权人);部分权限(被授权组)-------被授权组分类集合的第一个节点的path
		BEGIN
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Whs_Type t 
			INNER JOIN SS_WhsType_Jur j ON j.WhsTypeID = t.WhsTypeID AND j.RoleID=@RoleID
			WHERE t.WhsTypeID<>1 AND t.Lvl=1 
			ORDER BY t.TypeCode 
		END
		IF (@limit=1 AND @RightType=1) --部分权限(授权人);部分权限(被授权组)-------授权人和被授权组并集分类集合的第一个节点的path
		BEGIN
			;WITH typeidlist AS 
			(
				SELECT DISTINCT WhsTypeID FROM (
					SELECT WhsTypeID FROM SS_WhsType_Jur WHERE RoleID=@RoleID 
					UNION ALL
					SELECT WhsTypeID FROM UF_BD_KtypeTypeLimit(@OperatorID) 
				) o 
			)
			SELECT TOP 1 @parpath=t.[Path] FROM BD_Whs_Type t 
			INNER JOIN typeidlist td ON td.WhsTypeID = t.WhsTypeID
			WHERE t.WhsTypeID<>1 AND t.Lvl=1 
			ORDER BY t.TypeCode 
		END
	END
END
ELSE
BEGIN
	SELECT TOP 1 @parpath=[Path] FROM BD_Whs_Type WHERE WhsTypeID=@ParID 
END

SET @sql=';WITH typeid_temp AS 
(
	SELECT WhsTypeID FROM BD_Whs_Type WHERE [Path] LIKE @parpath+''%'' AND SonNum=0 
)
,PagingData AS 
(
	SELECT o.WhsID,o.WhsNO,o.WhsName,o.WhsTypeID,CAST( CASE WHEN kj.RoleID IS NULL THEN 0 ELSE 1 END AS BIT)[multi],o.Stt 
	FROM BD_Whs o 
	INNER JOIN typeid_temp td ON td.WhsTypeID=o.WhsTypeID 
	LEFT JOIN SS_Whs_Jur kj ON kj.WhsID=o.WhsID AND kj.WhsTypeID=o.WhsTypeID AND kj.RoleID=@RoleID 
)'
IF (@limit=1 AND @RightType=0) --部分权限(授权人);无权限(被授权组)-------授权人集合
BEGIN
	SET @sql=';WITH typeid_temp AS 
(
	SELECT WhsTypeID FROM BD_Whs_Type WHERE [Path] LIKE @parpath+''%'' AND SonNum=0 
)
,PagingData AS 
(
	SELECT o.WhsID,o.WhsNO,o.WhsName,o.WhsTypeID,CAST(0 AS BIT)[multi],o.Stt 
	FROM BD_Whs o 
	INNER JOIN typeid_temp td ON td.WhsTypeID=o.WhsTypeID 
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) lt ON lt.WhsID=o.WhsID 
)'
END
IF (@limit=0 AND @RightType=1) --无权限(授权人);部分权限(被授权组)-------被授权组集合
BEGIN
	SET @sql=';WITH path_temp AS (
	SELECT t.[Path] FROM SS_WhsType_Jur o 
	INNER JOIN BD_Whs_Type t ON t.WhsTypeID = o.WhsTypeID 
	WHERE o.RoleID=@RoleID AND o.LimitTag=1 
)
,typeid_temp AS (
	SELECT DISTINCT t.WhsTypeID FROM BD_Whs_Type t,path_temp 
    WHERE t.WhsTypeID<>1 AND t.[Path] like path_temp.[Path]+''%'' 
)
,typeid_nocheck AS
(
	SELECT td.WhsTypeID FROM BD_Whs_Type t 
	INNER JOIN typeid_temp td ON td.WhsTypeID = t.WhsTypeID 
	WHERE t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 
)
,typeid_check AS 
(
	SELECT j.WhsTypeID FROM BD_Whs_Type t 
	INNER JOIN SS_WhsType_Jur j ON j.WhsTypeID = t.WhsTypeID 
	WHERE j.RoleID=@RoleID AND t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 AND j.LimitTag=2 
)
,PagingData AS 
(
	SELECT bd.WhsID,bd.WhsNO,bd.WhsName,bd.WhsTypeID,CAST(0 AS BIT)[multi],bd.Stt 
	FROM BD_Whs bd 
	INNER JOIN typeid_nocheck b1 ON b1.WhsTypeID = bd.WhsTypeID 
	UNION ALL 
	SELECT bd.WhsID,bd.WhsNO,bd.WhsName,bd.WhsTypeID,CAST(1 AS BIT)[multi],bd.Stt 
	FROM BD_Whs bd 
	INNER JOIN typeid_check b2 ON b2.WhsTypeID = bd.WhsTypeID 
	INNER JOIN SS_Whs_Jur j ON j.WhsID = bd.WhsID AND j.RoleID=@RoleID 
)'
END
IF (@limit=1 AND @RightType=1) --部分权限(授权人);部分权限(被授权组)-------授权人和被授权组并集集合
BEGIN
	SET @sql=';WITH path_temp AS (
	SELECT t.[Path] FROM SS_WhsType_Jur o 
	INNER JOIN BD_Whs_Type t ON t.WhsTypeID = o.WhsTypeID 
	WHERE o.RoleID=@RoleID AND o.LimitTag=1 
)
,typeid_temp AS (
	SELECT DISTINCT t.WhsTypeID FROM BD_Whs_Type t,path_temp 
    WHERE t.WhsTypeID<>1 AND t.[Path] like path_temp.[Path]+''%'' 
)
,typeid_nocheck AS
(
	SELECT o.WhsTypeID FROM BD_Whs_Type t 
	INNER JOIN typeid_temp o ON o.WhsTypeID = t.WhsTypeID 
	WHERE t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 
)
,typeid_check AS 
(
	SELECT j.WhsTypeID FROM BD_Whs_Type t 
	INNER JOIN SS_WhsType_Jur j ON j.WhsTypeID = t.WhsTypeID 
	WHERE j.RoleID=@RoleID AND t.[Path] LIKE @parpath+''%'' AND t.SonNum=0 AND j.LimitTag=2 
)
,alldataid_cf AS 
(
	SELECT bd.WhsID,0[multi] 
	FROM BD_Whs bd 
	INNER JOIN typeid_nocheck b1 ON b1.WhsTypeID = bd.WhsTypeID 
	UNION ALL 
	SELECT bd.WhsID,1[multi] 
	FROM BD_Whs bd 
	INNER JOIN typeid_check b2 ON b2.WhsTypeID = bd.WhsTypeID 
	INNER JOIN SS_Whs_Jur j ON j.WhsID = bd.WhsID AND j.RoleID=@RoleID 
	UNION ALL 
	SELECT o.WhsID,0[multi] FROM BD_Whs o 
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) lt ON lt.WhsID = o.WhsID 
	INNER JOIN BD_Whs_Type t ON t.WhsTypeID = o.WhsTypeID 
	WHERE t.[Path] LIKE @parpath+''%''
)
,alldataid AS 
(
	SELECT WhsID,MAX(multi)[multi] FROM alldataid_cf 
	GROUP BY WhsID 
)
,PagingData AS 
(
	SELECT o.WhsID,o.WhsNO,o.WhsName,o.WhsTypeID,CAST(d.multi AS BIT)[multi],o.Stt 
	FROM BD_Whs o 
	INNER JOIN alldataid d ON d.WhsID = o.WhsID 
)'
END

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@RoleID','INT',@RoleID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

IF(@limit=0 AND (@RightType=2 OR @RightType=0))
	EXEC SP_EXECUTESQL N'SELECT ''''[ROWCOUNT],''''ROWID,WhsID,WhsNO,WhsName,WhsTypeID,CAST(0 AS BIT)[multi],Stt FROM BD_Whs WHERE 1<>1 '
ELSE
	EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'WhsNO ASC','','WhsNO ASC',1,1

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博	
	日期：2014-05-05
	描述：查询货位信息线性表
	updatedate 20150521 sunzhiyuan line:70 替换WHERE 1=1 '
			   修复仓库信息无权限还可以检索出货位信息BUG
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryKtypePtList]
(
	@ParId VARCHAR(50)='',
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(20)='',
	@showStopped BIT=1,
	@OperatorID INT
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50) = '',@sql NVARCHAR(MAX) = '', @WhsSql NVARCHAR(500) = '', @LimitSql NVARCHAR(MAX)= '', @WhereSql NVARCHAR(MAX)=''

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0
BEGIN
	SET @WhereSql = ' WHERE 1=2 '
END ELSE
BEGIN
	SET @WhereSql = ' WHERE 1=1 '
END


IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
	SET @LimitSql = 'INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =W.WhsID'

IF LEFT(@ParID,1) = 'K'
BEGIN
	SET @parpath = SUBSTRING(@ParID,2,len(@ParID))
	SET @WhsSql = 'SELECT W.WhsID, WhsName FROM BD_Whs W '+ @LimitSql +' WHERE W.WhsID = @parpath' 
	
END ELSE
BEGIN
	SELECT @parpath=[PATH] FROM BD_Whs_Type WHERE WhsTypeID=@ParId
	SET @WhsSql = 'SELECT w.WhsID, WhsName FROM BD_Whs_Type wt INNER JOIN BD_Whs w ON  wt.WhsTypeID = w.WhsTypeID '+ @LimitSql +' WHERE Path LIKE @parpath+''%'' '
END

SELECT @sql='
WITH PagingData AS 
(
	SELECT	    WhsPtID,
				WhsPtNO,
				WhsPtName,
				wp.WhsID,
				whs.WhsName,
				WhsPtType,
				Stt,
				Remark
	FROM BD_Whs_Position wp
	INNER JOIN 
	(
		'+ @WhsSql +'
	)whs ON whs.WhsID=wp.WhsID
	'+@WhereSql+' '
	

IF @UserCode <> ''
	SET @sql +=' AND WhsPtNO Like ''%''+@UserCode+''%'''
IF @FullName <> ''
	SET @sql +=' AND WhsPtName Like ''%''+@FullName+''%'''
IF @showStopped=0
	SET @sql +=' AND Stt=1'	

SET @sql +=') '

--PRINT (@sql)
		
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(50)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(20)',@UserCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'WhsPtNO ASC','','ROWID ASC',1,0

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博
	日期：2014-04-30
	描述：查询存货仓库树形
-------------------------------------------*/
CREATE PROCEDURE UP_BD_QueryKtypeTree
(
	@OperatorID INT
)

AS
SET NOCOUNT ON

DECLARE @LimitSql NVARCHAR(MAX)='', @Sql NVARCHAR(MAX)='', @WhereSql NVARCHAR(MAX)='', @TypeLimitSql NVARCHAR(MAX)=''

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0
BEGIN
	SET @WhereSql = ' WHERE 1=2 '
END ELSE
BEGIN
	SET @WhereSql = ' WHERE 1=1 '
END


IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
BEGIN
	SET @LimitSql = 'INNER JOIN UF_BD_KtypeLimit('+CONVERT(VARCHAR(10),@OperatorID)+') kl ON kl.WhsID =k.WhsID'
	SET @TypeLimitSql = 'INNER JOIN  UF_BD_KtypeTypeLimit('+CONVERT(VARCHAR(10),@OperatorID)+') wtj ON wt.WhsTypeID = wtj.WhsTypeID '
END

SET @Sql = '
SELECT	CONVERT(VARCHAR(50),wt.WhsTypeID) AS WhsID, 
		TypeCode AS WhsNO, 
		TypeName AS  [text], 
		TypeName+''[''+TypeCode+'']'' AS  WhsName, 
		CONVERT(VARCHAR(50), ParID) AS ParID, 
		Lvl, 
		1 AS IsType 
FROM BD_Whs_Type wt
'+ @TypeLimitSql +'
'+ @WhereSql +'
UNION ALL
SELECT	''K''+CONVERT(VARCHAR(50),k.WhsID) AS WhsID, 
		WhsNO, 
		WhsName AS [text], 
		WhsName+''[''+WhsNO+'']'' AS WhsName, 
		CONVERT(VARCHAR(50), k.WhsTypeID) AS ParID, 
		(kp.Lvl+1) AS Lvl, 
		0 AS IsType  
FROM BD_Whs k 
INNER JOIN  BD_Whs_Type kp ON k.WhsTypeID = kp.WhsTypeID  
'+ @LimitSql +'
'+ @WhereSql +' AND k.Stt=1
'
--PRINT(@SQL)
EXEC (@Sql)

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博
	日期：2014-10-15
	描述：网店管理查询存货仓库线性表
-------------------------------------------*/
CREATE PROCEDURE UP_BD_QueryKtypeUpLoadList
(
	@ParId		INT =0,
	@PageNo		INT =0,
	@PageSize	INT =0,
	@OperatorID INT = 1,
	@IsUpload	BIT = 0,
	@Stt		INT = 0--0为不显示停用，1为显示停用
)

AS
SET NOCOUNT ON

DECLARE @parpath VARCHAR(50) = '',@sql NVARCHAR(max) = '', @LimitSql NVARCHAR(MAX) = '', @UpLoadSql NVARCHAR(MAX) = ''

SELECT @parpath=PATH FROM BD_Whs_Type WHERE WhsTypeID=@ParId

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0
	SET @LimitSql = 'INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =k.WhsID'

IF @IsUpload = 1
	SET @UpLoadSql = ' , CASE IsUpload WHEN 1 THEN ''否'' ELSE ''是'' END AS IsReplace '

SELECT @sql='
;WITH PagingData AS 
(
	SELECT	    k.WhsID,
				WhsNO,
			    WhsName,
				WhsAbbName,
				Spell,
				k.WhsTypeID,
				TypeName,
				AreaID,
				Responsible,
				LinkMan,
				Tel,
				[Address],
				PostCode,
				Stt,
				Remark
				'+ @UpLoadSql +'
	FROM BD_Whs k 
	'+ @LimitSql +'
	INNER JOIN 
	(
		SELECT   WhsTypeID,
				 TypeName
		FROM BD_Whs_Type 
		WHERE Path LIKE @parpath+''%''
	)typeid ON typeid.WhsTypeID=k.WhsTypeID
	WHERE 1=1 '

IF @Stt = 0
	SET @sql += ' AND Stt=1'

IF @IsUpload = 0
	SET @sql += ' AND IsUpload = 0'
ELSE
	SET @sql += ' AND IsUpload > 0'

SET @sql +=') '
	
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@IsUpload','BIT',@IsUpload)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'WhsNO ASC','','ROWID ASC',1,1

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-5-5
	描述：查询期初应收应付
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryOpeningArap]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(20)='',
	@isquery INT,
	@UserID INT=1
)

AS
SET NOCOUNT ON

IF dbo.UF_BD_IsAllBtypeLimit(@UserID)=0
BEGIN
	SELECT TOP 0 * FROM BD_ARAP
	RETURN
END

DECLARE @sql NVARCHAR(max)
SELECT @sql='
;WITH PagingData AS 
(
	SELECT	b.BTypeID,
		b.BTypeName,
		b.BTypeCode,
		QcAP,
		QcAR,
		QcBR,
		QcBP,
		Stt,
		ISNULL(ARAPID,0) AS ARAPID
	FROM BD_Btype b'
IF dbo.UF_BD_IsAllBtypeLimit(@UserID)=1
	SET @sql+='
	INNER JOIN dbo.UF_BD_BtypeLimit(@UserID) b1 ON b1.BTypeID=b.BTypeID
	'
SET @sql+='
	LEFT JOIN BD_ARAP arap ON b.BTypeID=arap.BTypeID
	WHERE 1=1 '
	
IF @FullName <> ''
	SET @sql +=' AND BTypeName Like ''%''+@FullName+''%'''
IF @UserCode <> ''
	SET @sql +=' AND BTypeCode Like ''%''+@UserCode+''%'''

IF @isquery=1	--查询
BEGIN	
	SET @sql +='
	)
	'
	
	DECLARE  @TVP as TVP_Paging_Param
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserID','INT',@UserID)

	EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'BTypeCode','','BTypeCode',1,0
END
ELSE--合计
BEGIN
	SET @sql +='
	)

	SELECT SUM(QcAR) AS QcAR,
		   SUM(QcAP) AS QcAP,
		   SUM(QcBR) AS QcBR,
		   SUM(QcBP) AS QcBP
	FROM  PagingData

	'
--PRINT(@sql)
	EXEC sp_executesql @sql,N'@FullName VarChar(100),@UserCode VarChar(50),@UserID INT',@FullName,@UserCode,@UserID
END
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-5-6
	描述：查询期初现金银行
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryOpeningFinance]
(
	@MenuID INT=2519,
	@UserID INT=1
)
AS
SET NOCOUNT ON

IF  dbo.UF_BD_IsAllAtypeLimit(@UserID)=0
BEGIN
	SELECT TOP 0 * FROM BD_Finance
	RETURN
END

DECLARE @Path VARCHAR(50)='00001'
IF(@MenuID<>2519)
	SET @Path='00002,00003'
DECLARE @sql NVARCHAR(max)=''	
SET @sql='
	if object_id(''tempdb..#finance'',''U'') is not null drop table #finance
	CREATE TABLE #finance
	(
		[FinanceID] [int] NOT NULL,
		[FinanceName] [varchar](100) NOT NULL,
		[FinanceNO] [varchar](175) NOT NULL,
		[Path] [varchar](50) NOT NULL,
		[Lvl] [int] NOT NULL ,
		[SonNum] [int] NOT NULL ,
		QcBalances DECIMAL(20,8),
		[FundsID] INT,
		[Stt] [tinyint] NOT NULL,
	)

	--递归模式
	;WITH FinanceData AS
	(
		SELECT	fc.FinanceID,
				ParID,
				QcBalances,
				FundsID
		FROM BD_Finance fc
		INNER JOIN dbo.UF_OT_Split(@Path,'','')a ON fc.Path LIKE a.a+''%'''
IF  dbo.UF_BD_IsAllAtypeLimit(@UserID)=1
	SET @Sql+='
		INNER JOIN dbo.UF_BD_AtypeLimit(@UserID) al ON al.FinanceID=fc.FinanceID '
SET @sql+='
		LEFT JOIN BD_Funds fs ON fc.FinanceID = fs.FinanceID
		WHERE SonNum=0 
		UNION ALL
		SELECT	fc.FinanceID,
				fc.ParID,
				QcBalances,--SUM(ISNULL(QcBalances,0)) AS QcBalances,
				0 AS FundsID
		FROM BD_Finance fc
		INNER JOIN 	FinanceData fd ON fd.ParID=fc.FinanceID
		INNER JOIN dbo.UF_OT_Split(@Path,'','')a ON fc.Path LIKE a.a+''%'' AND (@MenuID<>2519 OR Path<>a.a)
	)

	INSERT INTO #finance
			( FinanceID ,
			  FinanceName ,
			  FinanceNO ,
			  Path ,
			  Lvl ,
			  SonNum ,
			  QcBalances,
			  FundsID,
			  Stt
			)
	SELECT	fc.FinanceID,
			FinanceName,
			dbo.UF_OT_StringReplace(Lvl,3)+FinanceNO AS FinanceNO,
			Path,
			Lvl,
			SonNum,
			ISNULL(QcBalances,0) AS QcBalances,--SUM(ISNULL(QcBalances,0)) AS QcBalances,
			ISNULL(FundsID,0) FundsID,
			Stt
	FROM BD_Finance fc
	INNER JOIN 
	(
		SELECT	SUM(QcBalances) AS QcBalances,
				FinanceID,
				FundsID
		FROM FinanceData 
		GROUP BY FinanceID,FundsID
	)fd ON fc.FinanceID = fd.FinanceID

	IF @MenuID<>2519
		UPDATE #finance SET FinanceName='''',Path=Path+''99999'',FinanceNO=CASE WHEN FinanceNO =''0002'' THEN ''收入合计'' ELSE ''支出合计'' END WHERE FinanceNO IN(''0003'',''0002'')

	SELECT * FROM #finance ORDER BY PATH,FinanceNO DESC
	DROP TABLE #finance'
	
EXEC sp_executesql @Sql,N'@Path varchar(50),@MenuID int,@UserID INT',@Path,@MenuID,@UserID	
	
	
	
	
/*   jion 模式
;WITH FinanceData1 AS
(
	SELECT	fc.FinanceID,
			ParID,
			Path,
			QcBalances
	FROM BD_Finance fc
	INNER JOIN BD_Funds fs ON fc.FinanceID = fs.FinanceID
	WHERE stt=1 AND (Path LIKE '0000100001%' OR Path LIKE '0000100002%') AND SonNum=0
)

SELECT a.*,
	ISNULL(fs.FundsID,0) AS FundsID
FROM
(
SELECT	fc.FinanceID,
		FinanceName,
		dbo.UF_OT_StringReplace(Lvl)+FinanceNO AS FinanceNO,
		Lvl,
		fc.path,
		SonNum,
		SUM(fd2.QcBalances)AS Qc--SUM(ISNULL(QcBalances,0)) AS QcBalances,
FROM BD_Finance fc
LEFT JOIN FinanceData1 fd2 ON  fd2.Path LIKE fc.Path+'%' 
WHERE stt=1 AND (fc.Path LIKE '0000100001%' OR fc.Path LIKE '0000100002%')
--GROUP BY fc.FinanceID,FinanceName,FinanceNO,Lvl,SonNum
GROUP BY fc.FinanceID,FinanceName,fc.Path,FinanceNO,Lvl,SonNum
) a
LEFT JOIN BD_Funds fs ON a.FinanceID = fs.FinanceID
ORDER BY Path,FinanceNO
*/

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-5-4
	描述：查询期初库存
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryOpeningStock]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(20)='',
	@WhsID VARCHAR(max)='',
	@isquery INT,
	@UserID INT
)

AS
SET NOCOUNT ON

DECLARE @sql NVARCHAR(max),@sqlg NVARCHAR(max)
SELECT @sql='
;WITH PagingData AS 
(
	SELECT	g.GoodsNO,
			g.GoodsName,
			g.GoodsID,
			g.GoodsTypeID,
			g.PptGroupID,
			g.CostMethod,
			g.DateType,
			g.ValidDays,
			g.NearbyDays,
			g.Spec,
			g.Model,
			g.Place,
			g.GoodsAbbName,
			g.Brand,
			g.KG,
			gt.TypeName,
			P.Unit,
			g.Stt,
			s.Price,
			s.Qty,
			s.Total
			
	FROM BD_Goods g
	Left JOIN BD_Goods_Price p ON g.GoodsID=p.GoodsID
	Left JOIN BD_Goods_Type gt ON g.GoodsTypeID = gt.GoodsTypeID
	LEFT JOIN
	(	SELECT ISNULL(SUM(oS.Qty),0) AS Qty,
			   CAST(ISNULL(CAST(SUM(os.Total) AS DECIMAL(20,8))/CASE SUM(os.Qty) WHEN 0 THEN NULL ELSE CAST(SUM(os.Qty) AS DECIMAL(20,8)) END,0) AS DECIMAL(20,8)) AS Price,
			   ISNULL(SUM(oS.Total),0) AS Total,
			   oS.GoodsID
		FROM BD_OpeningStock os'
IF @WhsID<>''
	SET @sql+='	INNER JOIN dbo.UF_OT_Split_Int(@WhsID,'','') W ON os.WhsID=W.typeid '	
IF  dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2
	SET @sql+='	INNER JOIN UF_BD_KtypeLimit(@UserID) W1 ON os.WhsID=W1.WhsID '	
SET @sql+='
		GROUP BY oS.GoodsID
	)s ON g.GoodsID=s.GoodsID 
	WHERE (p.UnitID=1 OR p.UnitID IS NULL) '
	
IF @UserCode <> ''
	SET @sql +=' AND GoodsNo Like ''%''+@UserCode+''%'''

IF @FullName <> ''
	SET @sql +=' AND GoodsName Like ''%''+@FullName+''%'''	

IF @isquery=1--查询	
BEGIN	
	SET @sql +='
	)
	'
	
	
/***********定义要关联的基础资料sql***********/
	SET @sqlg=N'SELECT STUFF((
					SELECT ''>''+TypeName 
					FROM BD_Goods_Type a 
					WHERE GT.Path LIKE a.PATH+''%''  ORDER BY Lvl FOR XML PATH('''')
				),1,4,'''') AS Path ,GoodsTypeID as GID from BD_Goods_Type GT'

	DECLARE  @TVP as TVP_Paging_Param
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@WhsID','VARCHAR(250)',@WhsID)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserID','INT',@UserID)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsTypeID=_DATA_a.GID',@sqlg)
	
	EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'GoodsNO ','','GoodsNO ',1,0
END
ELSE --求合计
SET @sql +='
	)
	SELECT  SUM(Qty) AS Qty,
			SUM(Total) AS Total
	FROM PagingData
	'
--PRINT(@sql)
EXEC sp_executesql @sql,N'@WhsID VarChar(max),@FullName VarChar(100),@UserCode VarChar(50),@UserID INT',@WhsID,@FullName,@UserCode,@UserID
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-5-4
	描述：查询期初库存明细
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryOpeningStockDetail]
(
	@StockID INT=0
)

AS
SET NOCOUNT ON


	SELECT	StockID,
			DetailID,
			s.WhsPtID,
			p.WhsPtName,
			p2.Value AS Ppt2Name,
			p1.Value AS Ppt1Name,
			s.Ppt1ID,
			s.Ppt2ID,
			s.BatchNumber,
			s.ProductDate,
			s.EndDate,
			s.CostPrice,
			s.CostTotal,
			Qty 
	FROM BD_OpeningStock_Detail s 
	LEFT JOIN BD_Whs_Position p ON s.WhsPtID = p.WhsPtID
	LEFT JOIN BD_Goods_Ppt1 p1 ON s.Ppt1ID=p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON s.Ppt2ID=p2.Ppt2ID
	WHERE StockID=@StockID

GO



/****** Object:  StoredProcedure [UP_BD_QueryOperatorUploadList]    Script Date: 10/15/2014 10:10:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_QueryOperatorUploadList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_QueryOperatorUploadList]
GO

/****** Object:  StoredProcedure [UP_BD_QueryOperatorUploadList]    Script Date: 10/15/2014 10:10:14 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-10-15
	描述：同步操作员列表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryOperatorUploadList]
(
	@ParID INT=1,
	@PageNo INT=0,
	@PageSize INT=0,
	@IsUpload BIT=0,
	@Stt INT=0	--0为不显示停用，1为显示停用
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)

SET @sql='
;WITH PathData AS(
	SELECT DeptId 
	FROM BD_Dept 
	WHERE [Path] LIKE 
					(
						SELECT [Path] 
						FROM BD_Dept 
						WHERE DeptId=@ParID
					)+''%''
)
,PagingData AS
(
	SELECT o.ElyID,o.ElyCode,o.ElyName,CASE WHEN o.IsUpload=2 THEN ''是'' ELSE ''否'' END[IsUpdate],Stt 
	FROM BD_Employee o 
	WHERE o.ElyID<>1 '
IF @Stt=0
	SET @sql+='AND Stt=1 '
IF @IsUpload=0
	SET @sql+='AND IsUpload=0 '
ELSE
	SET @sql+='AND IsUpload<>0 '
IF @ParID <> 1
	SET @sql +='AND EXISTS (SELECT 1 FROM PathData WHERE DeptId=o.DeptId) '
SET @sql +=') '

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@ParId','INT',@ParId)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@IsUpload','BIT',@IsUpload)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'ElyCode','','',1,0

END

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-5-6
	描述：查询属性组线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryPptGroupList]
(
	@PageNo INT=1,
	@PageSize INT=0
)

AS
SET NOCOUNT ON
DECLARE @sql NVARCHAR(max)
SELECT @sql='
;WITH PagingData AS 
(
	select DISTINCT PptGroupID,
			GroupName,
			dbo.UF_BD_GetPptName(PptGroupID,1) as Ppt1Name,
			dbo.UF_BD_GetPptName(PptGroupID,2) as Ppt2Name,
			RemarkGroup  
	from BD_Goods_PptGroup 
) '
DECLARE  @TVP AS TVP_Paging_Param
--INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)','1')

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'PptGroupID'

GO



/****** Object:  StoredProcedure [UP_BD_QueryProTempData]    Script Date: 04/25/2014 10:00:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_QueryProTempData]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_QueryProTempData]
GO

/****** Object:  StoredProcedure [UP_BD_QueryProTempData]    Script Date: 04/25/2014 10:00:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-01-20
	描述：查询生产模板和明细信息
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryProTempData]
(
	@BillNo BIGINT=0
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)

SELECT @sql='
SELECT o.BillNo,o.ModelName,o.GoodsID,g.GoodsNo,g.GoodsName,g.DateType,g.CostMethod,pt1.Ppt1ID,pt1.Value[Ppt1Name],pt2.Ppt2ID,pt2.Value[Ppt2Name],o.AssemblyCost 
FROM PD_ProduceModelBill o 
INNER JOIN BD_Goods g ON g.GoodsID = o.GoodsID 
LEFT JOIN BD_Goods_Ppt1 pt1 ON pt1.Ppt1ID = o.Ppt1ID 
LEFT JOIN BD_Goods_Ppt2 pt2 ON pt2.Ppt2ID = o.Ppt2ID 
WHERE o.BillNo=@BillNo 

SELECT o.GoodsID,g.GoodsNo,g.GoodsName,g.DateType,g.CostMethod,pt1.Ppt1ID,pt1.Value[Ppt1Name],pt2.Ppt2ID,pt2.Value[Ppt2Name],0[StockQty],o.Qty,o.Qty[BSQty],0[ReqQty],0[RemainingQty],0[CQty]
		,gp.BarCode,g.Model,g.Spec,gp.Unit,gp.Convfactor
		,gp1.Convfactor Convfactor1,CASE WHEN gp2.Convfactor IS NULL THEN 1 ELSE gp2.Convfactor END Convfactor2,CASE WHEN gp3.Convfactor IS NULL THEN 1 ELSE gp3.Convfactor END Convfactor3
		,gp1.Unit Unit1,gp2.Unit Unit2,gp3.Unit Unit3,gp1.BarCode BarCode1,gp2.BarCode BarCode2,gp3.BarCode BarCode3 
FROM PD_ProduceModelDetail o 
INNER JOIN BD_Goods g ON g.GoodsID = o.GoodsID 
INNER JOIN BD_Goods_Price gp ON gp.GoodsID = g.GoodsID AND gp.UnitID=1
LEFT JOIN BD_Goods_Ppt1 pt1 ON pt1.Ppt1ID = o.Ppt1ID 
LEFT JOIN BD_Goods_Ppt2 pt2 ON pt2.Ppt2ID = o.Ppt2ID 
LEFT JOIN BD_Goods_Price gp1 ON o.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
LEFT JOIN BD_Goods_Price gp2 ON o.GoodsID=gp2.GoodsID AND gp2.UnitID=2
LEFT JOIN BD_Goods_Price gp3 ON o.GoodsID=gp3.GoodsID AND gp3.UnitID=3 
WHERE o.BillNo=@BillNo '
--PRINT @Sql
EXEC SP_EXECUTESQL @sql,N'@BillNo BIGINT',@BillNo
END

GO






/****** Object:  StoredProcedure [UP_BD_QueryProTempList]    Script Date: 04/25/2014 10:00:34 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_QueryProTempList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_QueryProTempList]
GO

/****** Object:  StoredProcedure [UP_BD_QueryProTempList]    Script Date: 04/25/2014 10:00:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-01-20
	描述：查询生产模板信息
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryProTempList]
(
	@pageNo INT=0,
	@pageSize INT=0,
	@ModelName VARCHAR(100)='',
	@GoodsID VARCHAR(1000)='',
	@GoodsID_part VARCHAR(1000)=''
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)

IF @GoodsID='' AND @GoodsID_part=''
BEGIN
	SET @sql='
;WITH PagingData AS
(
	SELECT o.BillNo,o.ModelName,g.GoodsNo,g.GoodsName,pt1.Value[Ppt1Name],pt2.Value[Ppt2Name],o.AssemblyCost FROM PD_ProduceModelBill o 
	INNER JOIN BD_Goods g ON g.GoodsID = o.GoodsID 
	LEFT JOIN BD_Goods_Ppt1 pt1 ON pt1.Ppt1ID = o.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 pt2 ON pt2.Ppt2ID = o.Ppt2ID '
END
ELSE IF @GoodsID<>'' AND @GoodsID_part=''
BEGIN
	SET @sql='
;WITH PagingData AS
(
	SELECT o.BillNo,o.ModelName,g.GoodsNo,g.DateType,g.CostMethod,g.GoodsName,pt1.Value[Ppt1Name],pt2.Value[Ppt2Name],o.AssemblyCost FROM PD_ProduceModelBill o 
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _g0 ON _g0.typeid=o.GoodsID 
	INNER JOIN BD_Goods g ON g.GoodsID = o.GoodsID 
	LEFT JOIN BD_Goods_Ppt1 pt1 ON pt1.Ppt1ID = o.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 pt2 ON pt2.Ppt2ID = o.Ppt2ID '
END 
ELSE IF @GoodsID='' AND @GoodsID_part<>''
BEGIN
	SET @sql='
DECLARE @ct INT
SELECT @ct=COUNT(1) FROM dbo.UF_OT_Split_Int(@GoodsID_part, '','')
;WITH BillNo_Temp0 AS (
	SELECT DISTINCT BillNo,GoodsID FROM PD_ProduceModelDetail
)
,BillNo_Temp AS (
	SELECT BillNo,COUNT(1)[ct] FROM BillNo_Temp0 o 
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID_part, '','') _g1 ON _g1.typeid=o.GoodsID 
	GROUP BY BillNo 
)
,BillNoList AS (
	SELECT BillNo FROM BillNo_Temp WHERE ct=@ct 
)
,PagingData AS
(
	SELECT o.BillNo,o.ModelName,g.GoodsNo,g.GoodsName,g.DateType,g.CostMethod,pt1.Value[Ppt1Name],pt2.Value[Ppt2Name],o.AssemblyCost FROM PD_ProduceModelBill o 
	INNER JOIN BillNoList bl ON bl.BillNo = o.BillNo
	INNER JOIN BD_Goods g ON g.GoodsID = o.GoodsID 
	LEFT JOIN BD_Goods_Ppt1 pt1 ON pt1.Ppt1ID = o.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 pt2 ON pt2.Ppt2ID = o.Ppt2ID '
END
ELSE --IF @GoodsID<>'' AND @GoodsID_part<>''
BEGIN
	SET @sql='
DECLARE @ct INT
SELECT @ct=COUNT(1) FROM dbo.UF_OT_Split_Int(@GoodsID_part, '','')
;WITH BillNo_Temp0 AS (
	SELECT DISTINCT BillNo,GoodsID FROM PD_ProduceModelDetail
)
,BillNo_Temp AS (
	SELECT BillNo,COUNT(1)[ct] FROM BillNo_Temp0 o 
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID_part, '','') _g1 ON _g1.typeid=o.GoodsID 
	GROUP BY BillNo 
)
,BillNoList0 AS (
	SELECT BillNo FROM BillNo_Temp WHERE ct=@ct 
)
,BillNoList1 AS (
	SELECT BillNo FROM PD_ProduceModelBill o 
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _g0 ON _g0.typeid=o.GoodsID 
)
,BillNoList2 AS (
	SELECT BillNo FROM BillNoList0 
	UNION ALL 
	SELECT BillNo FROM BillNoList1 
)
,BillNoList AS (
	SELECT BillNo FROM BillNoList2 GROUP BY BillNo
)
,PagingData AS
(
	SELECT o.BillNo,o.ModelName,g.GoodsNo,g.GoodsName,g.DateType,g.CostMethod,pt1.Value[Ppt1Name],pt2.Value[Ppt2Name],o.AssemblyCost FROM PD_ProduceModelBill o 
	INNER JOIN BillNoList bl ON bl.BillNo = o.BillNo
	INNER JOIN BD_Goods g ON g.GoodsID = o.GoodsID 
	LEFT JOIN BD_Goods_Ppt1 pt1 ON pt1.Ppt1ID = o.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 pt2 ON pt2.Ppt2ID = o.Ppt2ID '
END
IF @ModelName<>'' 
	SET @sql += '
	WHERE o.ModelName LIKE ''%''+@ModelName+''%'' '
SET @sql+='
)'
DECLARE @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ModelName','VARCHAR(100)',@ModelName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsID','VARCHAR(1000)',@GoodsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsID_part','VARCHAR(1000)',@GoodsID_part)

EXEC UP_OT_Paging @sql,@TVP,@pageNo,@pageSize,'ModelName','','',1,0
END

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-4-29
	描述：查询颜色属性线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryPtypeAttributeCList]
(
	@PageNo INT=1,
	@PageSize INT=1
)

AS
SET NOCOUNT ON
DECLARE @sql nvarchar(max)
SELECT @sql ='
;WITH PagingData AS 
(
	SELECT PPt1ID,PptNO as Ppt1NO,Value as Value1,Remark from BD_Goods_Ppt1
)'

DECLARE  @TVP AS TVP_Paging_Param


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'Ppt1NO'
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：韩林
	日期：2014-4-25
	描述：查询往来单位线性类表
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_QueryPtypeAttributeSList]
(
	@PageNo INT=0,
	@PageSize INT=0
)

AS
SET NOCOUNT ON
DECLARE @sql nvarchar(max)
SELECT @sql ='
;WITH PagingData AS 
(
	SELECT PPt2ID,PptNO as Ppt2NO,Value as Value2,Remark from BD_Goods_Ppt2
)'


DECLARE  @TVP AS TVP_Paging_Param


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'Ppt2NO'
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_StockLimitSettings]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_StockLimitSettings]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*------------------------------------------
    作者：HanLin
	日期：2015-3-23
	描述：库存上下限设置
-------------------------------------------*/
CREATE PROCEDURE UP_BD_StockLimitSettings
(
	 @pageNo INT=0
	,@pageSize INT=0
	,@WhsID INT=0
	,@GoodsTypeID INT=0
	,@fullName VARCHAR(100)=''
	,@fullNameMatch int =0
	,@userCode VARCHAR(50)=''
	,@userCodeMatch int =0,
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0           --条码匹配方式 0:包含 1:等于
)

AS
SET NOCOUNT ON

	DECLARE @Sql NVARCHAR(4000)='',@JoinSql VARCHAR(max)='',@GoodsSql VARCHAR(max)=''			

	IF @GoodsTypeID=0                           
		SET @GoodsTypeID=1
	IF @GoodsTypeID<>1	
	BEGIN
		CREATE TABLE #PTypeType(TypeID INT) 
		INSERT INTO #PTypeType SELECT p1.GoodsTypeID  FROM BD_Goods_Type p INNER JOIN BD_Goods_Type p1 ON p1.Path LIKE p.Path+'%' WHERE p.GoodsTypeID=@GoodsTypeID
	END
	IF @FullName<>'' AND @UserCode=''
		SET @GoodsSql=' And p.GoodsName '+CASE @FullNameMatch WHEN 0 THEN ' Like''%'+@FullName+'%'' ' ELSE  ' ='''+@FullName+'''' END
	ELSE IF @FullName='' AND @UserCode<>''
		SET @GoodsSql=' And p.GoodsNO '+CASE @UserCodeMatch WHEN 0 THEN ' Like''%'+@UserCode+'%'' ' ELSE ' ='''+@UserCode+''''  END
	ELSE IF @FullName<>'' AND @UserCode<>''
		SET @GoodsSql=' And p.GoodsName '+CASE @FullNameMatch WHEN 0 THEN ' Like''%'+@FullName+'%'' ' ELSE  ' ='''+@FullName+'''' END
			+ ' And p.GoodsNO '+CASE @UserCodeMatch WHEN 0 THEN ' Like''%'+@UserCode+'%'' ' ELSE  ' ='''+@UserCode+'''' END

	/*新增商品查询条件 start 150906*/
	IF @Model <> ''      --商品型号
	   SET @GoodsSql+=' AND p.Model '+CASE @ModelMatch WHEN 0 THEN ' LIKE ''%'+@Model+'%'' ' ELSE  ' ='''+@Model+'''' END     
	IF @AbbName <> ''    --商品简名
	   SET @GoodsSql+=' AND p.GoodsAbbName '+CASE @AbbNameMatch WHEN 0 THEN ' LIKE ''%'+@AbbName+'%'' ' ELSE  ' ='''+@AbbName+'''' END 
	IF @Brand <> ''      --商品品牌
	   SET @GoodsSql+=' AND p.Brand '+CASE @BrandMatch WHEN 0 THEN ' LIKE ''%'+@Brand+'%'' ' ELSE  ' ='''+@Brand+'''' END   
	IF @Spec <> ''       --商品规格
	   SET @GoodsSql+=' AND p.Spec '+CASE @SpecMatch WHEN 0 THEN ' LIKE ''%'+@Spec+'%'' ' ELSE  ' ='''+@Spec+'''' END 
	IF @BarCode <> ''      --商品条码
	   BEGIN 
		   SET @GoodsSql += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = p.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @GoodsSql += N' AND pri.BarCode LIKE ''%' + @BarCode +'%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @GoodsSql += N' AND pri.BarCode = '''+@BarCode+'''' 
		   SET @GoodsSql += ' ) '
	   END    
	/*end*/	

	SET @sql='	
	;WITH PageData AS
	(
		SELECT p.GoodsID,p.GoodsNo,p.GoodsName,Spec,Model,Place,Brand,@WhsID WhsID,LowerBound,UpperBound,u.Unit,p.GoodsAbbName,u.BarCode 
		FROM BD_Goods p
		'+CASE WHEN @GoodsTypeID<>1 THEN 'INNER JOIN #PTypeType pt On pt.TypeID=p.GoodsTypeID 
		' ELSE '' END +'
		INNER JOIN BD_Goods_Price u ON u.GoodsID=p.GoodsID
		LEFT JOIN PD_GoodsStock_Bound g  ON g.GoodsID = p.GoodsID AND g.WhsID=@WhsID
		WHERE u.UnitID=1 '+@GoodsSql		+'
		)	
		SELECT a.*,b.*,w.WhsName,w.WhsNo FROM 
		(SELECT COUNT(1)AS[RowCount] FROM PageData)a
		CROSS JOIN 
		(
			SELECT *,ROW_NUMBER() OVER( ORDER BY GoodsNo ) AS ROWID
			FROM PageData
		)b
		INNER JOIN
		(	
			SELECT WhsName,WhsNo,WhsID FROM BD_Whs
			UNION ALL
			SELECT ''全部仓库'',''全部仓库'',99999
		)W On b.WhsID=w.WhsID		
		WHERE B.ROWID>(@PageNo-1)*@PageSize
		AND B.ROWID<=@PageNo*@PageSize'
	--PRINT @Sql
	EXEC sp_executesql @sql,N'@WhsID INT,@PageNo int,@PageSize INT',@WhsID,@PageNo,@PageSize
		
	if object_id('tempdb..#PTypeType','U') is not null 
	DROP TABLE #PTypeType

GO






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

/*------------------------------------------
    作者：李文博
	日期：2014-05-15
	描述：地区TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCAreaTypeList
(
	@ParID INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@IsOverLevel INT = 0,  --是否匹配所有层级 默认匹配末级
	@showStopped BIT=1,
	@IsTree BIT = 1      /*默认查询树形结构*/
)

AS

DECLARE @sql NVARCHAR(max)

IF @IsTree = 1
BEGIN
	SELECT @sql='
	;WITH PagingData AS 
	(
		SELECT	  AreaID,
				  AreaNO ,
				  AreaName ,
				  AreaAbbName ,
				  Spell ,
				  Path ,
				  ParID ,
				  Lvl ,
				  SonNum ,
				  AreaType ,
				  Stt ,
				  Remark
		FROM BD_Area 
		WHERE ParID=@parID '
END ELSE
BEGIN
	SELECT @sql='
	;WITH PagingData AS 
	(
		SELECT	  AreaID,
				  AreaNO ,
				  AreaName ,
				  AreaAbbName ,
				  Spell ,
				  Path ,
				  ParID ,
				  Lvl ,
				  SonNum ,
				  AreaType ,
				  Stt ,
				  Remark
		FROM BD_Area 
		WHERE AreaID <> 1 '
		
	IF @IsOverLevel = 0
        SET @sql += ' AND SonNum = 0 '
        	
	IF @SearchStr <> ''
		SET @sql +=' AND (AreaNO Like ''%''+@SearchStr+''%'' OR AreaName Like ''%''+@SearchStr+''%'' )'
		
	IF @ExactSearchStr <> ''
		SET @sql += ' AND (AreaNO = @ExactSearchStr OR AreaName = @ExactSearchStr)'
END

IF @showStopped=0
	SET @sql +=' AND Stt=1'	

SET @sql +=') '
	
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ParID','INT',@ParID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'AreaNO ASC', '','ROWID ASC',1,0
GO






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

/*------------------------------------------
    作者：李文博
	日期：2014-05-15
	描述：科目TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCAtypeList
(
	@FinanceType INT=1,
	@BtypeId INT = 0,
	@ParID INT=0, 
	@PageNo INT=0,
	@PageSize INT=0,
	@QueryType INT = 2,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@showStopped BIT=1,
	@IsTree BIT = 1,      /*默认查询树形结构*/
	@VipCardID INT = 0,
	@OperatorID INT =1
)

AS

DECLARE @sql NVARCHAR(MAX), @TypeSql NVARCHAR(MAX), @LimitSql NVARCHAR(MAX) = '', @WhereSql NVARCHAR(MAX) = '', @ColName NVARCHAR(MAX) = ''
DECLARE @VipCardTotal NUMERIC(20,8) = 0, @VipCardFinanceID INT = 0, @VipCardTypeID INT = 0

/***********************************/
--关于@FinanceType定义：
--0：所有科目
--1：收款账户（预收,微信）
--2：付款账户（预付,微信）
--3：其它收入
--4：费用合计
--5：现金合计
--6: 收支账户（预收预付）
--7: 收支账户
--8: 收入项目
--9：支出项目
--10:会员储值
--11:收款账户（预收）
--12:付款账户（预付）
--13:付款账户（预付,支付宝,微信）
--14: 收支账户（支付宝,微信）
/***********************************/

SET @TypeSql = ''
IF @FinanceType = 1 AND @ParID = 2--收款账户（微信）第一层
BEGIN
		SET @TypeSql = ' OR a.FinanceID = 38'
		IF @VipCardID <> 0
		BEGIN
			SELECT @VipCardTotal = MoneyBalance, @VipCardTypeID = VipCardTypeID FROM VS_VipCard WHERE VipCardID = @VipCardID
			SELECT @VipCardFinanceID = FinanceID FROM VS_VipCardType WHERE VipCardTypeID = @VipCardTypeID
			SET @TypeSql += ' OR a.FinanceID = @VipCardFinanceID '
		END
END ELSE 
IF @FinanceType = 2 AND @ParID = 2--付款账户(微信)第一层
BEGIN
		SET @TypeSql = ' OR a.FinanceID = 34'
		IF @VipCardID <> 0
		BEGIN
			SELECT @VipCardTotal = MoneyBalance, @VipCardTypeID = VipCardTypeID FROM VS_VipCard WHERE VipCardID = @VipCardID
			SELECT @VipCardFinanceID = FinanceID FROM VS_VipCardType WHERE VipCardTypeID = @VipCardTypeID
			SET @TypeSql += ' OR a.FinanceID = @VipCardFinanceID '
		END
END ELSE
IF @FinanceType = 6 AND @ParID = 2--收支账户第一层
BEGIN
		SET @TypeSql = ' OR a.FinanceID = 38 OR a.FinanceID = 34 OR a.FinanceID = 41 '
END ELSE
IF @FinanceType = 10 AND @ParID = 36 --会员储值第一层
BEGIN
	SET @TypeSql = ' AND a.FinanceID = 41'
END ELSE
IF @FinanceType = 11 AND @ParID = 2--收款账户第一层
BEGIN
	SET @TypeSql = ' OR a.FinanceID = 38 '
END ELSE
IF @FinanceType in (12,13) AND @ParID = 2 --付款账户第一层
BEGIN
	SET @TypeSql = ' OR a.FinanceID = 34'
END

IF dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 0
BEGIN
	SET @WhereSql = 'WHERE 1=2 '
END ELSE
BEGIN
	SET @WhereSql = 'WHERE 1=1 '
END

--IF @FinanceType = 7 OR @FinanceType = 11 OR @FinanceType = 12
--BEGIN
--	SET @WhereSql += ' AND a.FinanceID <> 42'
--END

IF dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 1
	SET @LimitSql = 'INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) al ON al.FinanceID =a.FinanceID '

IF @IsTree = 1
BEGIN
	SELECT @sql='
	;WITH PagingData AS 
	(
		SELECT	  a.FinanceID,
				  FinanceNO ,
				  FinanceName ,
				  CASE WHEN (a.ParID = 41 OR a.FinanceID = 41) THEN @VipCardTotal ELSE ISNULL(QmBalances, 0) END AS QmBalances,
				  Path ,
				  CASE WHEN (a.FinanceID = 38 OR a.FinanceID = 34 OR (a.Path LIKE ''0000500003%'' AND @ParID =2) ) THEN 2 ELSE ParID END AS ParID,
				  Lvl ,
				  SonNum ,
				  Stt ,
				  SysRow ,
				  LoanStt ,
				  Remark
		FROM BD_Finance a
		LEFT JOIN (
				SELECT * FROM(
					SELECT BF.FinanceID, SUM(ISNULL(QmBalances,0)) AS QmBalances FROM BD_Finance BF LEFT JOIN
					( 
						SELECT a.FinanceID, a.[Path], F.QmBalances FROM BD_Finance a
						INNER JOIN BD_Funds F ON a.FinanceID = F.FinanceID 
						'+ @LimitSql +'
					) 
					FT ON FT.Path LIKE BF.Path+''%''
					WHERE lvl>1 and BF.FinanceID <> 38 and BF.FinanceID <> 34
					GROUP BY BF.FinanceID
				)temp1
				UNION
				-- @FinanceType 1:收款单，13：付款单
				SELECT	CASE WHEN @FinanceType = 13 THEN 34 ELSE 38 END AS FinanceID,
				ISNULL(CASE WHEN @FinanceType = 13 THEN QmBP ELSE QmBR END,0) AS QmBalances
				FROM BD_ARAP WHERE BTypeID = '+ CONVERT(VARCHAR,@BtypeId) +'
		) bf ON a.FinanceID = bf.FinanceID
		'+ @LimitSql +'
		'+ @WhereSql +'AND (ParID=@ParID '+ @TypeSql+')'		
END ELSE
BEGIN
	SELECT @sql='
	;WITH PagingData AS 
	(
		SELECT	  a.FinanceID,
				  FinanceNO ,
				  FinanceName ,
				  CASE WHEN (a.ParID = 41 OR a.FinanceID = 41) THEN @VipCardTotal ELSE ISNULL(QmBalances, 0) END AS QmBalances,
				  Path ,
				  ParID ,
				  Lvl ,
				  SonNum ,
				  Stt ,
				  SysRow ,
				  LoanStt ,
				  Remark
		FROM BD_Finance a
		LEFT JOIN (
				SELECT * FROM(
					SELECT BF.FinanceID, SUM(ISNULL(QmBalances,0)) AS QmBalances FROM BD_Finance BF LEFT JOIN
					( 
					SELECT a.FinanceID, a.[Path], F.QmBalances FROM BD_Finance a
					INNER JOIN BD_Funds F ON a.FinanceID = F.FinanceID 
					'+ @LimitSql +'
					) FT ON FT.Path LIKE BF.Path+''%''
					WHERE lvl>1 and BF.FinanceID <> 38 and BF.FinanceID <> 34
					GROUP BY BF.FinanceID
				)temp1
				UNION
				-- @FinanceType 1:收款单，13：付款单
				SELECT	CASE WHEN @FinanceType = 13 THEN 34 ELSE 38 END AS FinanceID,
				ISNULL(CASE WHEN @FinanceType = 13 THEN QmBP ELSE QmBR END,0) AS QmBalances
				FROM BD_ARAP WHERE BTypeID = '+ CONVERT(VARCHAR,@BtypeId) +'
		) bf ON a.FinanceID = bf.FinanceID
		'+ @LimitSql +'
		'+ @WhereSql +' AND SonNum = 0 '

IF @QueryType = 1 --查询项目编号
BEGIN
	SET @ColName = ' a.FinanceNO '
END ELSE
IF @QueryType = 2 --查询项目名称
BEGIN
	SET @ColName = ' a.FinanceName '
END

IF @ExactSearchStr <> '' SET @sql += ' AND '+ @ColName +' = @ExactSearchStr '

IF @SearchStr <> '' SET @sql += ' AND '+ @ColName +' Like ''%''+@SearchStr+''%'' '

	
/*****定义科目类型<科目的筛选条件>*****/
IF @FinanceType = 0 --所有科目
	SET @sql += ' AND (PATH LIKE ''%'')'
ELSE IF @FinanceType IN (1,2,6,7,11, 12,13,14) --收款账户（预收,微信）,付款账户（预付）,收支账户（预收预付）,收支账户,收款账户(预收)
BEGIN
	IF @FinanceType = 6 SET @TypeSql = ' OR a.FinanceID = 38 OR a.FinanceID = 34 OR a.Path LIKE ''0000500003%'' '
	SET @sql += ' AND (PATH LIKE ''00001%'''+ @TypeSql+')'
END
ELSE IF @FinanceType = 3 --其它收入
	SET @sql += ' AND (PATH LIKE ''0000200003%'')'
ELSE IF @FinanceType = 4 --费用合计
	SET @sql += ' AND (PATH LIKE ''0000300003%'')'
ELSE IF @FinanceType = 5 --现金合计
	SET @sql += ' AND (PATH LIKE ''0000100001%'')'
ELSE IF @FinanceType = 8 --收入项目
	SET @sql += ' AND (PATH LIKE ''00002%'')'
ELSE IF @FinanceType = 9 --支出项目
	SET @sql += ' AND (PATH LIKE ''00003%'')'
ELSE IF @FinanceType = 10 --会员储值
	SET @sql += ' AND (PATH LIKE ''0000500003%'')'
/**************************************/

END



IF @showStopped=0
	SET @sql +=' AND Stt <> 0'	
	
SET @sql +=') '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@QueryType','INT',@QueryType)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FinanceType','INT', @FinanceType)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ParID','INT', @ParID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipCardFinanceID','INT', @VipCardFinanceID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipCardTotal','NUMERIC(20,8)', @VipCardTotal)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'FinanceNO ASC','','ROWID ASC',1,1

GO






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

/*------------------------------------------
    作者：李文博
	日期：2014-07-16
	描述：单据类型TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCBillTypeList
(
	@ExactSearchStr VARCHAR(50)='',
	@SearchStr VARCHAR(50)='',
	@Type VARCHAR(50)='All'
)

AS

/*******************************************/
--@Type参数定义:
--All		所有单据（包含订单，盘点单，期初应收应付）
--Post		所有过账单据
--Settle	所有能结算单据
--Pay		付款单结算单据
--Rec		收款单结算单据
--InOut		出入库单据
--In		入库单据
--Out		出库单据
--Audit     可以审核的单据    


/*******************************************/




DECLARE @Sql NVARCHAR(MAX) = '', @WhereSql NVARCHAR(MAX) = '', @UnionSql NVARCHAR(MAX) = ''

IF @Type = 'All'			
	SET @WhereSql = ' WHERE 1=1'
ELSE IF @Type = 'Post'		
	SET @WhereSql = ' WHERE CanPost = 1'
ELSE IF @Type = 'Settle'	
	SET @WhereSql = ' WHERE SettleType <> 0'
ELSE IF @Type = 'Pay'		
	SELECT @WhereSql = ' WHERE SettleType = 2', @UnionSql = ' UNION ALL SELECT	BillTypeID, BillName, SortId FROM PD_BillType WHERE BillTypeID = 201 ' 
ELSE IF @Type = 'Rec'		
	SET @WhereSql = ' WHERE SettleType = 1'
ELSE IF @Type = 'InOut'		
	SET @WhereSql = ' WHERE InOutType <> 0'
ELSE IF @Type = 'In'		
	SET @WhereSql = ' WHERE InOutType IN (1,3)'
ELSE IF @Type = 'Out'		
	SET @WhereSql = ' WHERE InOutType IN (2,3)'
ELSE IF @Type = 'Audit'
	SET @WhereSql = ' WHERE BillTypeID NOT IN (507,508,998,999,307,311) '




SET  @Sql = '
SELECT	BillTypeID, 
		BillName 
FROM
 (
	SELECT	BillTypeID, 
			BillName,
			SortId
	FROM PD_BillType
	'+@WhereSql + @UnionSql+
') TypeData WHERE 1=1'	
			
IF @ExactSearchStr <> ''
   SET @Sql += 'AND BillName = '''+ @ExactSearchStr +''''
   
IF @SearchStr <> ''
   SET @Sql += ' AND BillName LIKE ''%' + @SearchStr + '%'''

SET @Sql += ' ORDER BY SortId'

--PRINT(@Sql)
EXEC(@Sql)

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博
	日期：2014-05-13
	描述：往来单位TC查询
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_TCBtypeList]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,  
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@Type INT,
	@showStopped BIT=1,
	@OperatorID INT = 1
	
)

AS

DECLARE @parpath VARCHAR(50)='',@sql NVARCHAR(MAX)='', @PathSql NVARCHAR(MAX)='', @LimitSql NVARCHAR(MAX)='', @WhereSql NVARCHAR(MAX)='',@sqlb NVARCHAR(max)='',@feildsql VARCHAR(max)='',@joinsql VARCHAR(max)=''

SELECT @joinsql+= CASE WHEN SourceType=1 THEN ' ' 
	WHEN SourceType=2 AND SOURCE=1 THEN ' LEFT JOIN BD_Goods G'+CAST(CustItemID AS VARCHAR)+' ON G'+CAST(CustItemID AS VARCHAR)+'.GoodsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=2 THEN ' LEFT JOIN BD_BType B'+CAST(CustItemID AS VARCHAR)+' ON B'+CAST(CustItemID AS VARCHAR)+'.BTypeID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=2 AND SOURCE=3 THEN ' LEFT JOIN BD_Whs W'+CAST(CustItemID AS VARCHAR)+' ON W'+CAST(CustItemID AS VARCHAR)+'.WhsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=4 THEN ' LEFT JOIN BD_Dept D'+CAST(CustItemID AS VARCHAR)+' ON D'+CAST(CustItemID AS VARCHAR)+'.DeptID=C.CustVal'+CAST(CustItemID AS VARCHAR)  
	WHEN SourceType=2 AND SOURCE=5 THEN ' LEFT JOIN BD_Employee E'+CAST(CustItemID AS VARCHAR)+' ON E'+CAST(CustItemID AS VARCHAR)+'.ElyID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=3 THEN ' LEFT JOIN BD_Custom C'+CAST(CustItemID AS VARCHAR) +' ON C'+CAST(CustItemID AS VARCHAR) +'.CustID=C.CustVal'+CAST(CustItemID AS VARCHAR)     
	END,
	@feildsql += CASE WHEN SourceType=1 THEN ' ,C.CustVal'+CAST(CustItemID AS VARCHAR)     
	WHEN SourceType=2 AND SOURCE=1 THEN ' ,G'+CAST(CustItemID AS VARCHAR)+'.GoodsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=2 THEN ' ,B'+CAST(CustItemID AS VARCHAR)+'.BTypeName AS CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=2 AND SOURCE=3 THEN ' ,W'+CAST(CustItemID AS VARCHAR)+'.WhsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=4 THEN ' ,D'+CAST(CustItemID AS VARCHAR)+'.DeptName AS CustVal'+CAST(CustItemID AS VARCHAR)  
	WHEN SourceType=2 AND SOURCE=5 THEN ' ,E'+CAST(CustItemID AS VARCHAR)+'.ElyName AS CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=3 THEN ',C'+CAST(CustItemID AS VARCHAR) +'.CustName AS CustVal'+CAST(CustItemID AS VARCHAR)     
	END
FROM dbo.BD_Btype_CustomItem


SELECT @parpath=PATH FROM BD_Btype_Type WHERE BtypeTypeID=@ParId

IF @Type = 0 --全部往来单位
	SET @PathSql = ' AND Path LIKE @parpath+''%'' '
ELSE IF @Type = 1 --物流公司
	SET @PathSql = ' AND (PATH LIKE ''00003%'') '

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0
BEGIN
	SET @WhereSql = 'WHERE 1=2 '
END ELSE
BEGIN
	SET @WhereSql = 'WHERE 1=1 '
END

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
	SET @LimitSql = ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =b.BTypeID '

SELECT @sql='
;WITH PagingData AS 
(
	SELECT	      b.BTypeID,
				  BTypeCode ,
				  BTypeName ,
				  BtypeAbbName ,
				  Spell ,
				  b.BtypeTypeID ,
				  AreaID ,
				  PriceLvl ,
				  LinkMan ,
				  Tel ,
				  MTel ,
				  Email ,
				  Adress ,
				  Bank ,
				  BankAcntNo ,
				  TaxNo ,
				  Boss ,
				  Stt ,
				  Remark,
				  PaidCircle,
				  CASE WHEN(QmAR - QmAP) >=0 THEN (QmAR - QmAP) ELSE 0 END AS ARTotal,
				  CASE WHEN(QmAR - QmAP) < 0 THEN (QmAP - QmAR) ELSE 0 END AS APTotal,
				  CASE WHEN(QmBR - QmBP) >=0 THEN (QmBR - QmBP) ELSE 0 END AS BRTotal,
				  CASE WHEN(QmBR - QmBP) < 0 THEN (QmBP - QmBR) ELSE 0 END AS BPTotal,
				  (QmAR-QmAP-QmBR+QmBP) AS YETotal
	FROM BD_Btype b
	'+ @LimitSql +'
	INNER JOIN 
	(
		SELECT   BtypeTypeID,
				 TypeName
		FROM BD_Btype_Type 
		WHERE 1=1 '+ @PathSql +'
	)typeid ON typeid.BtypeTypeID=b.BtypeTypeID
	
	LEFT JOIN BD_ARAP ar
	ON ar.BTypeID = b.BTypeID
	'+ @WhereSql

IF @SearchStr <> ''
	SET @sql +=' AND (BTypeCode Like ''%''+@SearchStr+''%'' OR BTypeName Like ''%''+@SearchStr+''%'' OR Spell LIKE ''%''+@SearchStr+''%'')'
IF @ExactSearchStr <> ''
	SET @sql += ' AND (BTypeCode = @ExactSearchStr OR BTypeName = @ExactSearchStr)'
IF @showStopped=0
	SET @sql +=' AND Stt=1'		
	
SET @sql +=') '

SET @sqlb= 'SELECT C.BaseID BTypeID'+@feildsql+' FROM BD_Btype_CustomVal C ' + @joinsql
		  
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.BtypeID=_DATA_a.BTypeID',@sqlb)

--PRINT(@sql)
EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'BTypeCode ASC', '', 'ROWID ASC',1,0

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：Wu Bin
	日期：2015-10-10
	描述：自定义基础资料指定类别TC查询
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_TCCustomList]
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,  
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@OperatorID INT = 1
	
)

AS

DECLARE @sql NVARCHAR(MAX)=''
SELECT @sql=';WITH PagingData AS (SELECT c.CustID, c.CustTypeID, CustCode, CustName FROM dbo.BD_Custom c WHERE CustTypeID = @ParId '
IF @SearchStr <> ''
	SET @sql +=' AND (c.CustCode Like ''%''+@SearchStr+''%'' OR c.CustName Like ''%''+@SearchStr+''%'')'	
IF @ExactSearchStr <> ''
	SET @sql += ' AND (c.CustCode = @ExactSearchStr OR c.CustName = @ExactSearchStr)'	
SET @sql +=') '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ParId','INT',@ParId)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'CustCode ASC', '', 'ROWID ASC',1,0

GO



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

/*------------------------------------------
    作者：Hlin
	日期：2015-10-15
	描述：基础资料来源TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCCustomSourceList
(
	@Type INT=0,
	@SearchStr VARCHAR(max)
)

AS

DECLARE @sql NVARCHAR(max)

IF @Type=2
BEGIN
	CREATE TABLE #Source(CustTypeID INT,TypeName VARCHAR(100) )
	INSERT INTO #Source
	        ( CustTypeID, TypeName )
	VALUES  ( 1, -- CustTypeID - int
	          '商品信息'  -- TypeName - varchar(100)
	          ),
	          ( 2, -- CustTypeID - int
	          '往来单位'  -- TypeName - varchar(100)
	          ),
	          ( 3, -- CustTypeID - int
	          '仓库'  -- TypeName - varchar(100)
	          ),
	          ( 4, -- CustTypeID - int
	          '部门'  -- TypeName - varchar(100)
	          ),
	          ( 5, -- CustTypeID - int
	          '职员'  -- TypeName - varchar(100)
	          )
	          
	          SELECT CustTypeID Source,TypeName SourceName
	          FROM #Source
	          WHERE TypeName LIKE '%'+@SearchStr+'%'
	          DROP TABLE #Source
END
ELSE	
	
	SELECT CustTypeID Source,TypeName SourceName
	FROM dbo.BD_Custom_Type
	WHERE TypeName LIKE '%'+@SearchStr+'%'

GO






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

/*------------------------------------------
    作者：李文博
	日期：2014-05-15
	描述：部门TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCDtypeList
(
	@ParID INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@IsOverLevel INT = 0,  --是否匹配所有层级 默认匹配末级
	@showStopped BIT=1,
	@IsTree BIT = 1      /*默认查询树形结构*/
)

AS

DECLARE @sql NVARCHAR(MAX)

IF @IsTree = 1
BEGIN
	SELECT @sql='
	;WITH PagingData AS 
	(
		SELECT	  DeptID,
				  DeptCode ,
				  DeptName ,
				  DeptAbbName ,
				  Spell ,
				  Path ,
				  ParID ,
				  Lvl ,
				  SonNum ,
				  Stt ,
				  Remark
		FROM BD_Dept 
		WHERE ParID=@parID '
END ELSE
BEGIN
	SELECT @sql='
	;WITH PagingData AS 
	(
		SELECT	  DeptID,
				  DeptCode ,
				  DeptName ,
				  DeptAbbName ,
				  Spell ,
				  Path ,
				  ParID ,
				  Lvl ,
				  SonNum ,
				  Stt ,
				  Remark
		FROM BD_Dept 
		WHERE 1 = 1 '
    IF @IsOverLevel = 0
        SET @sql += ' AND SonNum = 0 '
	IF @SearchStr <> ''
		SET @sql +=' AND (DeptCode Like ''%''+@SearchStr+''%'' OR DeptName Like ''%''+@SearchStr+''%''  OR Spell Like ''%''+@SearchStr+''%'')'
	
	IF @ExactSearchStr <> ''
		SET @sql += ' AND (DeptCode = @ExactSearchStr OR DeptName = @ExactSearchStr)'
END
IF @showStopped=0
	SET @sql +=' AND Stt=1'	
	
SET @sql +=') '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ParID','INT',@ParID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'DeptCode ASC', '', 'ROWID ASC',1,0
GO






/****** Object:  StoredProcedure [UP_BD_TCEtypeList]    Script Date: 05/21/2014 14:56:58 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_TCEtypeList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_TCEtypeList]
GO

/****** Object:  StoredProcedure [UP_BD_TCEtypeList]    Script Date: 05/21/2014 14:56:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：李文博
	日期：2014-05-13
	描述：职员TC查询
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_TCEtypeList]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@DeptID INT = 0,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@showStopped BIT=1
)

AS

DECLARE @sql NVARCHAR(max) = '', @DeptSql NVARCHAR(MAX) = ''



SELECT @sql='
;WITH PagingData AS 
(
	SELECT	  ElyID,
			  ElyCode ,
			  ElyName ,
			  e.Spell ,
			  Sex ,
			  Birthday ,
			  IdCard ,
			  Addr ,
			  PostCode ,
			  Tel ,
			  MTel ,
			  Email ,
			  QQ ,
			  EntryDate ,
			  e.DeptID ,
			  ed.DeptName,
			  ed.Stt AS DeptStt,
			  DemitDate ,
			  e.Stt ,
			  e.Remark
	FROM BD_Employee e
	INNER JOIN BD_Dept ed ON e.DeptId = ed.DeptId
	WHERE ElyID<>1 '

IF @DeptID <> 0
BEGIN
	SET @sql += ' AND e.DeptID = @DeptID '
END	

IF @SearchStr <> ''
	SET @sql +=' AND (ElyCode Like ''%''+@SearchStr+''%'' OR ElyName Like ''%''+@SearchStr+''%'' OR e.Spell Like ''%''+@SearchStr+''%''  OR DeptName Like ''%''+@SearchStr+''%'')'

IF @ExactSearchStr <> ''
		SET @sql += ' AND (ElyCode = @ExactSearchStr OR ElyName = @ExactSearchStr OR DeptName = @ExactSearchStr)'

IF @showStopped=0
	SET @sql +=' AND e.Stt=1'	
	
SET @sql +=') '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID','INT',@DeptID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'ElyCode ASC','','ROWID ASC',1,0

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博
	日期：2014-05-13
	描述：仓库TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCKtypeList
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@showStopped BIT=1,
	@IsLimit BIT=1,
	@OperatorID INT = 1
)

AS

DECLARE @parpath VARCHAR(50) = '',@sql NVARCHAR(max) = '', @LimitSql NVARCHAR(MAX) = '', @WhereSql NVARCHAR(MAX) = ''

SELECT @parpath=PATH FROM BD_Whs_Type WHERE WhsTypeID = @ParId

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0
BEGIN
 SET @WhereSql = ' WHERE 1=2 '
END ELSE
BEGIN
 SET @WhereSql = ' WHERE 1=1 '
END

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1 AND @IsLimit = 1
	SET @LimitSql = 'INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =k.WhsID '


SELECT @sql='
;WITH PagingData AS 
(
	SELECT	    k.WhsID,
				WhsNO,
			    WhsName,
				WhsAbbName,
				Spell,
				k.WhsTypeID,
				TypeName,
				AreaID,
				Responsible,
				LinkMan,
				Tel,
				[Address],
				PostCode,
				Stt,
				Remark
	FROM BD_Whs k 
	'+ @LimitSql +'
	INNER JOIN 
	(
		SELECT   WhsTypeID,
				 TypeName
		FROM BD_Whs_Type 
		WHERE Path LIKE @parpath+''%''
	)typeid ON typeid.WhsTypeID=k.WhsTypeID
	'+ @WhereSql
IF @SearchStr <> ''
	SET @sql +=' AND (WhsNO Like ''%''+@SearchStr+''%'' OR WhsName Like ''%''+@SearchStr+''%'' OR Spell Like ''%''+@SearchStr+''%'')'
	
IF @ExactSearchStr <> ''
	SET @sql += ' AND (WhsNO = @ExactSearchStr OR WhsName = @ExactSearchStr )'
		
IF @showStopped=0
	SET @sql +=' AND Stt=1'	
	
SET @sql +=') '
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'WhsNO ASC','','ROWID ASC',1,1

GO



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

/*------------------------------------------
    作者：李文博
	日期：2015-05-26
	描述：多账户选择
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCMulAtypeList
(
	@PayRecType NVARCHAR(5) = 'P',
	@YRYP	INT=0,
	@VipCardID INT=0,
	@IsWeiXin INT = 0,
	@OperatorID INT = 1
)

AS

/*******************************************/
--@PayRecType参数定义:
--P		付款账户
--R		收款账户
/*******************************************/




DECLARE @sql NVARCHAR(MAX), @TypeSql NVARCHAR(MAX), @LimitSql NVARCHAR(MAX) = '', @WhereSql NVARCHAR(MAX) = ''
DECLARE @VipCardTotal NUMERIC(20,8) = 0, @VipCardFinanceID INT = 0, @VipCardTypeID INT = 0

SET @TypeSql = ' (Path like ''00001%'' AND SonNum = 0) '

IF @PayRecType = 'P' AND @YRYP = 1
BEGIN
	SET @TypeSql += ' OR a.FinanceID = 34'
END ELSE
IF @PayRecType = 'R' AND @YRYP = 1
BEGIN
	SET @TypeSql += ' OR a.FinanceID = 38'
END

IF @VipCardID <> 0
		BEGIN
			SELECT @VipCardTotal = MoneyBalance, @VipCardTypeID = VipCardTypeID FROM VS_VipCard WHERE VipCardID = @VipCardID
			SELECT @VipCardFinanceID = FinanceID FROM VS_VipCardType WHERE VipCardTypeID = @VipCardTypeID
			SET @TypeSql += ' OR a.FinanceID = @VipCardFinanceID '
		END

IF dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 0
BEGIN
	SET @WhereSql = 'WHERE 1=2'
END ELSE
BEGIN
	SET @WhereSql = 'WHERE 1=1 AND a.Stt<>0'
END

IF @IsWeiXin = 0
BEGIN
	SET @WhereSql += ' AND a.FinanceID <> 42'
END

IF dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 1
	SET @LimitSql = 'INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) al ON al.FinanceID =a.FinanceID '

SET @sql = '
SELECT	  a.FinanceID,
				  FinanceNO ,
				  FinanceName ,
				  CASE WHEN (a.ParID = 41 OR a.FinanceID = 41) THEN @VipCardTotal ELSE ISNULL(QmBalances, 0) END AS QmBalances,
				  Path ,
				  ParID ,
				  Lvl ,
				  SonNum ,
				  Stt ,
				  SysRow ,
				  LoanStt ,
				  Remark
		FROM BD_Finance a
		LEFT JOIN BD_Funds bf ON a.FinanceID = bf.FinanceID
		'+ @LimitSql +'
		'+ @WhereSql +' AND ('+ @TypeSql +') 
'

EXEC sp_executesql @Sql,N'@OperatorID INT,@VipCardTotal NUMERIC(20,8),@VipCardFinanceID INT',@OperatorID, @VipCardTotal, @VipCardFinanceID

GO






/****** Object:  StoredProcedure [UP_BD_TCEtypeList]    Script Date: 05/21/2014 14:56:58 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_TCOperatorList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_BD_TCOperatorList]
GO

/****** Object:  StoredProcedure [UP_BD_TCOperatorList]    Script Date: 05/21/2014 14:56:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：李文博
	日期：2014-06-03
	描述：职员TC查询
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_TCOperatorList]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50) = '',
	@ShowAdmin BIT = 1,
	@ShowCreator BIT = 1,
	@showStopped BIT=1
)

AS

DECLARE @sql NVARCHAR(max), @CreateTableSql NVARCHAR(MAX)

SET @CreateTableSql = '

DECLARE @Role TABLE (ID INT, RoleName NVARCHAR(2000))
INSERT INTO @Role 
        ( ID, RoleName)
SELECT OperID, RoleName FROM SS_Oper_Role sor INNER JOIN SS_Role sr ON sor.RoleID = sr.RoleID

'

SELECT @sql=@CreateTableSql+'
;WITH PagingData AS 
(
	SELECT * FROM
	(
		SELECT	  op.ElyID AS OperatorID,
				  ElyCode  AS OperatorCode,
				  ElyName  AS OperatorName,
				  op.PASSWORD,
				  Spell ,
				  Sex ,
				  Birthday ,
				  IdCard ,
				  Addr ,
				  PostCode ,
				  Tel ,
				  MTel ,
				  Email ,
				  QQ ,
				  EntryDate ,
				  DemitDate ,
				  op.SysRow,
				  op.Stt ,
				  ISNULL(op.Remark,'''') AS Remark,
				  ISNULL(role.RoleName, '''') AS RoleName
		FROM SS_Operator op 
		INNER JOIN BD_Employee e ON op.ElyID = e.ElyID
		LEFT JOIN (
			SELECT ID, RoleName
			FROM(
				SELECT DISTINCT ID FROM @Role
			)A
			OUTER APPLY(
				SELECT 
					RoleName = STUFF(REPLACE(REPLACE(
						(
							SELECT RoleName FROM @Role N
							WHERE ID = A.ID
							FOR XML AUTO
						), ''<N RoleName="'','',''), ''"/>'', ''''), 1, 1, '''')
			)N
		) role ON op.ElyID = role.ID
		UNION ALL
		SELECT	  999999 AS OperatorID,
				  ''creator'' AS OperatorCode,
				  ''制单人''  AS OperatorName,
				  '''' PASSWORD,
				  ''zdr'' AS Spell ,
				  0 AS Sex ,
				  ''1900-01-01'' AS Birthday ,
				  '''' AS IdCard ,
				  '''' AS Addr ,
				  '''' AS PostCode ,
				  '''' AS Tel ,
				  '''' AS MTel ,
				  '''' AS Email ,
				  '''' AS QQ ,
				  ''1900-01-01'' AS EntryDate ,
				  ''9999-01-01'' AS DemitDate ,
				  1 AS SysRow,
				  1 AS Stt ,
				  '''' AS Remark,
				  '''' AS RoleName
	) A
	WHERE 1=1'
	
IF @SearchStr <> ''
	SET @sql +=' AND (OperatorCode Like ''%''+@SearchStr+''%'' OR OperatorName Like ''%''+@SearchStr+''%'')'
	
IF @ExactSearchStr <> ''
		SET @sql += ' AND (OperatorCode = @ExactSearchStr OR OperatorName = @ExactSearchStr)'

IF @ShowAdmin = 0
	SET @sql += ' AND OperatorID <>1 '

IF @ShowCreator = 0
	SET @sql += ' AND OperatorID <>999999 '
		
IF @showStopped=0
	SET @sql +=' AND Stt=1'	
	
SET @sql +=') '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'OperatorCode ASC','','ROWID ASC',1,1

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博	
	日期：2014-05-14
	描述：货位TC查询
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_TCPTtypeList]
(
	@ParId INT = 0,
	@PageNo INT=0,
	@PageSize INT=0,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@GoodsID INT = 0, /*用于显示商品的库存数量*/
	@ShowStockQty BIT =1, /*只显示有库存数量的货位*/
	@showStopped BIT =1
)

AS
SET NOCOUNT ON

DECLARE @sql NVARCHAR(MAX)

SELECT @sql='
WITH PagingData AS 
(
	SELECT	    pt.WhsPtID,
				WhsPtNO,
				WhsPtName,
				WhsID,
				WhsPtType,
				Stt,
				Remark,
				ISNULL(Qty,0) Qty
	FROM BD_Whs_Position pt
	LEFT JOIN 
	(
		SELECT GoodsID, WhsPtID, SUM(Qty) Qty 
		FROM PD_GoodsStock_Detail WHERE GoodsID = @GoodsID
		GROUP BY GoodsID, WhsPtID
	)stock ON pt.WhsPtID = stock.WhsPtID
	WHERE WhsID = @ParID '

IF @ShowStockQty = 1
	SET @sql += ' AND Qty<>0'
IF @SearchStr <> ''
	SET @sql +=' AND (WhsPtNO Like ''%''+@SearchStr+''%'' OR WhsPtName Like ''%''+@SearchStr+''%'' )'
IF @ExactSearchStr <> ''
	SET @sql += ' AND (WhsPtNO = @ExactSearchStr OR WhsPtName = @ExactSearchStr )'
	
IF @showStopped=0
	SET @sql +=' AND Stt=1'	


		
SET @sql +=') '
--PRINT (@sql)
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsID','INT',@GoodsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ParID','VARCHAR(50)',@ParId)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'WhsPtNO ASC','','ROWID ASC',1,0

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博
	日期：2014-05-15
	描述：商品TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_BD_TCPtypeList
(
	@ParId INT=0,
	@PageNo INT=0,
	@PageSize INT=0,
	@IsBtypeNo BIT = 0,
	@BtypeID INT = 0,
	@QueryType INT = 1,
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50) ='',
	@showStopped BIT=1,
	@IsOS BIT = 0
)

AS

DECLARE @parpath VARCHAR(50) = '',@sql NVARCHAR(MAX) = '', @ColName NVARCHAR(100) = '', @MulQuerySql NVARCHAR(MAX) = ''
DECLARE @QuerySql NVARCHAR(MAX) = '', @BtypeNoSql NVARCHAR(MAX) = '', @BtypeCol NVARCHAR(MAX) = '',@sqlb NVARCHAR(max)='',@feildsql VARCHAR(max)='',@joinsql VARCHAR(max)=''
SELECT @parpath=[PATH] FROM BD_Goods_Type WHERE GoodsTypeID=@ParId


SELECT @joinsql+= CASE WHEN SourceType=1 THEN ' ' 
	WHEN SourceType=2 AND SOURCE=1 THEN ' LEFT JOIN BD_Goods G'+CAST(CustItemID AS VARCHAR)+' ON G'+CAST(CustItemID AS VARCHAR)+'.GoodsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=2 THEN ' LEFT JOIN BD_BType B'+CAST(CustItemID AS VARCHAR)+' ON B'+CAST(CustItemID AS VARCHAR)+'.BTypeID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=2 AND SOURCE=3 THEN ' LEFT JOIN BD_Whs W'+CAST(CustItemID AS VARCHAR)+' ON W'+CAST(CustItemID AS VARCHAR)+'.WhsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=4 THEN ' LEFT JOIN BD_Dept D'+CAST(CustItemID AS VARCHAR)+' ON D'+CAST(CustItemID AS VARCHAR)+'.DeptID=C.CustVal'+CAST(CustItemID AS VARCHAR)  
	WHEN SourceType=2 AND SOURCE=5 THEN ' LEFT JOIN BD_Employee E'+CAST(CustItemID AS VARCHAR)+' ON E'+CAST(CustItemID AS VARCHAR)+'.ElyID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=3 THEN ' LEFT JOIN BD_Custom C'+CAST(CustItemID AS VARCHAR) +' ON C'+CAST(CustItemID AS VARCHAR) +'.CustID=C.CustVal'+CAST(CustItemID AS VARCHAR)     
	END,
	@feildsql += CASE WHEN SourceType=1 THEN ' ,C.CustVal'+CAST(CustItemID AS VARCHAR)     
	WHEN SourceType=2 AND SOURCE=1 THEN ' ,G'+CAST(CustItemID AS VARCHAR)+'.GoodsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=2 THEN ' ,B'+CAST(CustItemID AS VARCHAR)+'.BTypeName AS CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=2 AND SOURCE=3 THEN ' ,W'+CAST(CustItemID AS VARCHAR)+'.WhsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
	WHEN SourceType=2 AND SOURCE=4 THEN ' ,D'+CAST(CustItemID AS VARCHAR)+'.DeptName AS CustVal'+CAST(CustItemID AS VARCHAR)  
	WHEN SourceType=2 AND SOURCE=5 THEN ' ,E'+CAST(CustItemID AS VARCHAR)+'.ElyName AS CustVal'+CAST(CustItemID AS VARCHAR)   
	WHEN SourceType=3 THEN ',C'+CAST(CustItemID AS VARCHAR) +'.CustName AS CustVal'+CAST(CustItemID AS VARCHAR)     
	END
FROM dbo.BD_Goods_CustomItem 




SET @ColName = CASE @QueryType 
WHEN 1 THEN ' p.GoodsNo '      --查询商品编号
WHEN 2 THEN ' p.GoodsName '    --查询商品名称
WHEN 3 THEN ' p.GoodsAbbName ' --查询简名
WHEN 4 THEN ' p.Brand '        --查询品牌
WHEN 5 THEN ' p.Spell '        --查询拼音码
WHEN 6 THEN ' p.Spec '		   --查询规格
WHEN 7 THEN ' p.Model '		   --查询型号
WHEN 8 THEN ' p.Place '		   --查询产地
WHEN 99 THEN ' gn.GoodsNo'	   --查询往来单位商品编号	
ELSE  ' p.GoodsNo ' END


IF @IsBtypeNo = 1
	OR EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'UsePtypeQuery' AND CfgValue = '1') --需要往来单位商品编号
BEGIN
	SET @BtypeNoSql = ' LEFT JOIN (SELECT GoodsID, GoodsNo FROM BD_Goods_NO WHERE BtypeID = @BtypeID) gn ON p.GoodsID = gn.GoodsID'
	SET @BtypeCol = 'ISNULL(gn.GoodsNo,'''') AS BtypeGoodsNO, '
END

--单据局部更新
IF @ExactSearchStr <> ''
BEGIN
	--5.0 5.1 5.2的算法是只能更新列，6.0通用定制改为 编号，名称等查询	
	--模糊查询
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'UsePtypeQuery' AND CfgValue = '1')
	BEGIN	
		--IF (@QueryType=99)
		--BEGIN
		--	SET @QuerySql = ' AND'+ @ColName + '= @ExactSearchStr'
		--END 
		--ELSE 
		--BEGIN 
			SET @QuerySql = ' AND (
									p.GoodsNo =  '''+@ExactSearchStr+''' 
									OR p.GoodsName = '''+@ExactSearchStr+'''
									OR p.GoodsAbbName = '''+@ExactSearchStr+'''
									OR p.Brand ='''+@ExactSearchStr+'''
									OR p.Spell = '''+@ExactSearchStr+'''
									OR p.Spec = '''+@ExactSearchStr+'''
									OR p.Model = '''+@ExactSearchStr+'''
									OR p.Place = '''+@ExactSearchStr+'''
									OR gn.GoodsNo = '''+@ExactSearchStr+'''
								  )'
		--END 
	END
	ELSE
	BEGIN
		SET @QuerySql = ' AND'+ @ColName + '= @ExactSearchStr'
	END							  
END 
ELSE IF @SearchStr <> ''
BEGIN
	--模糊查询
	IF EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'UsePtypeQuery' AND CfgValue = '1')
	BEGIN
		SET @MulQuerySql = ' AND (
								p.GoodsNo LIKE  ''%'+@SearchStr+'%'' 
								OR p.GoodsName LIKE ''%'+@SearchStr+'%''
								OR p.GoodsAbbName LIKE ''%'+@SearchStr+'%''
								OR p.Brand LIKE''%'+@SearchStr+'%''
								OR p.Spell LIKE ''%'+@SearchStr+'%''
								OR p.Spec LIKE ''%'+@SearchStr+'%''
								OR p.Model LIKE ''%'+@SearchStr+'%''
								OR p.Place LIKE ''%'+@SearchStr+'%''
								OR gn.GoodsNo LIKE ''%'+@SearchStr+'%''
							  )'	
	END
	ELSE
	BEGIN
		SELECT	ROW_NUMBER() OVER( ORDER BY a) AS ROWID, a INTO #temp fROM dbo.UF_OT_Split(@SearchStr,' ')
		DECLARE @I INT = 1, @Str NVARCHAR(500) = ''
		WHILE (@I >= 1)
		BEGIN
			SET @Str = ''
			SELECT @Str = a FROM #temp WHERE ROWID = @I
			IF @Str = '' BREAK
			SET @MulQuerySql += 'AND '+ @ColName +' LIKE ''%' + @Str + '%'' '
			SET @I = @I + 1
		END
	END	
END


SELECT @sql='
;WITH PagingData AS 
(
	SELECT		  p.GoodsID,	    
				  p.GoodsNo ,
				  '+ @BtypeCol +'
				  p.GoodsTypeID ,
				  GoodsName ,
				  GoodsAbbName ,
				  Spell ,
				  Spec ,
				  Model ,
				  Brand,
				  Place ,
				  BarCode,
				  Unit,
				  KG ,
				  PptGroupID ,
				  Stt ,
				  Del ,
				  Remark ,
				  IsOS,
				  CostMethod,
				  DateType,
				  ValidDays,
				  NearbyDays,
				  UpdateTag,
				  IsSerial
	FROM BD_Goods p
	INNER JOIN 
	(
		SELECT   GoodsTypeID,
				 TypeName
		FROM BD_Goods_Type 
		WHERE Path LIKE @parpath+''%''
	)typeid ON typeid.GoodsTypeID=P.GoodsTypeID
	INNER JOIN
	(
		SELECT GoodsID, BarCode, Unit FROM BD_Goods_Price WHERE UnitID = 1
	) barcode ON barcode.GoodsID = p.GoodsID
	'+ @BtypeNoSql +'
	WHERE 1=1 '+ @MulQuerySql + @QuerySql
	
IF @showStopped=0
	SET @sql +=' AND p.Stt=1'	
IF @IsOS = 1
	SET @sql += ' AND p.IsOS=1'
	
SET @sql +=') '

SET @sqlb= 'SELECT C.BaseID GoodsID'+@feildsql+' FROM BD_Goods_CustomVal C ' + @joinsql

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@parpath','VARCHAR(50)',@parpath)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BtypeID','INT', @BtypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsID=_DATA_a.GoodsID',@sqlb)

--PRINT(@sql)
EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'GoodsNo ASC', '', 'ROWID ASC',1,0

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：Wu Bin
	日期：2015-10-16
	描述：商品套餐TC查询
-------------------------------------------*/
CREATE PROCEDURE [UP_BD_TCPtypeSuiteList]
(
	@PageNo INT=0,
	@PageSize INT=0,  
	@SearchStr VARCHAR(50)='',
	@ExactSearchStr VARCHAR(50)='',
	@OperatorID INT = 1
	
)

AS

DECLARE @sql NVARCHAR(MAX)=''
SELECT @sql=';WITH PagingData AS (SELECT SuiteID, SuiteCode, SuiteName, Remark FROM dbo.OS_GoodsSuite WHERE 1 = 1 '
IF @SearchStr <> ''
	SET @sql +=' AND (SuiteCode Like ''%''+@SearchStr+''%'' OR SuiteName Like ''%''+@SearchStr+''%'')'	
IF @ExactSearchStr <> ''
	SET @sql += ' AND (SuiteCode = @ExactSearchStr OR SuiteName = @ExactSearchStr)'	
SET @sql +=') '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ExactSearchStr','VARCHAR(50)',@ExactSearchStr)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SearchStr','VARCHAR(50)',@SearchStr)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'SuiteCode ASC', '', 'ROWID ASC',1,0

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_UpdatePriceList]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_UpdatePriceList]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：WangWei
	日期：2014-5-23
	描述：商品物价信息更新
	/*** 2015-02-05 LWB Modify***/
	/*** 2015-12-22 WB Modify***/
-------------------------------------------*/
CREATE PROCEDURE UP_BD_UpdatePriceList
(
	 @PriceExpress VARCHAR(MAX)
	,@GoodsTypeID INT=0
	,@fullName VARCHAR(100)=''
	,@fullNameMatch int =0
	,@userCode VARCHAR(50)=''
	,@userCodeMatch int =0
	,@Spec VARCHAR(50)=''--规格
	,@SpecMatch int =0
	,@Model VARCHAR(50)=''--型号
	,@ModelMatch int =0
	,@Place VARCHAR(50)=''--产地
	,@PlaceMatch int =0
	,@UnitID int =0--计量单位
	,@PriceIndex int =0--价格类型
	,@PriceMin decimal(20,8)=-1 --最小值
	,@PriceMax decimal(20,8)=-1 --最大值
	,@showStock bit=0-- 只显示有库存的商品 0==所有
	,@showStopped BIT=0 --/*是否显示停用信息*/ 0=所有
)

AS
SET NOCOUNT ON
begin

DECLARE @sql NVARCHAR(max) = ''

SET @sql+=';WITH '

SET @sql+='
		AvgData as (
						SELECT goodsid,
								(CASE  sum(qty) WHEN 0 THEN 0
							ELSE  CAST(sum(Total) as numeric(20,8))/CAST(sum(qty) as numeric(20,8)) END) as AvgPrice
							,CAST(sum(qty) as numeric(20,4)) as StockQty
						FROM PD_GoodsStock GROUP BY GoodsID
		 ),
		PChPriceData as 
		(
		SELECT  GoodsID,max(PchDate)as maxDate,UnitID  FROM PD_PRiceTrail b
		GROUP BY  GoodsID,UnitID
		)
		, priceData as 
		(
		SELECT  a.goodsid,ISNULL(PchPrice,0)*ISNULL(a.PchDis,0) as PchPrice,a.UnitID  from PD_PRiceTrail a inner join PChPriceData b on a.goodsid=b.goodsid and b.maxDate=a.pchdate and a.UnitID=b.UnitID

		), '  --最近进价
		
SET @sql+='
	PagingData AS
	(
		SELECT 
		   p.[GoodsID]
		  ,p.[UnitID]
		  ,p.[Price_Rtl]
		  ,ISNULL(p.[Price1],0) as Price1
		  ,ISNULL(p.[Price2],0) as Price2
		  ,ISNULL(p.[Price3],0) as Price3
		  ,ISNULL(p.[Price4],0) as Price4
		  ,ISNULL(p.[Price5],0) as Price5
		  ,ISNULL(p.[Price6],0) as Price6
		  ,ISNULL(p.[Price7],0) as Price7
		  ,ISNULL(p.[Price8],0) as Price8
		  ,ISNULL(p.[Price9],0) as Price9
		  ,ISNULL(p.[Price10],0) as Price10
		  ,ISNULL(p.[Price11],0) as Price11
		  ,ISNULL(p.[Price12],0) as Price12
		  ,ISNULL(p.[Price13],0) as Price13
		  ,ISNULL(p.[Price14],0) as Price14
		  ,ISNULL(p.[Price15],0) as Price15
		  ,CAST(ISNULL(pd.PchPrice,0) AS NUMERIC(20,8)) AS PchPrice  --最近进价
		  ,CAST(ISNULL(ad.AvgPrice,0) as numeric(20,8)) * p.Convfactor  AS AvgPrice'  
SET 	@sql+='
	FROM [BD_Goods_Price] p
			INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
			INNER JOIN BD_Goods_Type gt ON g.GoodsTypeID=gt.GoodsTypeID 
			LEFT JOIN AvgData ad ON P.goodsID=ad.GoodsID  			' --成本均价

	SET @sql+='	LEFT JOIN priceData pd ON p.GoodsID=pd.goodsid AND p.UnitID=pd.UnitID '	 --最近进价	
	
SET @sql+='	WHERE 1=1 '


if @PriceIndex<>0 AND ( @PriceMin<>-1 OR  @PriceMax<>-1)
BEGIN
	if(@PriceIndex=-1)--成本均价
	BEGIN
		if(@PriceMin<>-1)
			SET	@sql+=' AND ad.AvgPrice >=@PriceMin'	 
		if(@PriceMax<>-1)	
			SET	@sql+=' AND ad.AvgPrice <= @PriceMax '
	END	
	ELSE if(@PriceIndex=-2)--最近进价
	BEGIN
		 
		if(@PriceMin<>-1)
			SET	@sql+=' AND pd.PchPrice >= @PriceMin '
		if(@PriceMax<>-1)		
			SET	@sql+=' AND pd.PchPrice <= @PriceMin'	
	END	
	ELSE  
	BEGIN
		if(@PriceMin<>-1)
			SET	@sql+=' AND p.Price'+CAST(@PriceIndex as Varchar)+' >= @PriceMin  '	 
		if(@PriceMax<>-1)	
			SET	@sql+=' AND p.Price'+CAST(@PriceIndex as Varchar)+' <= @PriceMax  '
	END
	
END


IF @UnitID>0
BEGIN
		SET	@sql+=' AND p.UnitID=@UnitID '
END
	  
IF 	 @userCode<>''
BEGIN
	  	if(@userCodeMatch=0)
				SET @sql +='AND g.GoodsNo like ''%''+@userCode+''%'' '
		else if(@userCodeMatch=1)
				SET @sql +='AND g.GoodsNo = @userCode '	  	
END	  

IF 	 @fullName<>''
BEGIN
	  	if(@fullNameMatch=0)
				SET @sql +='AND g.GoodsName like ''%''+@fullName+''%'' '
		else if (@userCodeMatch=1)
			SET @sql +='AND g.GoodsName = ''%''+@fullName+''%'' '
END

IF 	 @Spec<>''
BEGIN
	  	if(@SpecMatch=0)
			SET @sql +='AND g.Spec like  ''%''+@Spec+''%'' '
		else if  (@SpecMatch=1)
			SET @sql +='AND g.Spec = @Spec '
END

IF 	 @Model<>''
BEGIN
	  	if(@ModelMatch=0)
			SET @sql +='AND g.Model like ''%''+@Model+''%'' '
		else if (@ModelMatch=1)
			SET @sql +='AND g.Model = @Model'	
	  	
END

IF 	 @Place<>''
BEGIN
	  	if(@PlaceMatch=0)
			SET @sql +='AND g.Place like ''%''+@Place+''%'' '
		else if (@PlaceMatch=0)
			SET @sql +='AND g.Place = @Place '
END
	  	
IF @GoodsTypeID>0
BEGIN
		SET	@sql+=' AND g.GoodsTypeID=@GoodsTypeID '
END

IF @showStock=1
BEGIN
		SET	@sql+='  '

END
IF @showStopped=0
BEGIN
		SET	@sql+=' AND g.stt=1'
END

SET @sql +=') 	MERGE [BD_Goods_Price] as target
				 USING ( SELECT  * from PagingData ) as a
				 ON a.GoodsID=target.GoodsID AND a.UnitID=target.UnitID
				 WHEN MATCHED THEN 
				  UPDATE SET '

/*定义拆分价格公式参数*/
DECLARE @NowPrice INT, @Opera VARCHAR(10), @NumberValue NUMERIC(20,8), @DigitLen INT, @PriceSql NVARCHAR(MAX) = ''
DECLARE @PriceTable TABLE (RowID INT, PriceValue VARCHAR(50))
DECLARE @upSql NVARCHAR(MAX)='', @expressParamLen INT = 0, @priceID INT = 0
/*END*/

INSERT INTO @PriceTable 
SELECT ROW_NUMBER() OVER(ORDER BY IDENT_CURRENT(1)) AS 'RowID',a AS PriceValue 
FROM dbo.UF_OT_Split(@PriceExpress,',')

SELECT @expressParamLen = COUNT(1) FROM @PriceTable 

/*拼装修改价格字段Sql*/
DECLARE @count INT = 1, @tmpSql NVARCHAR(MAX) = ''

WHILE @count <= @expressParamLen
BEGIN
    SELECT @priceID = CONVERT(INT, PriceValue) FROM @PriceTable WHERE RowID = @count
	SELECT @NowPrice = CONVERT(INT, PriceValue) FROM @PriceTable WHERE RowID = @count + 1
	SELECT @Opera = PriceValue FROM @PriceTable WHERE RowID = @count + 2
	SELECT @NumberValue = CONVERT(NUMERIC(18,8),PriceValue) FROM @PriceTable WHERE RowID = @count + 3
	SELECT @DigitLen = CONVERT(INT, PriceValue) FROM @PriceTable WHERE RowID = @count + 4
	
	IF @NowPrice = -1   --成本均价
  		SET @PriceSql = 'ROUND(CONVERT(NUMERIC(20,8), a.AvgPrice)'+@Opera+CAST(@NumberValue AS VARCHAR)+','+CAST(@DigitLen AS VARCHAR)+')'
	ELSE IF @NowPrice = -2  --最近进价
 		SET @PriceSql = 'ROUND(CONVERT(NUMERIC(20,8), a.PchPrice)'+@Opera+CAST(@NumberValue AS VARCHAR)+','+CAST(@DigitLen AS VARCHAR)+')'
	ELSE IF @NowPrice = 0  --0
 		SET @PriceSql = 'ROUND(0'+@Opera+CAST(@NumberValue AS VARCHAR)+','+CAST(@DigitLen AS VARCHAR)+')'
	ELSE 
		SET @PriceSql = 'ROUND(CONVERT(NUMERIC(20,8), a.Price'+CAST(@NowPrice AS VARCHAR)+')'+@Opera+CAST(@NumberValue AS VARCHAR)+','+CAST(@DigitLen AS VARCHAR)+')'
	SET @upSql += ' ,Price'+ CONVERT(VARCHAR(10),@priceID) +' = CASE WHEN '+ @PriceSql +' >0 THEN '+ @PriceSql + ' ELSE 0 END '	
	SET @count = @count + 5
END
		  
SET @sql+= RIGHT(@upSql, LEN(@upSql)-1) + ';'		
--PRINT(@SQL)	  
EXECUTE sys.sp_executesql @sql, 
N'@PriceMin decimal(20,8), @PriceMax decimal(20,8),@UnitID int,@showStock int,@GoodsTypeID int,@Place VARCHAR(50),@Model VARCHAR(50)
	,@Spec VARCHAR(50),@fullName VARCHAR(100),@userCode VARCHAR(50)'
,@PriceMin
,@PriceMax
,@UnitID
,@showStock
,@GoodsTypeID
,@Place
,@Model
,@Spec
,@fullName
,@userCode

end
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_BD_UpdatePriceTracil]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_BD_UpdatePriceTracil]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*------------------------------------------
    作者：WangWei
	日期：2014-5-23
	描述：价格跟踪批量更新
-------------------------------------------*/
CREATE PROCEDURE UP_BD_UpdatePriceTracil
(
	 @NumValue decimal(18,8) --更新的数量
	,@UpdatePrice varchar(30) --更新的字段
	,@GetPrice  varchar(30) --取值的字段
	,@Opera varchar(10)--操作符
	,@BtypeID INT=0
	,@GoodsTypeID INT=0 --商品分类
	,@fullName VARCHAR(100)=''
	,@fullNameMatch int =0
	,@userCode VARCHAR(50)=''
	,@userCodeMatch int =0
	,@Spec VARCHAR(50)=''--规格
	,@SpecMatch int =0
	,@Model VARCHAR(50)=''--型号
	,@ModelMatch int =0
	,@Place VARCHAR(50)=''--产地
	,@PlaceMatch int =0
	,@UnitID int =0--计量单位
	,@PriceColumn varchar(30)=''--价格类型
	,@PriceMin decimal(20,8)=-1 --最小值
	,@PriceMax decimal(20,8)=-1 --最大值
	,@showStopped BIT=0 --/*是否显示停用信息*/ 0=所有
	,@DigitLen int =8--小数位数
)

AS
SET NOCOUNT ON
begin

DECLARE @sql NVARCHAR(max)


SET @sql=''
SET @sql+=';WITH '

SET @sql+='
		AvgData as (
						SELECT goodsid,
								(CASE  sum(qty) WHEN 0 THEN 0
							ELSE  CAST(sum(Total) as numeric(20,8))/CAST(sum(qty) as numeric(20,8)) END) as AvgPrice
							,CAST(sum(qty) as numeric(20,4)) as StockQty
						FROM PD_GoodsStock GROUP BY GoodsID
		 ),
		PChPriceData as 
		(
		SELECT  GoodsID,max(PchDate)as maxDate,UnitID  FROM PD_PRiceTrail b
		GROUP BY  GoodsID,UnitID
		)
		, priceData as 
		(
		SELECT  a.goodsid,ISNULL(PchPrice,0)*ISNULL(a.PchDis,0) as PchPrice,a.UnitID  from PD_PRiceTrail a inner join PChPriceData b on a.goodsid=b.goodsid and b.maxDate=a.pchdate and a.UnitID=b.UnitID

		), '  --最近进价
		
SET @sql+='
	PagingData AS
	(
		SELECT 
			 Pr.GoodsID
			,Pr.UnitID
			,Pr.BtypeID
			,Pr.PchPrice
			,Pr.PchDis
			,Pr.SellPrice
			,Pr.SellDis
			,p.[Price1]
			,p.[Price2]
			,p.[Price3]
			,p.[Price4]
			,p.[Price5]
			,p.[Price6]
			,p.[Price7]
			,p.[Price8]
			,p.[Price9]
			,p.[Price10]
			,p.[Price11]
			,p.[Price12]
			,p.[Price13]
			,p.[Price14]
			,p.[Price15]
			,ISNULL(CAST(pd.PchPrice as numeric(20,8)),0) as RecentPrice  --最近进价
		  ,ISNULL(CAST(ad.AvgPrice as numeric(20,8)),0)*CAST( p.Convfactor as numeric(20,8)) as AvgPrice
		  
			 '  
SET 	@sql+='
	FROM 
			PD_PRiceTrail  pr
			INNER JOIN BD_Goods g ON pr.GoodsID=g.GoodsID
			INNER JOIN BD_Btype b ON b.BtypeID=pr.BtypeID
			LEFT JOIN [BD_Goods_Price] p ON Pr.GoodsID=p.GoodsID AND Pr.UnitID=p.UnitID
			LEFT JOIN AvgData ad ON P.goodsID=ad.GoodsID  			' --成本均价	
SET @sql+='	LEFT JOIN priceData pd ON p.GoodsID=pd.goodsid AND p.UnitID=pd.UnitID '	 --最近进价	
	
				
if (@GoodsTypeID<>0)
BEGIN 
	SET 	@sql+=' INNER JOIN BD_Goods_Type gt ON g.GoodsTypeID=gt.GoodsTypeID  '
END

	
SET @sql+='	WHERE 1=1 '


if ISNULL(@PriceColumn,'')<>'' AND ( @PriceMin<>-1 OR  @PriceMax<>-1)
BEGIN

	if (@PriceMin<>-1 )
		SET	@sql+=' AND (pr.'+@PriceColumn+' >= @PriceMin )  '	 
		 
	if (@PriceMax<>-1 )
		SET	@sql+=' AND (pr.'+@PriceColumn+' <= @PriceMax)  '	 
END


IF @UnitID>0
BEGIN
		SET	@sql+=' AND p.UnitID=@UnitID '
END

	  
IF 	 @userCode<>''
BEGIN
	if(@userCodeMatch=0)
			SET @sql +='AND g.GoodsNo like ''%''+@userCode+''%'' '
	else if(@userCodeMatch=1)
			SET @sql +='AND g.GoodsNo = @userCode '	  	
	  	
END	  

IF 	 @fullName<>''
BEGIN
	  	if(@fullNameMatch=0)
				SET @sql +='AND g.GoodsName like ''%''+@fullName+''%'' '
		else if (@userCodeMatch=1)
			SET @sql +='AND g.GoodsName = ''%''+@fullName+''%'' '
END

IF 	 @Spec<>''
BEGIN
	  	if(@SpecMatch=0)
			SET @sql +='AND g.Spec like  ''%''+@Spec+''%'' '
		else if  (@SpecMatch=1)
			SET @sql +='AND g.Spec = @Spec '
		
END

IF 	 @Model<>''
BEGIN
	  	if(@ModelMatch=0)
			SET @sql +='AND g.Model like ''%''+@Model+''%'' '
		else if (@ModelMatch=1)
			SET @sql +='AND g.Model = @Model'	
END


IF 	 @Place<>''
BEGIN
	  	if(@PlaceMatch=0)
			SET @sql +='AND g.Place like ''%''+@Place+''%'' '
		else if (@PlaceMatch=0)
			SET @sql +='AND g.Place = @Place '
END


  
	  	
IF @GoodsTypeID>0
BEGIN
		SET	@sql+=' AND g.GoodsTypeID=@GoodsTypeID '
END

IF @BtypeID>0
BEGIN
		SET	@sql+=' AND b.BtypeID=@BtypeID '
END


IF @showStopped=0
BEGIN
		SET	@sql+=' AND g.stt=1'
END


SET @sql +=') 	MERGE [PD_PRiceTrail] as tget
				 USING ( SELECT  * from PagingData ) as a
				 ON a.GoodsID=tget.GoodsID AND a.UnitID=tget.UnitID  AND a.BtypeID=tget.BtypeID 
				 WHEN MATCHED THEN 
				  UPdate Set '+CAST(@UpdatePrice as varchar)+'= '

DECLARE @upSql nvarchar(MAX)
SET @upSql=''

if(@GetPrice='0')				  
BEGIN
	SET @upSql = '  ROUND(CAST('+@GetPrice+'as numeric(20,8)) '+@Opera+CAST(@NumValue as varchar)+','+CAST(@DigitLen as varchar)+')'
END 
else 
	SET @upSql = 'ROUND(CAST( a.'+@GetPrice+' as numeric(20,8))'+@Opera+CAST(@NumValue as varchar)+','+CAST(@DigitLen as varchar)+')'

SET @sql+='CASE WHEN '+@upSql+'>0 THEN '+@upSql+' ELSE 0 END'
SET @sql+=';'		  
EXECUTE sys.sp_executesql @sql, 
N'@PriceMin decimal(20,8), @PriceMax decimal(20,8),@UnitID int,@GoodsTypeID int,@Place VARCHAR(50),@Model VARCHAR(50)
	,@Spec VARCHAR(50),@fullName VARCHAR(100),@userCode VARCHAR(50),@BtypeID INT'
,@PriceMin
,@PriceMax
,@UnitID
,@GoodsTypeID
,@Place
,@Model
,@Spec
,@fullName
,@userCode
,@BtypeID

end
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_ADJSQuery]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_MF_ADJSQuery
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2014-07-16
	描述：按单结算查询
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_ADJSQuery]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillStat TINYINT = 0,
	@BillTypeID VARCHAR(MAX)='',
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@BillCode VARCHAR(50) = '',
	@BillCodeMatch BIT = 0,
	@Summary VARCHAR(256)='',
	@SummaryMatch BIT = 0,
	@Description VARCHAR(100)='',
	@DescriptionMatch BIT = 0,
	@OrderFirst VARCHAR(20) = '',/*先排序*/
	@AscFirst INT = 1, 
	@OrderAgain VARCHAR(20) ='', /*再排序*/
	@AscAgain INT = 1,
	@IsSum BIT = 0, /*是否计算合计*/
	@IsHistory BIT = 0,
	@OperatorID INT = 1
) 
AS


DECLARE @Sql NVARCHAR(MAX) = '', @IndexSql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = '',@TableSql NVARCHAR(MAX) = ''
DECLARE @PchBill NVARCHAR(MAX) = '', @PchRetBill NVARCHAR(MAX) = '', @SellBill NVARCHAR(MAX) = '', @SellRetBill NVARCHAR(MAX) = ''
DECLARE @FeeRecBill NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = '', @SaleFreightBill NVARCHAR(MAX) = '', @BuyFreightBill NVARCHAR(MAX) = ''
DECLARE @FreightTableSql NVARCHAR(MAX) = '', @QCARBill NVARCHAR(MAX) = '', @QCAPBill NVARCHAR(MAX) = '', @QCTableSql NVARCHAR(MAX) = ''
DECLARE @OrderCol NVARCHAR(MAX) = '', @BillTypeSql NVARCHAR(MAX) = '', @Ret INT = 0
DECLARE @QCBillDate DATE = '1900-01-01', @QCPosTime DATETIME = '1900-01-01 00:00:00'

EXEC @Ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN
SET @IndexSql = ' WHERE I.BillDate BETWEEN @BeginDate AND @EndDate '

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0
BEGIN
	SET @IndexSql += ' AND 1=2'
END ELSE
IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
BEGIN
	SET @TableSql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID '
	SET @QCTableSql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID '
	SET @FreightTableSql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.LogistBTypeID'
END

SELECT @QCBillDate = StartDate FROM SS_MonthProc WHERE Period = 1
SET @QCPosTime = DATEADD(MS,2,CONVERT(DATETIME,@QCBillDate))

IF @BillTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BillType Table(BillTypeID INT)   
     INSERT  INTO @BillType SELECT typeid AS BillTypeID  FROM dbo.UF_OT_Split_Int(@BillTypeID,'','')   
     '  
	SET @BillTypeSql+=' INNER JOIN @BillType BT ON PR.BillTypeID=BT.BillTypeID '   
END

IF @BTypeID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     SET @TableSql += ' INNER JOIN @BType B ON I.BTypeID=B.BTypeID '
     SET @FreightTableSql += ' INNER JOIN @BType B ON I.LogistBTypeID =B.BTypeID'
     SET @QCTableSql = ' INNER JOIN @BType B ON I.BTypeID=B.BTypeID '
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
	SET @TableSql+=' INNER JOIN @DType D ON I.DeptID=D.DeptID '  
	SET @FreightTableSql += ' INNER JOIN @DType D ON I.DeptID=D.DeptID '  
END

IF @ElyID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '    
	SET @FreightTableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '    
END


IF @BillCode <> ''
BEGIN
	IF @BillCodeMatch = 1 
		SET @IndexSql += ' AND BillCode = @BillCode '
	ELSE
		SET @IndexSql += ' AND BillCode Like ''%''+@BillCode+''%'' ' 
END

IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 1 
		SET @IndexSql += ' AND Summary = @Summary '
	ELSE
		SET @IndexSql += ' AND Summary Like ''%''+@Summary+''%'' ' 
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 1 
		SET @IndexSql += ' AND Description = @Description '
	ELSE
		SET @IndexSql += ' AND Description Like ''%''+@Description+''%'' ' 
END
IF @OrderFirst <> ''
BEGIN
	IF @AscFirst = 2 SET @OrderCol = @OrderFirst+' DESC' ELSE SET @OrderCol = @OrderFirst +' ASC'
END
IF @OrderAgain <> ''
BEGIN
	IF @OrderCol <> '' SET @OrderCol +=', '
	IF @AscAgain = 2 SET @OrderCol += @OrderAgain+' DESC' ELSE SET @OrderCol += @OrderAgain +' ASC'
END

IF @OrderCol = '' SET @OrderCol = 'BillDate ASC'

--采购入库单
SET @PchBill = '
SELECT	101 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
		Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		Privilege,			PayRecTotal,	I.PaidTotal
FROM PD_PchBill I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

--采购入库单运费
SET @BuyFreightBill = '
SELECT	101 AS BillTypeID,	BillCode,		BillDate,		Freight,	(Freight - I.FreightPaidTotal - FreightTotal) AS BalanceTotal,
		''【物流运费】''+Summary,		Description,	I.LogistBTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		0 AS Privilege,	FreightTotal,	I.FreightPaidTotal
FROM PD_PchBill I '+ @FreightTableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0 AND  Freight<> 0' 


--采购退货单
SET @PchRetBill = '
SELECT	102 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
		Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		Privilege,			PayRecTotal,	I.PaidTotal
FROM PD_PchRetBill I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

--销售出库单
SET @SellBill = '
SELECT	201 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
		Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		Privilege,			PayRecTotal,	I.PaidTotal
FROM PD_SellBill I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

--销售出库单运费
SET @SaleFreightBill = '
SELECT	201 AS BillTypeID,	BillCode,		BillDate,		Freight,	(Freight - I.FreightPaidTotal - FreightTotal) AS BalanceTotal,
		''【物流运费】''+Summary,		Description,	I.LogistBTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		0 AS Privilege,	FreightTotal,	I.FreightPaidTotal
FROM PD_SellBill I '+ @FreightTableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0 AND IsOS = 0 AND  Freight<> 0' 

--销售退货单
SET @SellRetBill = '
SELECT	202 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
		Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		Privilege,			PayRecTotal,	I.PaidTotal
FROM PD_SellRetBill I  '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 
--其它收入单,一般费用单
SET @FeeRecBill = '
SELECT	I.BillTypeID,	BillCode,		BillDate,	Total,	(Total - PayRecTotal - I.PaidTotal) AS BalanceTotal,
		Summary,		Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		0 AS Privilege,	PayRecTotal,	I.PaidTotal
FROM MF_FeeRecBill I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

--应收增加,应收减少，应付增加，应付减少
SET @ARAPBill = '
SELECT	I.BillTypeID,	BillCode,		BillDate,	Total,	(Total - I.PaidTotal) AS BalanceTotal,
		Summary,		Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
		0 AS Privilege,	0 AS PayRecTotal,	I.PaidTotal
FROM MF_ARAPBill I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

--期初应收
SET @QCARBill = '
SELECT * FROM(
SELECT	998 AS BillTypeID,		''本年期初应收'' AS BillCode,		@QCBillDate AS BillDate,	QcAR AS Total,	(QcAR - ARPaidTotal) AS BalanceTotal,
		''本年期初应收'' AS Summary,	'''' AS	Description,	I.BTypeID,			NULL AS DeptID,		NULL AS ElyID,	
		@QCPosTime AS PosTime,	@QCPosTime AS CreateTime,	I.ARAPID AS BillNo,		0 AS Privilege,		0 AS PayRecTotal,	ARPaidTotal AS PaidTotal
FROM BD_ARAP I '+ @QCTableSql+'
WHERE QcAR <> 0
) I '+ @IndexSql 

--期初应付
SET @QCAPBill = '
SELECT * FROM (
SELECT	999 AS BillTypeID,		''本年期初应付'' AS BillCode,		@QCBillDate AS BillDate,	QcAP AS Total,	(QcAP - APPaidTotal) AS BalanceTotal,
		''本年期初应付'' AS Summary,	'''' AS	Description,	I.BTypeID,			NULL AS DeptID,		NULL AS ElyID,	
		@QCPosTime AS PosTime,	@QCPosTime AS CreateTime,	I.ARAPID AS BillNo,		0 AS Privilege,		0 AS PayRecTotal,	APPaidTotal AS PaidTotal
FROM BD_ARAP I '+ @QCTableSql+'
WHERE QcAP <> 0
) I '+ @IndexSql

IF @IsHistory = 1
BEGIN
	--采购入库单
	SET @PchBill += '
	UNION ALL
	SELECT	101 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
			Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			Privilege,			PayRecTotal,	I.PaidTotal
	FROM PD_PchBill_His I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

	--采购入库单运费
	SET @BuyFreightBill += '
	UNION ALL
	SELECT	101 AS BillTypeID,	BillCode,		BillDate,		Freight,	(Freight - I.FreightPaidTotal - FreightTotal) AS BalanceTotal,
			''【物流运费】''+Summary,		Description,	I.LogistBTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			0 AS Privilege,	FreightTotal,	I.FreightPaidTotal
	FROM PD_PchBill_His I '+ @FreightTableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0 AND  Freight<> 0' 

	--采购退货单
	SET @PchRetBill += '
	UNION ALL
	SELECT	102 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
			Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			Privilege,			PayRecTotal,	I.PaidTotal
	FROM PD_PchRetBill_His I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

	--销售出库单
	SET @SellBill += '
	UNION ALL
	SELECT	201 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
			Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			Privilege,			PayRecTotal,	I.PaidTotal
	FROM PD_SellBill_His I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 

	--销售出库单运费
	SET @SaleFreightBill += '
	UNION ALL
	SELECT	201 AS BillTypeID,	BillCode,		BillDate,		Freight,	(Freight - I.FreightPaidTotal - FreightTotal) AS BalanceTotal,
			''【物流运费】''+Summary,		Description,	I.LogistBTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			0 AS Privilege,	FreightTotal,	I.FreightPaidTotal
	FROM PD_SellBill_His I '+ @FreightTableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0 AND IsOS = 0 AND Freight<> 0' 

	--销售退货单
	SET @SellRetBill += '
	UNION ALL
	SELECT	202 AS BillTypeID,	BillCode,		BillDate,	Total,	(Total - Privilege - PayRecTotal - I.PaidTotal) AS BalanceTotal,
			Summary,			Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			Privilege,			PayRecTotal,	I.PaidTotal
	FROM PD_SellRetBill_His I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 
	
	--其它收入单,一般费用单
	SET @FeeRecBill += '
	UNION ALL
	SELECT	I.BillTypeID,	BillCode,		BillDate,	Total,	(Total - PayRecTotal - I.PaidTotal) AS BalanceTotal,
			Summary,		Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			0 AS Privilege,	PayRecTotal,	I.PaidTotal
	FROM MF_FeeRecBill_His I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 
	
	--应收增加,应收减少，应付增加，应付减少
	SET @ARAPBill += '
	UNION ALL
	SELECT	I.BillTypeID,	BillCode,		BillDate,	Total,	(Total - I.PaidTotal) AS BalanceTotal,
			Summary,		Description,	I.BTypeID,	I.DeptID,	I.ElyID,	PosTime,	CreateTime,		I.BillNo,
			0 AS Privilege,	0 AS PayRecTotal,	I.PaidTotal
	FROM MF_ARAPBill_His I '+ @TableSql +@IndexSql + 'AND IsDraft = 0 AND Red = 0' 
END




SET @Sql = @CreateTableSql+'
;WITH PagingData AS 
(
SELECT	PR.BillTypeID,	PBT.BillName,	PR.BillCode,	BillDate,		Total,		BalanceTotal,	
		CASE WHEN PR.BillTypeID IN (998,999) THEN ''【''+B.BTypeName+''】''+Summary ELSE Summary END AS Summary,		
		Description,	PR.BTypeID,		B.BTypeCode,	B.BTypeName,	PR.DeptID,		D.DeptCode,		
		D.DeptName,		PR.ElyID,		E.ElyCode,		E.ElyName,		CONVERT(varchar(100),PosTime,120) PosTime,		
		CONVERT(varchar(100),CreateTime,120) CreateTime,	BillNo,			Privilege,		PayRecTotal,	PaidTotal
	FROM(
	'+ @QCARBill+'
	UNION ALL
	'+ @QCAPBill+'
	UNION ALL
	'+@PchBill+'
	UNION ALL
	'+ @BuyFreightBill+'
	UNION ALL
	'+ @PchRetBill+'
	UNION ALL
	'+ @SellBill+'
	UNION ALL
	'+ @SaleFreightBill+'
	UNION ALL
	'+ @SellRetBill+'
	UNION ALL
	'+ @FeeRecBill+'
	UNION ALL
	'+ @ARAPBill+'
	) PR
	INNER JOIN BD_Btype B ON PR.BTypeID = B.BTypeID
	LEFT JOIN BD_Employee E ON PR.ElyID = E.ElyID
	LEFT JOIN BD_Dept D ON PR.DeptID = D.DeptID
	INNER JOIN PD_BillType PBT ON PR.BillTypeID = PBT.BillTypeID
	'+ @BillTypeSql
IF @BillStat = 1	SET @Sql += ' WHERE BalanceTotal = 0'
IF @BillStat = 2	SET @Sql += ' WHERE BalanceTotal <> 0'

SET @Sql += ')'

IF @IsSum = 0 --不计算合计
BEGIN
	DECLARE  @TVP AS TVP_Paging_Param
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate','DATE', @BeginDate)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate','DATE', @EndDate)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@QCBillDate','DATE', @QCBillDate)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@QCPosTime','DATETIME', @QCPosTime)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillTypeID','VARCHAR(MAX)',@BillTypeID)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BTypeID','VARCHAR(MAX)',@BTypeID)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID','VARCHAR(MAX)',@DeptID)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ElyID','VARCHAR(MAX)',@ElyID)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillCode','VARCHAR(50)',@BillCode)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Summary','VARCHAR(256)',@Summary)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Description','VARCHAR(100)',@Description)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

	EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, @OrderCol,'','ROWID ASC',1,1
END ELSE
BEGIN
	SET @Sql += ' 
	SELECT SUM(Total) Total, SUM(BalanceTotal) BalanceTotal FROM PagingData
	'
	EXEC sp_executesql @sql,N'@BeginDate DATE,@EndDate DATE,@QCBillDate DATETIME,@QCPosTime DATETIME,@BillTypeID VARCHAR(MAX),@BTypeID VARCHAR(MAX),@DeptID VARCHAR(MAX),@ElyID VARCHAR(MAX),@BillCode VARCHAR(50),@Summary VARCHAR(256),@Description VARCHAR(100), @OperatorID INT',
	@BeginDate,@EndDate,@QCBillDate,@QCPosTime,@BillTypeID,@BTypeID,@DeptID,@ElyID,@BillCode,@Summary,@Description, @OperatorID
END









GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_ARAPBalance]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_ARAPBalance]
GO
/****** Object:  StoredProcedure [UP_MF_ARAPBalance]    Script Date: 07/16/2014 15:31:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/16
-- Description:	 单位明细账本此前应收/付余额
-- =============================================
CREATE PROCEDURE [UP_MF_ARAPBalance](
	 @BTypeID INT = 0,              --往来单位
	 @StartDate DATETIME,   --开始时间
	 @IsHistory BIT = 0  --是否查询历史记录
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @AR INT = 33, --应收款合计
	        @AP INT = 37, --应付款合计
	        @BP INT = 34, --预付账款
	        @BR INT = 38,  --预收账款
	        @HisDate Date	
    DECLARE @TVP_BT AS [TVP_Paging_Param]
	SELECT arap.QcAR - arap.QcAP AS QcAB, arap.QcBR - arap.QcBP AS QcBB FROM BD_ARAP arap WHERE arap.BtypeID = @BTypeID	
    IF @IsHistory = 0
        BEGIN
	   /*开始日期是否大于最后一次月结日期*/	
            SELECT  @HisDate = MAX(EndDate)
            FROM    SS_MonthProc
            WHERE   [State] = 1 
            IF @HisDate IS NOT NULL AND @StartDate >= @HisDate
                SET @IsHistory = 1
        END
	   
	IF @IsHistory = 1
	    WITH ListData AS (SELECT lt.BillTypeID, lt.BillNo, lt.BillDate, lt.FinanceID, lt.BtypeID, lt.JTotal, lt.DTotal FROM PD_ListTable lt
							WHERE lt.BtypeID = @BTypeID AND lt.BillDate < @StartDate
							 AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP)
               UNION ALL (SELECT lt.BillTypeID, lt.BillNo, lt.BillDate, lt.FinanceID, lt.BtypeID, lt.JTotal, lt.DTotal FROM PD_ListTable_His lt
                           WHERE lt.BtypeID = @BTypeID AND lt.BillDate < @StartDate
						    AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP)))
         SELECT (SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.JTotal ELSE 0 END) -  
				 SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.DTotal ELSE 0 END)) AS BeforeAB,
			    (SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.JTotal ELSE 0 END) -  
				 SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.DTotal ELSE 0 END)) AS BeforeBB FROM ListData lt
	ELSE
		SELECT (SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.JTotal ELSE 0 END) -  
				SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.DTotal ELSE 0 END)) AS BeforeAB,
			   (SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.JTotal ELSE 0 END) -  
				SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.DTotal ELSE 0 END)) AS BeforeBB	
			FROM PD_ListTable lt WHERE lt.BtypeID = @BTypeID AND lt.BillDate < @StartDate
			AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP)
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_ARAPDetail]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_ARAPDetail]
GO
/****** Object:  StoredProcedure [UP_MF_ARAPDetail]    Script Date: 07/11/2014 17:45:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/11
-- Description:	 单位明细账本
-- =============================================
CREATE PROCEDURE [UP_MF_ARAPDetail](
     @PageNo INT = 0,
     @PageSize INT = 0,
	 @BTypeID INT = 0,              --往来单位
	 @IsShowRed BIT = 0,            --是否显示红冲单据
	 @StartDate DATETIME,   --开始时间
	 @EndDate DATETIME,      --结束时间
	 @IsHistory BIT = 0  --是否查询历史记录
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @TbSql NVARCHAR(MAX) = '',
	        @RedParam NVARCHAR(50) = '', @_RedParam NVARCHAR(50) = '', 
	        @SqlBeforePage NVARCHAR(MAX) = '', --此页前应收/付余额SQL
	        @DataSQL NVARCHAR(1000) = '',
	        @SellBillType NVARCHAR(3) = '201', --销售出库单单据类型
	        @BuyBillType NVARCHAR(3) = '101', --采购入库单据类型
	        @RedCol NVARCHAR(20) = '', --是否红冲字段
	        @AR INT = 33, --应收款合计
	        @AP INT = 37, --应付款合计
	        @BP INT = 34, --预付账款
	        @BR INT = 38  --预收账款
    DECLARE @TVP_BT AS [TVP_Paging_Param]
    
    IF @IsShowRed = 0
       BEGIN
         SET @RedParam = N' AND lt.Red = 0 ';	
         SET @_RedParam = N' AND Red = 0 ';				 
         INSERT INTO @TVP_BT([ParaName],[DataType],[ParaValue]) 
				SELECT bt.BillTypeID, bt.BillName, bt.BillTable FROM PD_BillType bt WHERE bt.CanPost = 1 AND
					  EXISTS (SELECT 1 FROM PD_ListTable lt WHERE lt.BillTypeID = bt.BillTypeID AND lt.BtypeID = @BTypeID 
							   AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP )
							   AND lt.BillDate BETWEEN @StartDate AND @EndDate AND lt.Red = 0)
       END 
    ELSE
        BEGIN
            SET @RedCol = ' , Red '
			INSERT INTO @TVP_BT([ParaName],[DataType],[ParaValue]) 
				SELECT bt.BillTypeID, bt.BillName, bt.BillTable FROM PD_BillType bt WHERE bt.CanPost = 1 AND
					  EXISTS (SELECT 1 FROM PD_ListTable lt WHERE lt.BillTypeID = bt.BillTypeID AND lt.BtypeID = @BTypeID 
							   AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP )
							   AND lt.BillDate BETWEEN @StartDate AND @EndDate)
	    END
	
	IF @IsHistory = 1
	    BEGIN
	        INSERT INTO @TVP_BT([ParaName],[DataType],[ParaValue])
				SELECT bt.BillTypeID, bt.BillName, bt.BillTable FROM PD_BillType bt WHERE bt.CanPost = 1 AND
					  EXISTS (SELECT 1 FROM PD_ListTable_His lt WHERE lt.BillTypeID = bt.BillTypeID AND lt.BtypeID = @BTypeID 
							   AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP )
							   AND lt.BillDate BETWEEN @StartDate AND @EndDate AND (CASE WHEN @IsShowRed = 0 THEN lt.Red ELSE 0 END) = 0)
				  AND NOT EXISTS (SELECT 1 FROM PD_ListTable lt WHERE lt.BillTypeID = bt.BillTypeID AND lt.BtypeID = @BTypeID 
							   AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP )
							   AND lt.BillDate BETWEEN @StartDate AND @EndDate AND (CASE WHEN @IsShowRed = 0 THEN lt.Red ELSE 0 END) = 0)
			SET @Sql = N' ;WITH ListData AS (SELECT lt.BillTypeID, lt.BillNo, lt.BillDate, lt.FinanceID, lt.BtypeID, lt.JTotal, lt.DTotal FROM PD_ListTable lt
											  WHERE lt.BtypeID = @BTypeID AND lt.BillDate BETWEEN @StartDate AND @EndDate ' + @RedParam + 
											  ' AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP)
								   UNION ALL (SELECT lt.BillTypeID, lt.BillNo, lt.BillDate, lt.FinanceID, lt.BtypeID, lt.JTotal, lt.DTotal FROM PD_ListTable_His lt
											   WHERE lt.BtypeID = @BTypeID AND lt.BillDate BETWEEN @StartDate AND @EndDate ' + @RedParam + 
											  ' AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP)))
						 ,PagingData AS (SELECT SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.JTotal ELSE 0 END) AS AJ, 
												SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.DTotal ELSE 0 END) AS AD,
												SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.JTotal ELSE 0 END) AS BJ,
												SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.DTotal ELSE 0 END) AS BD,
												lt.BillTypeID, lt.BillNo, lt.BillDate FROM ListData lt GROUP BY lt.BillTypeID, lt.BillNo, lt.BillDate)'
	    END
	ELSE
	    SET @Sql = N' ;WITH PagingData AS 
					 (SELECT SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.JTotal ELSE 0 END) AS AJ, 
							 SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.DTotal ELSE 0 END) AS AD,
							 SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.JTotal ELSE 0 END) AS BJ,
							 SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.DTotal ELSE 0 END) AS BD,
							 lt.BillTypeID, lt.BillNo, lt.BillDate FROM PD_ListTable lt
							 WHERE lt.BtypeID = @BTypeID AND lt.BillDate BETWEEN @StartDate AND @EndDate 
							 AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP) '
							 + @RedParam + ' GROUP BY lt.BillTypeID, lt.BillNo, lt.BillDate)'
	   
    
    IF EXISTS(SELECT 1 FROM @TVP_BT WHERE ParaName = @SellBillType OR ParaName = @BuyBillType)
	   SELECT @TbSql += N'UNION ALL SELECT '+ [ParaName] +' AS _BillTypeID,'''+ [DataType] +''' AS BillName, 
	                     BillNo AS _BillNo, BillCode, PosTime, CreateTime, Summary ' + @RedCol + ' FROM
	                     ' + [ParaValue] + N' WHERE IsDraft = 0 AND (BtypeID = @BTypeID OR LogistBTypeID = @BTypeID)
	                     AND BillDate BETWEEN @StartDate AND @EndDate ' + @_RedParam +            
	                     ' UNION ALL SELECT '+ [ParaName] +' AS _BillTypeID,'''+ [DataType] +''' AS BillName, 
	                     BillNo AS _BillNo, BillCode, PosTime, CreateTime, Summary ' + @RedCol + ' FROM
	                     ' + [ParaValue] + N'_His WHERE IsDraft = 0 AND (BtypeID = @BTypeID OR LogistBTypeID = @BTypeID)
	                     AND BillDate BETWEEN @StartDate AND @EndDate ' + @_RedParam + ' '
	   FROM @TVP_BT WHERE ParaName = @SellBillType OR ParaName = @BuyBillType
	   
    IF EXISTS(SELECT 1 FROM @TVP_BT WHERE ParaName <> @SellBillType AND ParaName <> @BuyBillType)
	   SELECT @TbSql += N'UNION ALL SELECT '+ [ParaName] +' AS _BillTypeID,'''+ [DataType] +''' AS BillName, 
	                     BillNo AS _BillNo, BillCode, PosTime, CreateTime, Summary ' + @RedCol + ' FROM
	                     ' + [ParaValue] + N' WHERE IsDraft = 0 AND BtypeID = @BTypeID
	                     AND BillDate BETWEEN @StartDate AND @EndDate ' + @_RedParam +            
	                     ' UNION ALL SELECT '+ [ParaName] +' AS _BillTypeID,'''+ [DataType] +''' AS BillName, 
	                     BillNo AS _BillNo, BillCode, PosTime, CreateTime, Summary ' + @RedCol + ' FROM
	                     ' + [ParaValue] + N'_His WHERE IsDraft = 0 AND BtypeID = @BTypeID
	                     AND BillDate BETWEEN @StartDate AND @EndDate ' + @_RedParam + ' '
	   FROM @TVP_BT WHERE ParaName <> @SellBillType AND ParaName <> @BuyBillType
	
    IF @TbSql <> ''
       BEGIN 
         SET @TbSql = SUBSTRING(@TbSql, 10, LEN(@TbSql)-9);	
         SET @TbSql = ', _DATA_Bill AS (' + @TbSql + ')'
         SET @DataSQL += ' LEFT JOIN _DATA_Bill ON Data.BillTypeID = _DATA_Bill._BillTypeID AND Data.BillNo = _DATA_Bill._BillNo '
       END
	
	IF @PageNo > 1	
	   BEGIN
		SET @SqlBeforePage = @Sql+ N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
									   CROSS JOIN
									   (SELECT ROW_NUMBER() OVER(ORDER BY BillDate) AS ROWID, * FROM PagingData) B
										WHERE B.ROWID > 0 AND B.ROWID <= (@PageNo-1) * @PageSize)
										SELECT SUM(AJ)-SUM(AD) AS BeforePageAB, SUM(BJ)-SUM(BD) AS BeforePageBB FROM DATA'
	    --PRINT @SqlBeforePage
		EXEC sp_executesql @SqlBeforePage,
						   N'@PageNo INT, @PageSize INT, @BTypeID INT, @StartDate VARCHAR(50), @EndDate VARCHAR(50), 
							 @AR INT, @AP INT, @BR INT, @BP INT', 
	                       @PageNo, @PageSize, @BTypeID, @StartDate, @EndDate, @AR, @AP, @BR, @BP
       END  
       
    SET @Sql= N'SET NOCOUNT ON;'
             + @Sql + @TbSql + 
			 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
						 CROSS JOIN
						(SELECT ROW_NUMBER() OVER(ORDER BY BillDate ) AS ROWID,* FROM PagingData ) B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				SELECT * FROM DATA ' + @DataSQL + ' ORDER BY ROWID'  
	--PRINT @Sql
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BTypeID INT, @StartDate VARCHAR(50), @EndDate VARCHAR(50), 
							   @AR INT, @AP INT, @BR INT, @BP INT', 
	                         @PageNo, @PageSize, @BTypeID, @StartDate, @EndDate, @AR, @AP, @BR, @BP
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_ARAPDetailSum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_ARAPDetailSum]
GO
/****** Object:  StoredProcedure [UP_MF_ARAPDetailSum]    Script Date: 07/18/2014 14:25:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/18
-- Description:	 单位明细账本合计
-- =============================================
CREATE PROCEDURE [UP_MF_ARAPDetailSum](
	 @BTypeID INT = 0,              --往来单位
	 @IsShowRed BIT = 0,            --是否显示红冲单据
	 @StartDate DATETIME,   --开始时间
	 @EndDate DATETIME,      --结束时间
	 @IsHistory BIT = 0  --是否查询历史记录
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @RedParam NVARCHAR(50) = '',
	        @AR INT = 33, --应收款合计
	        @AP INT = 37, --应付款合计
	        @BP INT = 34, --预付账款
	        @BR INT = 38  --预收账款   
    IF @IsShowRed = 0
         SET @RedParam = N' AND lt.Red = 0 ';		
	
	IF @IsHistory = 1
		SET @Sql = N' ;WITH ListData AS (SELECT lt.BillTypeID, lt.BillNo, lt.BillDate, lt.FinanceID, lt.BtypeID, lt.JTotal, lt.DTotal FROM PD_ListTable lt
										  WHERE lt.BtypeID = @BTypeID AND lt.BillDate BETWEEN @StartDate AND @EndDate ' + @RedParam + 
										  ' AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP)
		                       UNION ALL (SELECT lt.BillTypeID, lt.BillNo, lt.BillDate, lt.FinanceID, lt.BtypeID, lt.JTotal, lt.DTotal FROM PD_ListTable_His lt
		                                   WHERE lt.BtypeID = @BTypeID AND lt.BillDate BETWEEN @StartDate AND @EndDate ' + @RedParam + 
										  ' AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP)))
					  SELECT SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.JTotal ELSE 0 END) AS AJ, 
							 SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.DTotal ELSE 0 END) AS AD,
							 SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.JTotal ELSE 0 END) AS BJ,
							 SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.DTotal ELSE 0 END) AS BD FROM ListData lt'
	ELSE	
		SET @Sql = N' SELECT SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.JTotal ELSE 0 END) AS AJ, 
						     SUM(CASE WHEN lt.FinanceID = @AR OR lt.FinanceID = @AP THEN lt.DTotal ELSE 0 END) AS AD,
							 SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.JTotal ELSE 0 END) AS BJ,
							 SUM(CASE WHEN lt.FinanceID = @BR OR lt.FinanceID = @BP THEN lt.DTotal ELSE 0 END) AS BD
							 FROM PD_ListTable lt
							 WHERE lt.BtypeID = @BTypeID AND lt.BillDate BETWEEN @StartDate AND @EndDate 
							 AND (lt.FinanceID = @AR OR lt.FinanceID = @AP OR lt.FinanceID = @BR OR lt.FinanceID = @BP) '
							 + @RedParam
	EXEC sp_executesql @Sql,
					   N'@AR INT,@AP INT,@BR INT,@BP INT,@BTypeID INT,@StartDate VARCHAR(50),@EndDate VARCHAR(50)',
						 @AR,@AP,@BR,@BP,@BTypeID,@StartDate,@EndDate 
END
GO




if exists (select * from sysobjects where id = object_id(N'[UP_MF_ArAPLoadBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_MF_ArAPLoadBill]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		王伟
-- Create date:  2014/6/16
-- Description:	 应收，应付增加，减少调单
-- =============================================
CREATE PROCEDURE [UP_MF_ArAPLoadBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM MF_ARAPBill_His WHERE BillNo=@BillNo )
BEGIN 
	SELECT  bill.[BillNo]
		   ,bill.[BillTypeID] as BillType
		   ,bill.[BillCode]
		   ,bill.[BillDate]
		   ,bill.[BTypeID]
		   ,bill.[DeptID]
		   ,bill.[ElyID]
		   ,bill.[PaidTotal]
		   ,bill.[Total]
		   ,bill.[Creator]
		   ,bill.[CreateTime]
		   ,bill.[PosElyID]
		   ,bill.[PosTime]
		   ,bill.[Summary]
		   ,bill.[Description]
		   ,bill.[IsDraft]
		   ,b.BTypeName
		   ,d.DeptName
		   ,e.ElyName
		   ,ec.ElyName as CreatorName
		   ,ep.ElyName as PosName --过账人
		   ,bill.red as Red
		   ,bill.AuditStatus
	FROM MF_ARAPBill_His bill
		 LEFT JOIN BD_Btype b ON bill.BtypeID=b.BTypeID
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 left JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
	WHERE bill.BillNo = @BillNo;  --查询主表
     
     SELECT		detail.[DID]
			  ,detail.[BillTypeID]
			  ,detail.[BillNo]
			  ,detail.[FinanceID]
			  ,detail.[Total]
			  ,detail.[Remark]
			  ,f.FinanceNO
			  ,f.FinanceName
	 FROM MF_ARAPDetail_His detail
		  INNER JOIN BD_Finance f ON detail.FinanceID=f.FinanceID	
      WHERE detail.BillNo = @BillNo;  --查询明细             


END 
ELSE 
BEGIN 		
		SELECT  bill.[BillNo]
			   ,bill.[BillTypeID] as BillType
			   ,bill.[BillCode]
			   ,bill.[BillDate]
			   ,bill.[BTypeID]
			   ,bill.[DeptID]
			   ,bill.[ElyID]
			   ,bill.[PaidTotal]
			   ,bill.[Total]
			   ,bill.[Creator]
			   ,bill.[CreateTime]
			   ,bill.[PosElyID]
			   ,bill.[PosTime]
			   ,bill.[Summary]
			   ,bill.[Description]
			   ,bill.[IsDraft]
			   ,b.BTypeName
			   ,d.DeptName
			   ,e.ElyName
			   ,ec.ElyName as CreatorName
			   ,ep.ElyName as PosName --过账人
			   ,bill.red as Red
		   ,bill.AuditStatus
		FROM MF_ARAPBill bill
			 LEFT JOIN BD_Btype b ON bill.BtypeID=b.BTypeID
			 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
			 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
			 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
			 left JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		WHERE bill.BillNo = @BillNo;  --查询主表
	     
		 SELECT		detail.[DID]
				  ,detail.[BillTypeID]
				  ,detail.[BillNo]
				  ,detail.[FinanceID]
				  ,detail.[Total]
				  ,detail.[Remark]
				  ,f.FinanceNO
				  ,f.FinanceName
		 FROM MF_ARAPDetail detail
			  INNER JOIN BD_Finance f ON detail.FinanceID=f.FinanceID	
		  WHERE detail.BillNo = @BillNo;  --查询明细             

END



                                  
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_ARAPSummary]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_ARAPSummary]
GO
/****** Object:  StoredProcedure [UP_MF_ARAPSummary]    Script Date: 07/11/2014 09:53:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/11
-- Description:	 单位应收应付
-- =============================================
CREATE PROCEDURE [UP_MF_ARAPSummary](
     @PageNo INT = 0,
     @PageSize INT = 0,
	 @BTypeID VARCHAR(MAX) = '',         --往来单位
	 @AreaID VARCHAR(MAX) = '',          --地区
	 @SumParam INT = 0,                   --汇总条件
	 @SumLevel INT = 0,                   --汇总等级
	 @OrderStr VARCHAR(50) = '',          --排序字符串
	 @OperatorID INT = 0,                 --操作员ID 
	 @SumOrNot BIT = 0					  --是否计算合计	
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SqlGroup NVARCHAR(MAX) = '', 	
	        @HeadSql NVARCHAR(MAX), @Sql NVARCHAR(MAX),
	        @PageDataName NVARCHAR(20) = N'PagingData', 
	        @BtypeLimit INT = 0,
	        @BaseCols NVARCHAR(2000) = N''
    DECLARE @TVP_Area AS [TVP_Type]
	SET @HeadSql = ' ;WITH PagingData AS 
	             (SELECT (CASE WHEN (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)) > 0) 
	                           THEN (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)))
	                           ELSE 0 END) AS ARBalance, 
	                     (CASE WHEN (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)) < 0) 
	                           THEN ABS(SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)))
	                           ELSE 0 END) AS APBalance, 
	                     (CASE WHEN (SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)) > 0) 
	                           THEN (SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)))
	                           ELSE 0 END) AS BRBalance, 
	                     (CASE WHEN (SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)) < 0) 
	                           THEN ABS(SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)))
	                           ELSE 0 END) AS BPBalance,  
	                     (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0))
	                    - SUM(ISNULL(arap.QmBR,0)) + SUM(ISNULL(arap.QmBP,0))) AS Balance '
	SET @Sql = ' FROM BD_Btype btype LEFT JOIN BD_ARAP arap ON btype.BTypeID = arap.BTypeID'
	   
	--往来单位权限                    
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)
	                    
    IF @BtypeLimit = 1  --部份权限
	   SET @Sql +=' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID = btype.BTypeID '
	        
    IF @BTypeID <> ''
	    SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _BType ON _BType.typeid = btype.BTypeID '
	   
	IF @AreaID <> ''
      BEGIN
	    SET @Sql +=' INNER JOIN @TVP_Area _area ON _area.ChildTypeID = btype.AreaID '
        INSERT INTO @TVP_Area([TypeID],[ChildTypeID]) 
	    SELECT a.AreaID, ca.AreaID FROM BD_Area a 
	         INNER JOIN BD_Area ca ON ca.[Path] Like a.[Path] + '%'
		     WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@AreaID, ',') _Area WHERE _Area.typeid = a.AreaID)
	  END
	   
	IF @SumParam = 1
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0 
            BEGIN
	          SET @HeadSql += ', parBtypeType.BaseID AS BtypeTypeID'
	          SET @Sql += ' INNER JOIN dbo.UF_BD_BaseSummary(''BTYPE'', @SumLevel) parBtypeType ON parBtypeType.ParID = btype.BtypeTypeID '
			  SET @SqlGroup += ', parBtypeType.BaseID '
			  SET @BaseCols += ', Data.BtypeTypeCode AS Code, Data.BtypeTypeName AS Name '
	        END
	     ELSE IF @SumLevel = 6
            BEGIN
			  SET @HeadSql += ', btype.BTypeID, btype.BTypeCode, btype.BTypeName '
			  SET @SqlGroup += ', btype.BTypeID, btype.BTypeCode, btype.BTypeName '
			  SET @BaseCols += ', Data.BTypeCode AS Code, Data.BTypeName AS Name '
	        END
	   END
	   
	ELSE IF @SumParam = 2
	   BEGIN
         IF @SumLevel <> 0
            BEGIN
	          SET @HeadSql += ', parArea.BaseID AS AreaID '
			  SET @Sql += ' INNER JOIN dbo.UF_BD_BaseSummary(''AREA'', @SumLevel) parArea ON parArea.ParID = btype.AreaID   '
			  SET @SqlGroup += ', parArea.BaseID '
			  SET @BaseCols += ', Data.AreaNO AS Code, Data.AreaName AS Name '
	        END
	   END
	   
	SET @Sql = @HeadSql + @Sql + ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1) + ' )'
	   
	IF (@SumParam = 1 AND @SumLevel <> 6) OR @SumParam = 2
	    BEGIN
		    SET @Sql += N', MainData AS (SELECT PagingData.* ' 
		    IF @SumParam = 1 AND @SumLevel <> 6
				SET @Sql += N',b.TypeCode AS BtypeTypeCode, b.TypeName AS BtypeTypeName' 
		    IF @SumParam = 2 
				SET @Sql += N',a.AreaNO, a.AreaName'
			SET @Sql += N' FROM PagingData '
		    IF @SumParam = 1 AND @SumLevel <> 6
				SET @Sql += N' INNER JOIN BD_Btype_Type b on b.BtypeTypeID = PagingData.BtypeTypeID '
		    IF @SumParam = 2 
				SET @Sql += N' INNER JOIN BD_Area a on a.AreaID = PagingData.AreaID '
		    SET @Sql += N')'
			SET @PageDataName = N' MainData '	       
	    END 
	IF @SumOrNot = 0
	BEGIN
		SET @Sql=N'SET NOCOUNT ON;'
             + @Sql + 
			 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM ' + @PageDataName + ') A 
						 CROSS JOIN
						(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM ' + @PageDataName + ') B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				SELECT * ' + @BaseCols + ' FROM DATA ORDER BY ROWID'
				
		IF @BtypeLimit = 0
			SET @Sql = N' SELECT * FROM BD_ARAP WHERE 1 <> 1'
	END ELSE
	BEGIN
		SET @Sql = N'SET NOCOUNT ON;'
             + @Sql + 
			 N' SELECT	SUM(ARBalance) AS ARBalance, 
						SUM(APBalance) AS APBalance,
						SUM(BRBalance) AS BRBalance,
						SUM(BPBalance) AS BPBalance,
						SUM(Balance) AS Balance
				FROM '+ @PageDataName
				
		IF @BtypeLimit = 0
			SET @Sql = ' SELECT 0 AS ARBalance,
								0 AS APBalance,
								0 AS BRBalance,
								0 AS BPBalance,
								0 AS Balance'
	END
     
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BTypeID VARCHAR(MAX), @AreaID VARCHAR(max), @SumLevel INT, 
	                           @TVP_Area TVP_Type READONLY, @OperatorID INT ', 
	                         @PageNo, @PageSize, @BTypeID, @AreaID, @SumLevel, @TVP_Area, @OperatorID
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_ARCQQuery]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_ARCQQuery]
GO
/****** Object:  StoredProcedure [UP_MF_ARCQQuery]    Script Date: 03/18/2015 09:53:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		leiyang
-- Create date:  2015/3/18
-- Description:	 超期应付查询
-- update:增加UF_OT_GetLastDate参数；替换SettlementDate字段由LastDate为CheckDate
-- =============================================
CREATE PROCEDURE [UP_MF_ARCQQuery](
     @PageNo INT = 0,
     @PageSize INT = 0,
	 @BTypeID VARCHAR(1000) = '',         --往来单位
	 @AreaID VARCHAR(1000) = '',          --地区
	 @PaidCircle Int = 0,				  --结算周期
	 @OrderStr VARCHAR(50) = '',          --排序字符串
	 @ShowARPNUM Int = 0,
	 @SumOrNot INT = 0,					  --是否为合计形式
	 @OperatorID INT = 0                  --操作员ID 
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE 
	        @Sql NVARCHAR(MAX)='',@ShowARPNumSql varchar(max)='',
	        @BtypeLimit INT = 0,@InnerSql varchar(Max) = '',@CondiTionSql varchar(Max)=''
    DECLARE @TVP_Area AS [TVP_Type]
    
    --往来单位权限                    
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)
	                    
    IF @BtypeLimit = 1  --部份权限
	   SET @InnerSql +=' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID = btype.BTypeID '
	        
    IF @BTypeID <> ''
	    SET @InnerSql +=' INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _BType ON _BType.typeid = btype.BTypeID '
	   
	IF @AreaID <> ''
      BEGIN
	    SET @InnerSql +=' INNER JOIN @TVP_Area _area ON _area.ChildTypeID = btype.AreaID '
        INSERT INTO @TVP_Area([TypeID],[ChildTypeID]) 
	    SELECT a.AreaID, ca.AreaID FROM BD_Area a 
	         INNER JOIN BD_Area ca ON ca.[Path] Like a.[Path] + '%'
		     WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@AreaID, ',') _Area WHERE _Area.typeid = a.AreaID)
	  END
	if(@PaidCircle <> 0)
		Select @CondiTionSql += ' AND PaidCircle = ' + cast((@PaidCircle -1) as varchar(2))	
    if(@ShowARPNum = 1)
		Select @ShowARPNumSql = ' where (((PaidCircle = 0 or PaidCircle = 1) and Balance> 0) or CQARBalance>0)'
	SET @Sql = ' ;with BtypeDate as (select btype.BTypeID,PaidCircle,
			case when PaidCircle =0 or PaidCircle = 1 then ''''
				else dbo.UF_OT_GetLastDate(PaidCircle,StatementPeriod,PaidDeadline) 
				end as CheckDate,
			case when PaidCircle =0 or PaidCircle = 1 then '''' 
				else Convert(nvarchar(10),DATEADD(D,StatementPeriod, dbo.UF_OT_GetLastDate(PaidCircle,StatementPeriod,PaidDeadline)),120) 
				end as LastDate
			from BD_Btype btype '+@InnerSql+' where 1=1 '+@CondiTionSql+'),
			SaleData as (
				select b.BTypeID,(Total-Privilege-PayRecTotal-PaidTotal) as CQARBalance 
					from PD_SellBill a inner join BtypeDate b on a.BTypeID = b.BTypeID and a.BillDate <= b.CheckDate
				 where IsDraft = 0 and StlTag <> 2 and Red = 0 and b.CheckDate <> ''''
				 Union All
				 select b.BTypeID,(Total-Privilege-PayRecTotal-PaidTotal)*-1 as CQARBalance 
					from PD_SellRetBill a inner join BtypeDate b on a.BTypeID = b.BTypeID and a.BillDate <= b.CheckDate
				 where IsDraft = 0 and StlTag <> 2 and Red = 0 and b.CheckDate <> ''''
			),SaleSumData as(
				select BTypeID,SUM(CQARBalance) as CQARBalance from SaleData group by BTypeID
			),PData AS 
         (SELECT Btype.BTypeID,BTypeName,BTypeCode,(CASE WHEN (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)) > 0) 
                   THEN (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)))
                   ELSE 0 END) AS ARBalance, 
             (CASE WHEN (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)) < 0) 
                   THEN ABS(SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0)))
                   ELSE 0 END) AS APBalance, 
             (CASE WHEN (SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)) > 0) 
                   THEN (SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)))
                   ELSE 0 END) AS BRBalance, 
             (CASE WHEN (SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)) < 0) 
                   THEN ABS(SUM(ISNULL(arap.QmBR,0)) - SUM(ISNULL(arap.QmBP,0)))
                   ELSE 0 END) AS BPBalance,  
             (SUM(ISNULL(arap.QmAR,0)) - SUM(ISNULL(arap.QmAP,0))
            - SUM(ISNULL(arap.QmBR,0)) + SUM(ISNULL(arap.QmBP,0))) AS Balance 
             FROM BD_Btype btype LEFT JOIN BD_ARAP arap ON btype.BTypeID = arap.BTypeID 
             '+@InnerSql+'
             Where 1=1 '+@CondiTionSql+'
             group by BTypeName,BTypeCode,Btype.BTypeID ),PagingData as (
	            Select BTypeName,BTypeCode,ARBalance,APBalance,BRBalance,BPBalance,Balance,
	            case when PaidCircle = 0 or PaidCircle = 1 then Balance else isnull(s.CQARBalance,0) End as CQARBalance,LastDate as SettlementDate,CheckDate AS CheckDate
	             from PData P Inner join BtypeDate BD on P.BTypeID = BD.BTypeID Left Join SaleSumData S on P.BTypeID = S.BTypeID '+@ShowARPNumSql+'	            
	            )'	    
	IF @SumOrNot = 0       
	BEGIN
		SET @Sql=N'SET NOCOUNT ON;'
				 + @Sql + 
				 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
							 CROSS JOIN
							(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM PagingData) B
							  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
					SELECT * FROM DATA ORDER BY ROWID'		
	END
	IF @SumOrNot = 1
	BEGIN
		SET @Sql=N'SET NOCOUNT ON;'
				 + @Sql + 
				 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
							 CROSS JOIN
							(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM PagingData) B
							  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
					SELECT SUM(ARBalance)[ARBalance],SUM(APBalance)[APBalance],SUM(BRBalance)[BRBalance],
						   SUM(BPBalance)[BPBalance],SUM(Balance)[Balance],SUM(CQARBalance)[CQARBalance] FROM DATA '	
	END
	IF @BtypeLimit = 0
		SET @Sql = N' SELECT * FROM BD_ARAP WHERE 1 <> 1'
		print @Sql
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BTypeID VARCHAR(1000), @AreaID VARCHAR(1000), 
	                           @TVP_Area TVP_Type READONLY,@SumOrNot INT, @OperatorID INT ', 
	                         @PageNo, @PageSize, @BTypeID, @AreaID, @TVP_Area,@SumOrNot, @OperatorID
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_BuyInvoiceM]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_MF_BuyInvoiceM
GO
/****** Object:  StoredProcedure [UP_MF_BuyInvoiceM]    Script Date: 02/12/2015 11:07:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/2/12
-- Description:	 采购发票管理
-- =============================================
CREATE PROCEDURE [UP_MF_BuyInvoiceM](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @InvoiceStartDate DATETIME,                    --开始日期
	 @InvoiceEndDate DATETIME,                    --结束日期
	 @BTypeID VARCHAR(1000) = '',            --往来单位
     @InvoiceBillCodeMatch INT = 0,   --发票单据编号匹配方式
     @InvoiceBillCode VARCHAR(50) = '', --发票单据编号
	 @ElyID VARCHAR(1000) = '',            --经手人
	 @InvoiceMode INT = 0,            --开票方式
     @InvoiceCodeMatch INT = 0,   --发票号匹配方式
	 @InvoiceCode VARCHAR(100) = '',            --发票号
	 @InvoiceType INT = 0,            --发票类型
	 @CheckStt INT = 0,            --审核状态
	 @BillStartDate DATETIME = NULL,                    --单据开始日期
	 @BillEndDate DATETIME = NULL,                    --单据结束日期
	 @BillType INT = 0,            --单据类型
     @BillCodeMatch INT = 0,   --单据编号匹配方式
	 @BillCode VARCHAR(100) = '',         --单据编号
	 @OrderStr VARCHAR(50) = '',         --排序字符串
	 @OperatorID INT = 0,                  --操作员ID   
	 @IsHistory BIT = 0,   --是否查询历史记录  
	 --------------------跳转报表的参数-----------------------
	 @BillNo INT = 0,                  --单据ID   
	 @InBTypeID INT = 0    --往来单位 
   ) 
AS
BEGIN
	SET NOCOUNT ON;		
	DECLARE @Re INT 
	EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @InvoiceStartDate, @isHistory = @IsHistory
	IF @Re = 1 RETURN @Re;
	
	EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @BillStartDate, @isHistory = @IsHistory
	IF @Re = 1 RETURN @Re;
	
	DECLARE @Sql NVARCHAR(MAX) = '', @HeadSql NVARCHAR(MAX) = '',
		    @SqlParam NVARCHAR(1000) = N' WHERE 1 = 1 ',
		    @SttParam NVARCHAR(1000) = N'',
	        @SumSql NVARCHAR(MAX) = N'', 
	        @DataSql NVARCHAR(2000) = N'', 
	        @BaseSql NVARCHAR(2000) = N'',
	        @BillSql NVARCHAR(4000) = N'',
	        @BillParam NVARCHAR(2000) = N' WHERE 1 = 1 ',
	        @BtypeLimit INT = 0,
	        @BuyBill INT = 101,
	        @BuyBackBill INT = 102
    DECLARE @TVP_Dept AS [TVP_Type]
    IF @InvoiceStartDate IS NOT NULL AND @InvoiceEndDate IS NOT NULL
		SET @SqlParam += ' AND bill.BillDate BETWEEN @InvoiceStartDate AND @InvoiceEndDate '
	SET @SumSql = N' PagingData AS (SELECT DISTINCT bill.BillNo, bill.InvoiceTotal FROM  MF_PchInvoiceBill bill '	
	SET @HeadSql = N' PagingData AS (SELECT DISTINCT  bill.BillNo, bill.BillCode, bill.BTypeID, bill.DeptID, bill.ElyID, bill.BillDate
											   , bill.CreateTime, bill.Creator AS CreatorID, bill.Summary, bill.[Description], bill.IsDraft
											   , bill.InvoiceTotal, bill.InvoiceType, bill.InvoiceMode, bill.InvoiceCode, 0 as IsHistory	   
										 FROM  MF_PchInvoiceBill bill '	   
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)   
	                 
    IF @BtypeLimit = 1  --部份权限
	   BEGIN
			IF OBJECT_ID('tempdb..#BuyIMBtypeLimit', 'U') IS NOT NULL
				DROP TABLE #BuyIMBtypeLimit
			SELECT * INTO #BuyIMBtypeLimit FROM dbo.UF_BD_BtypeLimit(@OperatorID)
			SET @Sql +=' INNER JOIN #BuyIMBtypeLimit rBtype ON rBtype.BTypeID = bill.BTypeID '
	   END
       
    IF @BTypeID <> ''     --往来单位
	   BEGIN
			IF OBJECT_ID('tempdb..#BuyIMBtypeList', 'U') IS NOT NULL
				DROP TABLE #BuyIMBtypeList
			SELECT * INTO #BuyIMBtypeList FROM dbo.UF_OT_Split_Int(@BTypeID, ',')
			SET @Sql +=' INNER JOIN #BuyIMBtypeList _btype ON _btype.typeid = bill.BTypeID '
	   END
       
    IF @InBTypeID <> 0     --往来单位
	   SET @SqlParam += N' AND bill.BTypeID = @InBTypeID ' 
    							
	IF @InvoiceBillCode <> ''   --单据编号
	   BEGIN 
		   IF @InvoiceBillCodeMatch = 0
			   SET @SqlParam += N' AND bill.BillCode LIKE ''%'' + @InvoiceBillCode +''%'''
		   ELSE IF @InvoiceBillCodeMatch = 1
			   SET @SqlParam += N' AND bill.BillCode = @InvoiceBillCode ' 
	   END
	   
    IF @ElyID <> ''     --经手人
	   BEGIN
			IF OBJECT_ID('tempdb..#BuyIMElyList', 'U') IS NOT NULL
				DROP TABLE #BuyIMElyList
			SELECT * INTO #BuyIMElyList FROM dbo.UF_OT_Split_Int(@ElyID, ',')
			SET @Sql +=' INNER JOIN #BuyIMElyList _Emp ON _Emp.typeid = bill.ElyID '
	   END
	   
	IF @InvoiceMode <> 9999  --开票方式 
	    SET @SqlParam += ' AND bill.InvoiceMode = @InvoiceMode '
	     							
	IF @InvoiceCode <> ''   --发票号
	   BEGIN 
		   IF @InvoiceCodeMatch = 0
			   SET @SqlParam += N' AND bill.InvoiceCode LIKE ''%'' + @InvoiceCode +''%'''
		   ELSE IF @InvoiceCodeMatch = 1
			   SET @SqlParam += N' AND bill.InvoiceCode = @InvoiceCode ' 
	   END
	   
	IF @InvoiceType <> 9999  --发票类型
	    SET @SqlParam += ' AND bill.InvoiceType = @InvoiceType '
	   
	IF @CheckStt <> 9999  --审核状态
	    SET @SqlParam += ' AND bill.IsDraft = @CheckStt '
	    
	IF @BillNo <> 0 OR @InBTypeID <> 0 --报表跳转只查已审核的
	    SET @SqlParam += ' AND bill.IsDraft = 0 '
	    
	IF (@InvoiceMode <> 9999 AND @InvoiceMode <> 3) OR @BillNo <> 0 OR @BillType <> 9999 OR @BillCode <> '' OR (@BillStartDate IS NOT NULL AND @BillEndDate IS NOT NULL) --开票方式不为手工开票时或单据类型有选择时关联单据
	    BEGIN
			IF @BillStartDate IS NOT NULL AND @BillEndDate IS NOT NULL
				SET @BillParam += ' AND BillDate BETWEEN  @BillStartDate AND @BillEndDate '	     							
			IF @BillCode <> ''   --单据编号
			   BEGIN 
				   IF @BillCodeMatch = 0
					   SET @BillParam += N' AND BillCode LIKE ''%'' + @BillCode +''%'''
				   ELSE IF @BillCodeMatch = 1
					   SET @BillParam += N' AND BillCode = @BillCode ' 
			   END
			IF @BillNo <> 0
				SET @BillParam += N' AND BillNo = @BillNo ' 
			IF @BillType = 9999 OR @BillType = 101
				BEGIN
					SET @BillSql += ';WITH BillData AS (SELECT BillNo, @BuyBill AS BillType FROM PD_PchBill ' + @BillParam +
									' UNION ALL (SELECT BillNo, @BuyBill AS BillType FROM PD_PchBill_His ' + @BillParam + ' ) '
					IF @BillType = 9999
						SET @BillSql += '  UNION ALL (SELECT BillNo, @BuyBackBill AS BillType FROM PD_PchRetBill ' + @BillParam + ' )
										   UNION ALL (SELECT BillNo, @BuyBackBill AS BillType FROM PD_PchRetBill_His ' + @BillParam + ' ) '
					SET @BillSql += ' ) '
				END
			ELSE
				SET @BillSql += ';WITH BillData AS (SELECT BillNo, @BuyBackBill AS BillType FROM PD_PchRetBill ' + @BillParam + '
								   UNION ALL (SELECT BillNo, @BuyBackBill AS BillType FROM PD_PchRetBill_His ' + @BillParam + ' )) '
			IF @BillNo <> 0 OR @BillType <> 9999 OR @BillCode <> '' OR (@BillStartDate IS NOT NULL AND @BillEndDate IS NOT NULL)
				BEGIN
					IF @InBTypeID <> 0
						BEGIN
							SET @SqlParam +='  AND ((bill.InvoiceMode <> 3 AND EXISTS (SELECT 1 FROM MF_PchInvoiceDetail detail 
												INNER JOIN BillData bData ON bData.BillNo = detail.PchBillNo
												AND detail.BillType = bData.BillType AND detail.BillNo = bill.BillNo ))
												  OR (bill.InvoiceMode = 3 AND bill.BillDate BETWEEN @BillStartDate AND @BillEndDate ))'
						END
					ELSE
						BEGIN
							SET @Sql +=' INNER JOIN MF_PchInvoiceDetail detail ON detail.BillNo = bill.BillNo
										 INNER JOIN BillData bData ON bData.BillNo = detail.PchBillNo AND detail.BillType = bData.BillType '
							SET @SqlParam +=' AND bill.InvoiceMode <> 3 '
						END
				END
			SET @HeadSql = @BillSql + ',' + @HeadSql
			SET @SumSql = @BillSql + ',' + @SumSql
	    END
	ELSE
		BEGIN
			SET @HeadSql = ';WITH ' + @HeadSql
			SET @SumSql =  ';WITH' + @SumSql
		END
       
    SET @BaseSql += N', _DATA_Btype AS (SELECT BTypeID AS BID, BTypeCode, BTypeName FROM BD_Btype)
					  , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName FROM BD_Dept)
					  , _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName FROM BD_Employee)
					  , _DATA_Creator AS (SELECT ElyID AS CID, ElyCode AS CreatorCode, ElyName AS Creator FROM BD_Employee)'  
                   
    SET @DataSql += N' LEFT JOIN _DATA_Btype ON Data.BTypeID = _DATA_Btype.BID
					   LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID
					   LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID 
					   LEFT JOIN _DATA_Creator ON Data.CreatorID = _DATA_Creator.CID '
	SET @HeadSql = @HeadSql + @Sql + @SqlParam
	SET @SumSql = @SumSql + @Sql + @SqlParam
	IF @IsHistory = 1
		BEGIN
			SET  @SumSql = @SumSql + ' UNION ALL (SELECT DISTINCT bill.BillNo, bill.InvoiceTotal FROM  MF_PchInvoiceBill_His bill '+ REPLACE(@Sql,'MF_PchInvoiceDetail','MF_PchInvoiceDetail_His') 
									+ REPLACE(@SqlParam,'MF_PchInvoiceDetail','MF_PchInvoiceDetail_His') + ' ) '
			SET  @Sql = @HeadSql +  ' UNION ALL (SELECT DISTINCT bill.BillNo, bill.BillCode, bill.BTypeID, bill.DeptID, bill.ElyID, bill.BillDate
											   , bill.CreateTime, bill.Creator AS CreatorID, bill.Summary, bill.[Description], bill.IsDraft
											   , bill.InvoiceTotal, bill.InvoiceType, bill.InvoiceMode, bill.InvoiceCode, 1 as IsHistory	   
										 FROM  MF_PchInvoiceBill_His bill '+ REPLACE(@Sql,'MF_PchInvoiceDetail','MF_PchInvoiceDetail_His') + REPLACE(@SqlParam,'MF_PchInvoiceDetail','MF_PchInvoiceDetail_His') + ' ) '
		END								 
    ELSE
       SET @Sql = @HeadSql    
    SET @Sql = N'SET NOCOUNT ON;'
               + @Sql + ')' + @BaseSql + 
			   N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
						    CROSS JOIN
						   (SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM PagingData ) B
						    WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				   SELECT *, (CASE IsDraft WHEN 0 THEN ''已审核'' ELSE ''未审核'' END) AS SttName FROM DATA ' + @DataSql + ' ORDER BY ROWID'	
				   
    SET @SumSql = N'SET NOCOUNT ON;'
               + @SumSql + ') 
			    SELECT SUM(PagingData.InvoiceTotal) AS TotalSum FROM PagingData '		
				   
	IF @BtypeLimit = 0
		BEGIN
			SET @Sql = N' SELECT * FROM MF_PchInvoiceBill WHERE 1 <> 1'
			SET @SumSql = N' SELECT 1 FROM MF_PchInvoiceBill WHERE 1 <> 1'
		END
			
	--print @Sql	
	EXEC sp_executesql @Sql,  N'@PageNo INT, @PageSize INT, @InvoiceStartDate DATETIME, @InvoiceEndDate DATETIME, @InvoiceBillCode VARCHAR(50), 
								@InvoiceMode INT, @InvoiceCode VARCHAR(100), @InvoiceType INT, @BillStartDate DATETIME, @BillEndDate DATETIME,
								@BillCode VARCHAR(100), @InBTypeID INT, @BillNo INT, @BuyBill INT, @BuyBackBill INT, @CheckStt INT ',
								@PageNo, @PageSize, @InvoiceStartDate, @InvoiceEndDate, @InvoiceBillCode, @InvoiceMode, @InvoiceCode, @InvoiceType, 
								@BillStartDate, @BillEndDate, @BillCode, @InBTypeID, @BillNo, @BuyBill, @BuyBackBill, @CheckStt
	
			
	--print @SumSql								
	EXEC sp_executesql @SumSql,  N'@InvoiceStartDate DATETIME, @InvoiceEndDate DATETIME, @InvoiceBillCode VARCHAR(50), 
								@InvoiceMode INT, @InvoiceCode VARCHAR(100), @InvoiceType INT, @BillStartDate DATETIME, @BillEndDate DATETIME,
								@BillCode VARCHAR(100), @InBTypeID INT, @BillNo INT, @BuyBill INT, @BuyBackBill INT, @CheckStt INT ',
								@InvoiceStartDate, @InvoiceEndDate, @InvoiceBillCode, @InvoiceMode, @InvoiceCode, @InvoiceType, 
								@BillStartDate, @BillEndDate, @BillCode, @InBTypeID, @BillNo, @BuyBill, @BuyBackBill, @CheckStt
							 
END
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-7-31
	描述：现金银行查询
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_CashBankQuery]
(
	@Period INT=-1,
	@UserID int=1
)

AS
SET NOCOUNT ON

DECLARE @StartDate DATE,@Sql NVARCHAR(max)
IF  EXISTS(SELECT 1 FROM SS_MonthProc WHERE Name='本期' AND Period=@Period)
	SET @Period=-1
IF @Period=-1 
BEGIN
	SELECT @StartDate= StartDate FROM SS_MonthProc WHERE Name='本期'
	SET @Sql='
		if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
		SELECT	fc.FinanceID,
			ParID,
			Path,
			SUM(b.Total)Total,
			SUM(b.BQTotal) BQTotal
		INTO #ExpenditureData
		FROM BD_Finance fc
		INNER JOIN
		(
			SELECT FinanceID,SUM(JTotal-DTotal) AS BQTotal,0 AS Total  FROM PD_ListTable WHERE  BillDate>=@StartDate	AND Red=0 GROUP BY FinanceID
			UNION ALL
			SELECT FinanceID,0 AS BQTotal,QmBalances AS Total  FROM BD_Funds
		)b ON fc.FinanceID = b.FinanceID
		WHERE Path LIKE ''00001%'' AND lvl>1 AND SonNum=0 
		GROUP BY fc.FinanceID,ParID,Path'
END
Else if(@Period= 99999)
Begin
	Set @sql='
	;WITH FinanceData AS
	(
		SELECT	fc.FinanceID,
				ParID,
				Path,
				0 as Total,
				QcBalances as BQTotal
		FROM BD_Finance fc
		INNER JOIN BD_Funds b ON fc.FinanceID = b.FinanceID
		WHERE Path LIKE ''00001%'' AND lvl>1 AND SonNum=0 
	)
	'
ENd
ELSE 
	SET @sql='
	;WITH FinanceData AS
	(
		SELECT	fc.FinanceID,
				ParID,
				Path,
				b.Total,
				b.BQTotal
		FROM BD_Finance fc
		INNER JOIN SS_MonthBalance b ON fc.FinanceID = b.FinanceID
		WHERE Path LIKE ''00001%'' AND lvl>1 AND SonNum=0 AND b.Period=@Period
	)'
SET @Sql+='
	SELECT	fc.FinanceID,
			FinanceName,
			dbo.UF_OT_StringReplace(Lvl,3)+FinanceNO AS FinanceNO,
			Lvl,
			fc.path,
			SonNum,
			ISNULL(SUM(fd.Total),0) AS Total,
			ISNULL(SUM(fd.BQTotal),0) AS BQTotal
	FROM BD_Finance fc '
IF  dbo.UF_BD_IsAllAtypeLimit(@UserID)<>2
	SET @Sql+='
	INNER JOIN dbo.UF_BD_AtypeLimit(@UserID) a ON a.FinanceID=fc.FinanceID
	LEFT JOIN
	(
		SELECT f.* FROM '+CASE WHEN @Period=-1 THEN '#ExpenditureData' ELSE 'FinanceData' END+' f
		INNER JOIN dbo.UF_BD_AtypeLimit(@UserID) a ON a.FinanceID=f.FinanceID 
	)fd ON  fd.Path LIKE fc.Path+''%'' '
ELSE
	SET @sql+='
	LEFT JOIN '+CASE WHEN @Period=-1 THEN '#ExpenditureData' ELSE 'FinanceData' END+' fd ON  fd.Path LIKE fc.Path+''%'' '
SET @sql+='
	WHERE fc.Path LIKE ''00001%'' AND lvl>1
	GROUP BY fc.FinanceID,FinanceName,fc.Path,FinanceNO,Lvl,SonNum
	ORDER BY Path,FinanceNO
	if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
	'
--PRINT @Sql
EXEC sp_executesql @Sql,N'@Period int,@StartDate Date,@UserID int',@Period,@StartDate,@UserID
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：赵燕琴
	日期：2020-2-11
	描述：现金银行报表
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_CashBankReport]
(	
	@BeginDate DATE,
	@EndDate DATE,
	@UserID int=1
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(max)

SET @sql='
	
		if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
		if object_id(''tempdb..#Cqtotalbill'',''U'') is not null drop table #Cqtotalbill

		SELECT	fc.FinanceID,
			ParID,
			Path,
			SUM(b.Total)Total,
			SUM(b.BQTotal) BQTotal,
			SUM(b.addTotal) addTotal,
			SUM(b.reTotal) reTotal
		INTO #ExpenditureData
		FROM BD_Finance fc
		INNER JOIN
		(
			SELECT FinanceID,SUM(JTotal) AS addTotal ,SUM(DTotal) AS reTotal,SUM(JTotal-DTotal) AS BQTotal,0 AS Total  
			FROM PD_ListTable 
			WHERE  BillDate>=@BeginDate AND BillDate<=@EndDate	AND Red=0 GROUP BY FinanceID
			UNION ALL
			SELECT FinanceID,0 AS addTotal,0 AS reTotal,0 AS BQTotal,QmBalances AS Total  
			FROM BD_Funds
		)b 
		ON fc.FinanceID = b.FinanceID
		WHERE Path LIKE ''00001%'' AND lvl>1 AND SonNum=0 
		GROUP BY fc.FinanceID,ParID,Path


	 SELECT a.*,ISNULL(c.T,0) AS cqtotal INTO #Cqtotalbill FROM	#ExpenditureData a
	 INNER JOIN 	
	 (
		SELECT FinanceID, (SUM(BQTotal)+SUM(Total))T 
		FROM(
			SELECT FinanceID,SUM(JTotal-DTotal) AS BQTotal,0 AS Total  
			FROM PD_ListTable 
			WHERE  BillDate<@BeginDate 	AND Red=0 GROUP BY FinanceID
			UNION ALL
			SELECT FinanceID,0 AS BQTotal,QcBalances AS Total  
			FROM BD_Funds)d 
			GROUP BY d.FinanceID
	 )c
	 ON a.FinanceID=c.FinanceID	
	
	
		
	SELECT	fc.FinanceID,
			FinanceName,
			dbo.UF_OT_StringReplace(Lvl,3)+FinanceNO AS FinanceNO,
			Lvl,
			fc.path,
			SonNum,
			ISNULL(SUM(fd.cqtotal)+SUM(fd.BQTotal),0) AS Total,
			ISNULL(SUM(fd.BQTotal),0) AS BQTotal,
			ISNULL(SUM(fd.addTotal),0) AS addTotal,
			ISNULL(SUM(fd.reTotal),0) AS reTotal,
			ISNULL(SUM(fd.cqtotal),0) AS cqtotal
	FROM BD_Finance fc '
	IF  dbo.UF_BD_IsAllAtypeLimit(@UserID)<>2
	SET @Sql+='
	INNER JOIN dbo.UF_BD_AtypeLimit(@UserID) a ON a.FinanceID=fc.FinanceID
	LEFT JOIN
	(
		SELECT f.* FROM #Cqtotalbill f
		INNER JOIN dbo.UF_BD_AtypeLimit(@UserID) a ON a.FinanceID=f.FinanceID 
	)fd ON  fd.Path LIKE fc.Path+''%'' '
ELSE
	SET @sql+='
	LEFT JOIN  #Cqtotalbill fd ON  fd.Path LIKE fc.Path+''%'' '
	
SET @Sql+='WHERE fc.Path LIKE ''00001%'' AND lvl>1
	GROUP BY fc.FinanceID,FinanceName,fc.Path,FinanceNO,Lvl,SonNum
	ORDER BY Path,FinanceNO
	if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
    if object_id(''tempdb..#Cqtotalbill'',''U'') is not null drop table #Cqtotalbill'
--PRINT @Sql
EXEC sp_executesql @Sql,N'@EndDate Date,@BeginDate Date,@UserID int',@EndDate,@BeginDate,@UserID
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：hanlin
	日期：2014-7-28
	描述：往来发生统计
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_ContactAmountStatistics]
(
	@PageNo INT,
	@PageSize INT,
	@BeginDate DATE,
	@EndDate DATE,
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CollectType INT=1,
	@Layer INT =1,
	@OrderField VARCHAR(MAX),
	@Type INT,
	@IsHistory INT=0,
	@UserID INT=1
)

AS
SET NOCOUNT ON


DECLARE @Sql NVARCHAR(max),@TypeName VARCHAR(10),@FromTableStr VARCHAR(max),@JoinStr VARCHAR(max)='',@TableStr VARCHAR(max)='',@TypeJoinStr VARCHAR(max)='',@Ret INT=0

EXEC @ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN

DECLARE	@AR_ID VARCHAR(50),		
		@AP_ID VARCHAR(50),
		@BR_ID VARCHAR(50),		
		@BP_ID VARCHAR(50)
		
SELECT @AR_ID=FinanceID FROM BD_Finance WHERE FinanceNO='1131'			
SELECT @AP_ID=FinanceID FROM BD_Finance WHERE FinanceNO='2121'			
SELECT @BR_ID=FinanceID FROM BD_Finance WHERE FinanceNO='2131'			
SELECT @BP_ID=FinanceID FROM BD_Finance WHERE FinanceNO='1151'

IF @CollectType=1
	SET @TypeName='BtypeID'
ELSE IF @CollectType=2
	SET @TypeName='DeptID'
ELSE
	SET @TypeName='ElyID'

IF(@DeptID<>'')
BEGIN
	SET @TableStr =' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @JoinStr=' INNER JOIN @Dtype d on a.DeptID=d.TypeID '
	IF @CollectType=2
		SET @TypeJoinStr= ' INNER JOIN @Dtype d1 on D.DeptID=d1.TypeID '
END
IF @BTypeID<>'' OR dbo.UF_BD_IsAllBtypeLimit(@UserID)<>2 
BEGIN
	SET @TableStr+=' DECLARE @BType Table(TypeID INT) insert into @BType '
	IF @BTypeID<>'' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)=2 
		SET @TableStr+='	Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	ELSE IF @BTypeID='' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)<>2
		SET @TableStr+='	Select Btypeid from dbo.UF_BD_BtypeLimit(@UserID) '
	ELSE
		SET @TableStr+='	Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') a inner join dbo.UF_BD_BtypeLimit(@UserID) b ON b.BtypeID =a.typeid '
		
	SET @JoinStr+=' INNER JOIN @Btype b on a.BTypeID=b.TypeID '
	IF @CollectType=1
		SET @TypeJoinStr= ' INNER JOIN @Btype b1 on b.BTypeID=b1.TypeID '
END   
IF(@ElyID<>'')
BEGIN
	SET @TableStr +=' DECLARE @EType Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @JoinStr+=' INNER JOIN @Etype e on a.ElyID=e.TypeID '
	IF @CollectType=3
		SET @TypeJoinStr= ' INNER JOIN @Etype e1 on e.ElyID=e1.TypeID  '
END
		
SET @sql=@TableStr
SET @Sql+='

if object_id(''tempdb..#RssPagingData'',''U'') is not null drop table #RssPagingData
;WITH FinceTotal AS 
(
	SELECT '+@TypeName+',
			CASE WHEN f.FinanceID=@AR_ID THEN  SUM(A.Total*f.LoanStt) ELSE 0 END AS ARTotal,
			CASE WHEN f.FinanceID=@AP_ID THEN  SUM(A.Total*f.LoanStt) ELSE 0 END AS APTotal,
			CASE WHEN f.FinanceID=@BR_ID THEN  SUM(A.Total*f.LoanStt) ELSE 0 END AS BRTotal,
			CASE WHEN f.FinanceID=@BP_ID THEN  SUM(A.Total*f.LoanStt) ELSE 0 END AS BPTotal 
	FROM 
	(
		SELECT BillDate,BTypeID,DeptID,ElyID,FinanceID,JTotal-DTotal AS Total,Red FROM PD_ListTable '
IF @IsHistory=1
	SET @sql+='
		UNION ALL
		SELECT BillDate,BTypeID,DeptID,ElyID,FinanceID,JTotal-DTotal AS Total,Red  FROM PD_ListTable_His '
SET @sql+=	
	'
	)a  INNER JOIN BD_Finance f ON a.FinanceID = f.FinanceID
	'+@JoinStr+'
	WHERE BillDate BETWEEN @BeginDate AND @EndDate AND red=0 AND f.FinanceNO IN(''1131'',''2121'',''2131'',''1151'')
	GROUP by '+@TypeName+',f.FinanceID
)'

IF @CollectType=1
BEGIN
	IF @Layer<>6
	BEGIN
		SET @sql +=' ,PagingData AS (SELECT bt2.TypeCode As UserCode,bt2.TypeName as FullName,Bt2.BTypeTypeID as TypeID '
		SELECT @FromTableStr='  bd_btype_type bt2 INNER JOIN bd_btype_type bt On LEFT(bt.Path,5*'+CAST(@Layer AS VARCHAR)+')=bt2.Path inner join  BD_Btype b ON b.btypetypeid=bt.btypetypeid '+@TypeJoinStr+'
		LEFT JOIN FinceTotal f ON f.BtypeID=b.BtypeID  WHERE bt2.lvl='+CAST(@Layer AS VARCHAR)+' OR( bt2.lvl<'+CAST(@Layer AS VARCHAR)+' AND bt2.Sonnum=0) Group By bt2.TypeCode,bt2.TypeName,Bt2.BTypeTypeID)'
	END
	ELSE
	BEGIN
		SET @sql +=' ,PagingData AS(SELECT B.BtypeCode as UserCode,B.BtypeName as FullName,B.BTypeID as TypeID '
		SELECT @FromTableStr=' BD_Btype b '+@TypeJoinStr+' LEFT JOIN FinceTotal f ON b.BtypeID=f.BtypeID Group By B.BtypeCode,B.BtypeName,B.BTypeID) '
	END
END
ELSE IF @CollectType=2
BEGIN
	SET @sql +='  ,PagingData AS (SELECT D2.DeptCode As UserCode,D2.DeptName AS FullName,D2.DeptID as TypeID'
	SELECT @FromTableStr=' BD_Dept D2 inner join BD_Dept D ON d2.Path=LEFT(D.Path,5*'+CAST(@Layer AS VARCHAR)+')'+@TypeJoinStr+' LEFT JOIN FinceTotal f ON d.DeptID=f.DeptID WHERE D2.lvl='+CAST(@Layer AS VARCHAR)+' OR( d2.lvl<'+CAST(@Layer AS VARCHAR)+' AND d2.Sonnum=0)   Group By D2.DeptName,D2.DeptCode,D2.DeptID)'
END
ELSE
BEGIN
	SET @sql +=' ,PagingData AS (SELECT E.ElyCode AS UserCode,E.ElyName As FullName,E.ElyID AS TypeID'
	SELECT @FromTableStr=' BD_Employee E '+@TypeJoinStr+' LEFT JOIN FinceTotal f  ON f.ElyID=E.ElyID WHERE E.ElyID<>1  Group By E.ElyCode,E.ElyName,E.ElyID )'
END
	
SET @sql+=' ,isNULL(SUM(ARTotal),0)ARTotal,isNULL(SUM(APTotal),0) APTotal,isNULL(SUM(BRTotal),0)BRTotal,isNULL(SUM(BPTotal),0)BPTotal,isNULL(SUM(ARTotal+BPTotal-ApTotal-BRTotal),0) As ARAPTotal FROM'+@FromTableStr

IF @Type<>3
SET @sql+='
	SELECT * INTO #RssPagingData FROM PagingData	
   SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM #RssPagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderField+' ) AS ROWID,
	*
	FROM #RssPagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	DROP TABLE #RssPagingData

'
ELSE
	SET @sql+='
	select SUM(ARTotal)ARTotal,SUM(APTotal)APTotal,SUM(BRTotal)BRTotal,SUM(BPTotal)BPTotal,SUM(ARAPTotal)ARAPTotal from PagingData
	'
--PRINT(@sql)
EXEC sp_executesql @sql,N'@BeginDate Date,@EndDate Date,@AR_ID INT,@AP_ID INT,@BR_ID INT,@BP_ID INT,@PageNo int,@PageSize INT,@BTypeID VarChar(max),@DeptID varchar(max),@ElyID varchar(max),@UserID INT',@BeginDate,@EndDate,@AR_ID,@AP_ID,@BR_ID,@BP_ID,@PageNo,@PageSize,@bTypeid,@DeptID,@ElyID,@UserID

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：李文博
	日期：2014-08-15
	描述：创利分类统计[转换列数据]
-------------------------------------------*/
CREATE PROCEDURE UP_MF_EtypeProfitQuery
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BTypeID VARCHAR(MAX) = '',
	@DeptID VARCHAR(MAX) = '',
	@ElyID VARCHAR(MAX) = '',
	@FinanceID VARCHAR(MAX) = '',
	@ComContent TINYINT = 0,
	@SumType TINYINT = 1,
	@SumLayer TINYINT = 1,
	@OrderType VARCHAR(MAX) = '',
	@AscType BIT = 0,
	@IsHistory BIT = 0,
	@OperatorID INT = 1
)

AS

DECLARE @Sql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = '', @TableSql NVARCHAR(MAX)='', @IndexSql NVARCHAR(MAX) = ''
DECLARE @BaseCol NVARCHAR(MAX) = '', @ShowTableSql NVARCHAR(MAX) = '', @selectSql NVARCHAR(MAX) = '', @InSql NVARCHAR(MAX) = ''
DECLARE @TotalSql NVARCHAR(MAX) = '', @OrderCol NVARCHAR(MAX) = '', @Ret INT = 0, @ListTable NVARCHAR(MAX) = '', @BaseTableSql NVARCHAR(MAX) = ''
DECLARE @SumCol NVARCHAR(MAX) = '', @BDCol NVARCHAR(MAX) = '', @GroupCol NVARCHAR(MAX) = '', @TypeTotalSql NVARCHAR(MAX) = ''
DECLARE @LimitSql NVARCHAR(MAX) = ''

EXEC @Ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN


/*****处理排序******/
IF @AscType = 0 SET @OrderCol = @OrderType + ' ASC' ELSE SET @OrderCol = @OrderType + ' DESC'
/*******************/

/************处理显示列************/
DECLARE @soure TABLE (rowIndex INT IDENTITY,FinanceID INT,FinanceName VARCHAR(100), ClassID INT)
DECLARE	@Count INT = 0, @i INT = 1
DECLARE @FID VARCHAR(10) = '', @FName VARCHAR(100) = '', @CID VARCHAR(10)=''
IF @FinanceID = ''
BEGIN
	INSERT INTO @soure
	       SELECT FinanceID, FinanceName, ParID AS ClassID FROM BD_Finance WHERE ParID = 3 OR ParID =4 OR FinanceID IN (3,4)
END ELSE
BEGIN
	INSERT INTO @soure
	     SELECT FinanceID, FinanceName, CASE LEFT(Path,5) WHEN '00002' THEN 3 ELSE 4 END AS ClassID  FROM BD_Finance bf
	     INNER JOIN (
			SELECT typeid FROM  dbo.UF_OT_Split_Int(@FinanceID,',')
			) a
	     ON  bf.FinanceID = a.typeid
	     UNION ALL 
		 SELECT FinanceID, FinanceName, ParID AS ClassID FROM BD_Finance WHERE FinanceID IN (3,4)
END

SELECT @Count = COUNT(1) FROM @soure
WHILE @i <= @Count
BEGIN
	SELECT @FID = CONVERT(VARCHAR(10),FinanceID), @FName = FinanceName, @CID = ClassID FROM @soure WHERE rowIndex = @i
	IF (@CID = 3 OR @CID = 4)
	BEGIN
		SET @selectSql += ' ,' + ' ['+ @FID + '] AS ['+ @FName +'_' + @CID+']'
		SET @TotalSql +=', ['+@FName +'_' + @CID + ']'
		SET @TypeTotalSql += ', SUM(['+ @FName +'_' + @CID +']) AS ['+ @FName +'_' + @CID +']'
	END ELSE
	BEGIN
		IF @FID = 3	
		BEGIN
			SET @selectSql += ' ,' + ' ['+ @FID + '] AS InSumTotal'
			SET @TotalSql += ', InSumTotal'
			SET @TypeTotalSql +=', SUM(InSumTotal) AS InSumTotal'
		END
		IF @FID = 4	
		BEGIN
			SET @selectSql += ' ,' + ' ['+ @FID + '] AS OutSumTotal'
			SET @TotalSql += ', OutSumTotal'
			SET @TypeTotalSql +=', SUM(OutSumTotal) AS OutSumTotal'
		END
	END
	
	SET @InSql += ', '+ '['+@FID+']'
	SET @i = @i+1
END
SET @InSql = STUFF(@InSql,1,1,'')
SET @TotalSql += ', (ISNULL(InSumTotal, 0) - ISNULL(OutSumTotal, 0)) AS ProfitTotal'
SET @TypeTotalSql += ', SUM(ISNULL(InSumTotal, 0)) - SUM(ISNULL(OutSumTotal, 0)) AS ProfitTotal'
/**********************************/


IF @ComContent = 0 --发生额
BEGIN
	SET @IndexSql = ' AND BillDate BETWEEN @BeginDate AND @EndDate'
END ELSE
BEGIN
	SET @IndexSql = ' AND BillDate <= @EndDate'
END

IF @BTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     SET @TableSql += ' INNER JOIN @BType B ON LT.BTypeID=B.BTypeID '
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
	SET @TableSql+=' INNER JOIN @DType D ON LT.DeptID=D.DeptID '  
END

IF @ElyID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @EType E ON LT.ElyID=E.ElyID '    
END

IF @FinanceID <> ''
BEGIN
SET @CreateTableSql += '   
     DECLARE @ShowAType Table(FinanceID INT)   
     INSERT  INTO @ShowAType 
     SELECT typeid AS FinanceID FROM dbo.UF_OT_Split_Int(@FinanceID,'','')
     UNION ALL
     SELECT FinanceID FROM BD_Finance WHERE FinanceID IN (3,4)
     '  
	SET @ShowTableSql = ' INNER JOIN @ShowAType SA ON LT.FinanceID=SA.FinanceID'
END ELSE
BEGIN
	SET @CreateTableSql += '
	DECLARE @ShowAType Table(FinanceID INT)   
    INSERT  INTO @ShowAType 
    SELECT FinanceID FROM BD_Finance WHERE ParID = 3 OR ParID = 4 OR FinanceID IN (3,4)
	'
	SET @ShowTableSql += ' INNER JOIN @ShowAType SA ON LT.FinanceID=SA.FinanceID'
END

IF @SumType = 1 --按往来单位汇总
BEGIN
	SET @GroupCol = ', LT.BTypeID'
	SET @BaseCol = 'BTypeID'
	IF @SumLayer = 6
	BEGIN
		SET @BDCol = 'BD.BTypeID AS BaseID, BD.BTypeCode, BD.BTypeName' + @TotalSql
		IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 2
		BEGIN
			SET @BaseTableSql = '
				INNER JOIN 
				(SELECT BTypeID, BTypeCode, BTypeName FROM BD_Btype 
				UNION ALL
				SELECT 0 AS BTypeID,	'''' AS BTypeCode, ''其他'' AS BTypeName
				) BD  ON BD.BTypeID = SOURCE.BTypeID'
		END ELSE 
		BEGIN
			SET @BaseTableSql = '
				INNER JOIN (
				SELECT BTypeID, 
				CASE LimitID WHEN 0 THEN ''***'' ELSE BTypeCode END AS BTypeCode, 
				CASE LimitID WHEN 0 THEN ''***'' ELSE BTypeName END AS BTypeName  
				FROM (
					SELECT LT.BTypeID, BTypeCode, BTypeName, ISNULL(bl.BTypeID, 0) AS LimitID FROM BD_Btype LT
					LEFT JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =LT.BTypeID
					)A
				UNION ALL
				SELECT 0 AS BTypeID,	'''' AS BTypeCode, ''其他'' AS BTypeName
				) BD  ON BD.BTypeID = SOURCE.BTypeID'
		END
		
	END ELSE
	BEGIN
		SET @BDCol = 'BD.BTypeTypeID AS BaseID, BD.TypeCode AS BCode, BD.TypeName AS BName'+ @TypeTotalSql
		IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 2
		BEGIN
			SET @BaseTableSql += ' 
			INNER JOIN (SELECT BTypeID , BtypeTypeID FROM BD_Btype UNION ALL SELECT 0 AS BTypeID, 0 AS BtypeTypeID) BT ON  SOURCE.BTypeID = BT.BTypeID
			INNER JOIN dbo.UF_BD_BaseSummary(''BTYPE'', @SumLayer) SBD ON BT.BtypeTypeID = SBD.ParID 
			INNER JOIN (SELECT BTypeTypeID, TypeCode, TypeName FROM BD_Btype_Type 
						UNION ALL 
						SELECT 0 AS BTypeTypeID, '''' AS TypeCode, ''其他'' AS TypeName
						) BD ON SBD.BaseID = BD.BTypeTypeID '
		END ELSE
		BEGIN
			SET @BaseTableSql += ' 
			INNER JOIN (SELECT BTypeID , BtypeTypeID FROM BD_Btype UNION ALL SELECT 0 AS BTypeID, 0 AS BtypeTypeID) BT ON  SOURCE.BTypeID = BT.BTypeID
			INNER JOIN dbo.UF_BD_BaseSummary(''BTYPE'', @SumLayer) SBD ON BT.BtypeTypeID = SBD.ParID 
			INNER JOIN (SELECT BTypeTypeID, 
						CASE LimitID WHEN 0 THEN ''***'' ELSE TypeCode END AS TypeCode, 
						CASE LimitID WHEN 0 THEN ''***'' ELSE TypeName END AS TypeName FROM 
						(
							 SELECT LT.BtypeTypeID, TypeCode, TypeName, ISNULL(bl.BtypeTypeID, 0) AS LimitID FROM BD_Btype_Type LT
							 LEFT JOIN dbo.UF_BD_BtypeTypeLimit(@OperatorID) bl ON bl.BtypeTypeID =LT.BtypeTypeID
						)A
						UNION ALL 
						SELECT 0 AS BTypeTypeID, '''' AS TypeCode, ''其他'' AS TypeName
					) BD ON SBD.BaseID = BD.BTypeTypeID '
		END
		SET @SumCol = 'GROUP BY BD.BTypeTypeID, BD.TypeCode, BD.TypeName'
	END
	
END ELSE
IF @SumType = 2 --按部门汇总
BEGIN
	SET @GroupCol = ', LT.DeptID'
	SET @BaseCol = 'DeptID'
	IF @SumLayer = 5
	BEGIN
		SET @BDCol = 'BD.DeptID AS BaseID, BD.DeptCode, BD.DeptName' + @TotalSql
		SET @BaseTableSql = 'INNER JOIN BD_Dept BD ON BD.DeptID = SOURCE.DeptID '
	END ELSE
	BEGIN
		SET @BDCol = 'BaseID, BD.DeptCode, BD.DeptName' + @TypeTotalSql
		SET @BaseTableSql += ' 
		INNER JOIN dbo.UF_BD_BaseSummary(''DTYPE'', @SumLayer) SBD ON SBD.ParID= SOURCE.DeptID
		INNER JOIN BD_Dept BD ON SBD.BaseID = BD.DeptID'	
		SET @SumCol = 'GROUP BY BaseID, BD.DeptCode, BD.DeptName'
	END

END ELSE
IF @SumType = 3 --按职员汇总
BEGIN
	SET @GroupCol = ', LT.ElyID'
	SET @BaseCol = 'ElyID'
	SET @BDCol = 'BD.ElyID AS BaseID, BD.ElyCode, BD.ElyName' + @TotalSql
	SET @BaseTableSql = 'INNER JOIN BD_Employee BD ON BD.ElyID = SOURCE.ElyID '
	
END


IF @IsHistory = 0
BEGIN
	SET @ListTable = '
	( SELECT LT.FinanceID '+ @GroupCol +', CASE BF.LoanStt WHEN 1 THEN JTotal - DTotal ELSE DTotal - JTotal END AS Total 
	  FROM PD_ListTable LT 
	  INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
	  '+ @TableSql +'
	  WHERE Red = 0 AND (BF.Path LIKE ''00002%'' OR BF.Path LIKE ''00003%'')' + @IndexSql +'
	  )
	'
END ELSE
BEGIN
	SET @ListTable = '
	( SELECT LT.FinanceID '+ @GroupCol +', CASE BF.LoanStt WHEN 1 THEN JTotal - DTotal ELSE DTotal - JTotal END AS Total 
	  FROM PD_ListTable LT 
	  INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
	  '+ @TableSql +'
	  WHERE Red = 0 AND (BF.Path LIKE ''00002%'' OR BF.Path LIKE ''00003%'') '+ @IndexSql +'
	  UNION ALL
	  SELECT LT.FinanceID '+ @GroupCol +', CASE BF.LoanStt WHEN 1 THEN JTotal - DTotal ELSE DTotal - JTotal END AS Total 
	  FROM PD_ListTable_His LT
	  '+ @TableSql +'
	  INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
	  WHERE Red = 0 AND (BF.Path LIKE ''00002%'' OR BF.Path LIKE ''00003%'') '+ @IndexSql +'
	  )
	'
END

SET @CreateTableSql += ' DECLARE @AtypeData Table(FinanceID INT, '+ @BaseCol +' INT, Total decimal(20, 8) )'

SET @Sql = @CreateTableSql + '
INSERT INTO @AtypeData 
SELECT BF.FinanceID ' + @GroupCol + ', SUM(Total) 
FROM BD_Finance BF 
LEFT JOIN
(
	SELECT BF.Path, BF.FinanceID, ISNULL('+ STUFF(@GroupCol,1,1,'') +', 0) '+ @BaseCol +', ISNULL(Total, 0) Total FROM
	(SELECT LT.FinanceID '+ @GroupCol +',SUM(Total) Total
	FROM  
	'+ @ListTable +' LT
	GROUP BY LT.FinanceID '+ @GroupCol +'
	) LT
	INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
) LT 
ON LT.Path LIKE BF.Path + ''%''
WHERE BF.PATH LIKE ''00002%'' OR BF.PATH LIKE ''00003%''
GROUP BY BF.FinanceID' + @GroupCol + '


;WITH PagingData AS  
(
	SELECT '+ @BDCol +'
	FROM 
	(
		SELECT '+ @BaseCol + @selectSql +' 
		FROM
		(
			SELECT LT.FinanceID '+ @GroupCol +', Total FROM
			@AtypeData LT
		'+ @ShowTableSql +'
		)
		AS SourceData PIVOT (MAX(Total) FOR FinanceID IN ('+ @InSql +'))AS A

	) SOURCE 
	'+ @BaseTableSql +'
	'+ @SumCol+'
)

'
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FinanceID','VARCHAR(MAX)', @FinanceID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BTypeID','VARCHAR(MAX)', @BTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID','VARCHAR(MAX)', @DeptID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ElyID','VARCHAR(MAX)', @ElyID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate','DATE', @BeginDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate','DATE', @EndDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SumLayer','TINYINT', @SumLayer)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT', @OperatorID)
EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, @OrderCol,'','ROWID ASC',1,0
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：李文博
	日期：2014-08-15
	描述：创利分类统计[转换列数据]
-------------------------------------------*/
CREATE PROCEDURE UP_MF_EtypeProfitQuerySum
(
	@BeginDate DATE,
	@EndDate DATE,
	@BTypeID VARCHAR(MAX) = '',
	@DeptID VARCHAR(MAX) = '',
	@ElyID VARCHAR(MAX) = '',
	@FinanceID VARCHAR(MAX) = '',
	@ComContent TINYINT = 0,
	@IsHistory BIT = 0,
	@OperatorID INT = 1
)

AS

DECLARE @Sql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = '', @TableSql NVARCHAR(MAX)='', @IndexSql NVARCHAR(MAX) = ''
,@ShowTableSql NVARCHAR(MAX) = '', @selectSql NVARCHAR(MAX) = '', @InSql NVARCHAR(MAX) = ''
DECLARE @TotalSql NVARCHAR(MAX) = '', @Ret INT = 0, @ListTable NVARCHAR(MAX) = ''
DECLARE @SumCol NVARCHAR(MAX) = '', @TypeTotalSql NVARCHAR(MAX) = ''
DECLARE @LimitSql NVARCHAR(MAX) = ''

EXEC @Ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN

/*******************/

/************处理显示列************/
DECLARE @soure TABLE (rowIndex INT IDENTITY,FinanceID INT,FinanceName VARCHAR(100), ClassID INT)
DECLARE	@Count INT = 0, @i INT = 1
DECLARE @FID VARCHAR(10) = '', @FName VARCHAR(100) = '', @CID VARCHAR(10)=''
IF @FinanceID = ''
BEGIN
	INSERT INTO @soure
	       SELECT FinanceID, FinanceName, ParID AS ClassID FROM BD_Finance WHERE ParID = 3 OR ParID =4 OR FinanceID IN (3,4)
END ELSE
BEGIN
	INSERT INTO @soure
	     SELECT FinanceID, FinanceName, CASE LEFT(Path,5) WHEN '00002' THEN 3 ELSE 4 END AS ClassID  FROM BD_Finance bf
	     INNER JOIN (
			SELECT typeid FROM  dbo.UF_OT_Split_Int(@FinanceID,',')
			) a
	     ON  bf.FinanceID = a.typeid
	     UNION ALL 
		 SELECT FinanceID, FinanceName, ParID AS ClassID FROM BD_Finance WHERE FinanceID IN (3,4)
END

SELECT @Count = COUNT(1) FROM @soure
WHILE @i <= @Count
BEGIN
	SELECT @FID = CONVERT(VARCHAR(10),FinanceID), @FName = FinanceName, @CID = ClassID FROM @soure WHERE rowIndex = @i
	IF (@CID = 3 OR @CID = 4)
	BEGIN
		SET @selectSql += ' ,' + ' ['+ @FID + '] AS ['+ @FName +'_' + @CID+']'
		SET @TotalSql +=', ['+@FName +'_' + @CID + ']'
		SET @TypeTotalSql += ', SUM(['+ @FName +'_' + @CID +']) AS ['+ @FName +'_' + @CID +']'
	END ELSE
	BEGIN
		IF @FID = 3	
		BEGIN
			SET @selectSql += ' ,' + ' ['+ @FID + '] AS InSumTotal'
			SET @TotalSql += ', InSumTotal'
			SET @TypeTotalSql +=', SUM(InSumTotal) AS InSumTotal'
		END
		IF @FID = 4	
		BEGIN
			SET @selectSql += ' ,' + ' ['+ @FID + '] AS OutSumTotal'
			SET @TotalSql += ', OutSumTotal'
			SET @TypeTotalSql +=', SUM(OutSumTotal) AS OutSumTotal'
		END
	END
	
	SET @InSql += ', '+ '['+@FID+']'
	SET @i = @i+1
END
SET @InSql = STUFF(@InSql,1,1,'')
SET @selectSql = STUFF(@selectSql,1,2,'')
SET @TotalSql =STUFF(@TotalSql,1,1,'')+ ', (ISNULL(InSumTotal, 0) - ISNULL(OutSumTotal, 0)) AS ProfitTotal'
SET @TypeTotalSql = STUFF(@TypeTotalSql,1,1,'')+', SUM(ISNULL(InSumTotal, 0)) - SUM(ISNULL(OutSumTotal, 0)) AS ProfitTotal'
/**********************************/


IF @ComContent = 0 --发生额
BEGIN
	SET @IndexSql = ' AND BillDate BETWEEN @BeginDate AND @EndDate'
END ELSE
BEGIN
	SET @IndexSql = ' AND BillDate <= @EndDate'
END

IF @BTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     SET @TableSql += ' INNER JOIN @BType B ON LT.BTypeID=B.BTypeID '
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
	SET @TableSql+=' INNER JOIN @DType D ON LT.DeptID=D.DeptID '  
END

IF @ElyID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @EType E ON LT.ElyID=E.ElyID '    
END

IF @FinanceID <> ''
BEGIN
SET @CreateTableSql += '   
     DECLARE @ShowAType Table(FinanceID INT)   
     INSERT  INTO @ShowAType 
     SELECT typeid AS FinanceID FROM dbo.UF_OT_Split_Int(@FinanceID,'','')
     UNION ALL
     SELECT FinanceID FROM BD_Finance WHERE FinanceID IN (3,4)
     '  
	SET @ShowTableSql = ' INNER JOIN @ShowAType SA ON LT.FinanceID=SA.FinanceID'
END ELSE
BEGIN
	SET @CreateTableSql += '
	DECLARE @ShowAType Table(FinanceID INT)   
    INSERT  INTO @ShowAType 
    SELECT FinanceID FROM BD_Finance WHERE ParID = 3 OR ParID = 4 OR FinanceID IN (3,4)
	'
	SET @ShowTableSql += ' INNER JOIN @ShowAType SA ON LT.FinanceID=SA.FinanceID'
END

IF @IsHistory = 0
BEGIN
	SET @ListTable = '
	( SELECT LT.FinanceID , CASE BF.LoanStt WHEN 1 THEN JTotal - DTotal ELSE DTotal - JTotal END AS Total 
	  FROM PD_ListTable LT 
	  INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
	  '+ @TableSql +'
	  WHERE Red = 0 AND (BF.Path LIKE ''00002%'' OR BF.Path LIKE ''00003%'')' + @IndexSql +'
	  )
	'
END ELSE
BEGIN
	SET @ListTable = '
	( SELECT LT.FinanceID , CASE BF.LoanStt WHEN 1 THEN JTotal - DTotal ELSE DTotal - JTotal END AS Total 
	  FROM PD_ListTable LT 
	  INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
	  '+ @TableSql +'
	  WHERE Red = 0 AND (BF.Path LIKE ''00002%'' OR BF.Path LIKE ''00003%'') '+ @IndexSql +'
	  UNION ALL
	  SELECT LT.FinanceID , CASE BF.LoanStt WHEN 1 THEN JTotal - DTotal ELSE DTotal - JTotal END AS Total 
	  FROM PD_ListTable_His LT
	  '+ @TableSql +'
	  INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
	  WHERE Red = 0 AND (BF.Path LIKE ''00002%'' OR BF.Path LIKE ''00003%'') '+ @IndexSql +'
	  )
	'
END


SET @CreateTableSql += ' DECLARE @AtypeData Table(FinanceID INT, Total decimal(20, 8) )'

SET @Sql = @CreateTableSql + '
INSERT INTO @AtypeData 
SELECT BF.FinanceID, SUM(Total) 
FROM BD_Finance BF 
LEFT JOIN
(
	SELECT BF.Path, BF.FinanceID, ISNULL(Total, 0) Total FROM
	(SELECT LT.FinanceID,SUM(Total) Total
	FROM  
	'+ @ListTable +' LT
	GROUP BY LT.FinanceID 
	) LT
	INNER JOIN BD_Finance BF ON LT.FinanceID = BF.FinanceID
) LT 
ON LT.Path LIKE BF.Path + ''%''
WHERE BF.PATH LIKE ''00002%'' OR BF.PATH LIKE ''00003%''
GROUP BY BF.FinanceID

SELECT '+ @TotalSql +'
FROM 
(
	SELECT '+ @selectSql +' 
	FROM
	(
		SELECT LT.FinanceID, Total FROM
		@AtypeData LT
	'+ @ShowTableSql +'
	)
	AS SourceData PIVOT (MAX(Total) FOR FinanceID IN ('+ @InSql +'))AS A

) SOURCE 

'
EXEC sp_executesql @sql,N'@BeginDate DATE,@EndDate DATE,@BTypeID VARCHAR(MAX),@DeptID VARCHAR(MAX),@ElyID VARCHAR(MAX),@FinanceID Varchar(max),@ComContent INT,@OperatorID INT'
,@BeginDate,@EndDate,@BTypeID ,@DeptID ,@ElyID,@FinanceID ,@ComContent ,@OperatorID 
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：hanlin
	日期：2014-7-28
	描述：费用支出统计
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_ExpenditureStatistics]
(
	@Period INT=0,
	@UserID INT=1
)

AS
SET NOCOUNT ON

IF  dbo.UF_BD_IsAllAtypeLimit(@UserID)=0
BEGIN
	SELECT  TOP 0 * FROM BD_Finance
	RETURN 
END

DECLARE @StartDate DATE,@Sql NVARCHAR(max)
IF  EXISTS(SELECT 1 FROM SS_MonthProc WHERE Name='本期' AND Period=@Period)
	SET @Period=0
IF @Period=99999
	SET @Sql='
		;WITH FinanceData AS
		(
			SELECT	fc.FinanceID,
					ParID,
					Path,
					b.QcBalances As Total,
					b.QcBalances AS BqTotal
			FROM BD_Finance fc
			INNER JOIN BD_Funds b ON fc.FinanceID = b.FinanceID
			WHERE FinanceNO<>''5401'' AND Path LIKE ''00003%'' AND lvl>1 AND SonNum=0 
		)
		'
ELSE IF @Period=0
BEGIN
	SELECT @StartDate= StartDate FROM SS_MonthProc WHERE Name='本期'
	SET @Sql='
		if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
		SELECT	fc.FinanceID,
			ParID,
			Path,
			SUM(b.Total)Total,
			SUM(b.BQTotal) BQTotal
		INTO #ExpenditureData
		FROM BD_Finance fc
		INNER JOIN
		(
			SELECT FinanceID,SUM(JTotal-DTotal) AS BQTotal,0 AS Total  FROM PD_ListTable WHERE  BillDate>=@StartDate	AND Red=0 GROUP BY FinanceID
			UNION ALL
			SELECT FinanceID,0 AS BQTotal,QmBalances AS Total  FROM BD_Funds
		)b ON fc.FinanceID = b.FinanceID
		WHERE FinanceNO<>''5401'' AND Path LIKE ''00003%'' AND lvl>1 AND SonNum=0 
		GROUP BY fc.FinanceID,ParID,Path'
END
ELSE
	SET @sql='
	;WITH FinanceData AS
	(
		SELECT	fc.FinanceID,
				ParID,
				Path,
				b.Total,
				b.BQTotal
		FROM BD_Finance fc
		INNER JOIN SS_MonthBalance b ON fc.FinanceID = b.FinanceID
		WHERE FinanceNO<>''5401'' AND Path LIKE ''00003%'' AND lvl>1 AND SonNum=0 AND b.Period=@Period
	)'
SET @Sql+='
	SELECT	fc.FinanceID,
			FinanceName,
			dbo.UF_OT_StringReplace(Lvl,3)+FinanceNO AS FinanceNO,
			Lvl,
			fc.path,
			SonNum,
			ISNULL(SUM(fd.Total),0) AS Total,
			ISNULL(SUM(fd.BQTotal),0) AS BQTotal
	FROM BD_Finance fc'
IF  dbo.UF_BD_IsAllAtypeLimit(@UserID)<>2
	SET @Sql+='
	INNER JOIN dbo.UF_BD_AtypeLimit(@UserID) a ON a.FinanceID=fc.FinanceID
	LEFT JOIN
	(
		SELECT f.* FROM '+CASE WHEN @Period=0 THEN '#ExpenditureData' ELSE 'FinanceData' END+' f
		INNER JOIN dbo.UF_BD_AtypeLimit(@UserID) a ON a.FinanceID=f.FinanceID 
	)fd ON  fd.Path LIKE fc.Path+''%'' '
ELSE
	SET @sql+='
	LEFT JOIN '+CASE WHEN @Period=0 THEN '#ExpenditureData' ELSE 'FinanceData' END+' fd ON  fd.Path LIKE fc.Path+''%'' '
SET @sql+='
	WHERE FinanceNO<>''5401'' AND fc.Path LIKE ''00003%'' AND lvl>1
	GROUP BY fc.FinanceID,FinanceName,fc.Path,FinanceNO,Lvl,SonNum
	ORDER BY Path,FinanceNO
	if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
	'
--PRINT @Sql
EXEC sp_executesql @Sql,N'@Period int,@StartDate Date,@UserID INT',@Period,@StartDate,@UserID
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_MF_FinanceDetailsQuery]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_FinanceDetailsQuery]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*------------------------------------------
    作者：wwei
	日期：2014-07-11
	描述：项目明细查询
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_FinanceDetailsQuery]
(			   
	@pageNo INT=1					--页码
	,@pageSize INT=10				--分页数
	,@BillDateType INT=1				--单据日期类型:1=录单日期,2=制单日期,3=过账日期  对应BillDate,CreateTime,PosTime
	,@BillStartDate DATE			--单据开始日期
	,@BillEndDate DATE				--单据结束日期
	,@BillTypeID Nvarchar(700)='0'	   --单据类型
	,@FinanceID int=0						--项目ID
	,@BtypeID VARCHAR(1000) = ''	--往来单位
	,@BtypeClassID INT = 0	--往来单位分类
	,@DeptID VARCHAR(1000) = ''		--部门
	,@ElyID VARCHAR(1000) = ''		--经手人
	,@ShowRed bit=0					--显示红冲	
	,@OrderType INT=1				--排序条件一:1=录单日期,2=制单日期,3=过账日期
	,@OrderSeq INT=1				--排序规则：1=升序，2=降序
	,@isBeforeTotal int=0           ---1=查询此前余额,2=查询所有合计
	,@isHistory INT=0				--是否包含历史数据
	,@ExPay INT=0				--是否排除销售出库单的付款账款
	,@OperatorID INT --操作员
	,@islimitf int=1  --是否控制项目权限(0=否，1=是)
	
)

AS
SET NOCOUNT ON


DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@isHistory=@isHistory
if( @re=1 )return @re;

if (@BillTypeID='') SET @BillTypeID='0'

IF (@FinanceID<=0) 
BEGIN
	 RAISERROR ('请选择"查询项目"！' , 16, 1) WITH NOWAIT
      RETURN 1
END


	DECLARE @limitAType INT =0
	SELECT @limitAType=dbo.UF_BD_IsAllAtypeLimit(@OperatorID) --是否所有权限[0-无权限，1-部分权限，2-全部权限]
	
	DECLARE @limitBType INT =0 --往来单位
	SELECT @limitBType=dbo.UF_BD_IsAllBtypeLimit(@OperatorID) --是否所有权限[0-无权限，1-部分权限，2-全部权限]
	
	
	
	
	if(@isLimitF=0)--不控制项目权限,
		SET @limitAType=2

DECLARE @FinSonnum INT  
SELECT @FinSonnum=SonNum FROM BD_Finance where FinanceID=@FinanceID


	DECLARE @DSql nvarchar(max)	,@BSql nvarchar(max)
	SELECT  @DSql='',@BSql=''


if (@BtypeClassID>0) --存在分类，并且权限值为非无权限时，才执行
BEGIN
	SET @BSql='DECLARE @bTb  as Table(typeid int)' 
	SET @BSql+='  INSERT INTO @bTb(typeid)'
	SET @BSql+=dbo.UF_BD_GetBtypeID_Str(@BtypeID)
END
if(@DeptID<>'')
BEGIN
	SET @DSql='DECLARE @DTb  as Table(typeid int) 
					INSERT INTO @DTb(typeid)'
	SET @DSql+=dbo.UF_BD_GetDeptID_Str()
END







------------------------------------------------------------过滤掉不相关的单据类型
DECLARE @billtypeTb as TABLE(tbName varchar(50),billTypeID int,billTypeCount int  )
IF @BillTypeID='0' 
BEGIN

	;WITH BillTABLE as (
		SELECT BillTable,BillTypeID FROM PD_BillType where CanPost=1   
	),
	billCount as (
	SELECT COunt(1) as BillCount,BillTable FROM PD_BillType  where CanPost=1    GROUP BY BillTable 
	)
	INSERT INTO @billtypeTb(tbName,billTypeID,billTypeCount)SELECT t.BillTable,t.BillTypeID, c.BillCount FROM BillTABLE t INNER JOIN  billCount c ON t.BillTable=c.BillTable
END
ELSE 
BEGIN
;WITH BillTABLE as (
		SELECT BillTable,BillTypeID FROM PD_BillType b
		 INNER JOIN  dbo.UF_OT_Split_Int(@BillTypeID,',') f ON (b.BillTypeID=f.typeid)
		 where CanPost=1   
	),
	billCount as (
	SELECT COunt(1) as BillCount,BillTable FROM PD_BillType  where CanPost=1    GROUP BY BillTable 
	)
	INSERT INTO @billtypeTb(tbName,billTypeID,billTypeCount)SELECT t.BillTable,t.BillTypeID, c.BillCount FROM BillTABLE t INNER JOIN  billCount c ON t.BillTable=c.BillTable
		
END

---------------------------开始拼单据明细相关的Sql	

DECLARE @SqlBill NVARCHAR(MAX),@SqlHis nvarchar(max),@sqlColumn nvarchar(MAX),@sqlFinance nvarchar(MAX),@sql nvarchar(max),@sqlList nvarchar(MAX),@Sqlold nvarchar(max),@sqlHisColumn nvarchar(max)
SELECT @SqlBill='',@sqlList='', @SqlHis='',@sqlColumn='',@sqlFinance='',@sql='',@Sqlold='',@sqlHisColumn=''

if(@FinSonnum>0)
BEGIN



	SET @sqlFinance+='
						DECLARE @financeTb  as Table(FinanceID int,FinanceNo varchar(256),FinanceName varchar(256),LoanStt int )
						INSERT INTO @financeTb(FinanceID,FinanceNo,FinanceName,LoanStt)
						SELECT b.FinanceID,b.FinanceNo,b.FinanceName,b.LoanStt FROM BD_Finance bc
										  INNER JOIN BD_Finance b ON  b.[Path]  like bc.[Path]+''%'' AND  bc.FinanceID=@FinanceID  '
										  
										  
	if @limitAType=1
	BEGIN
		SET @sqlFinance+=' INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) al ON b.FinanceID=al.FinanceID	'	
	END									  
	SET @sqlFinance+='	WHERE  b.SonNum=0  '
END		

SELECT   
		@sqlColumn='bill.BillNo 
					,'''+CAST(billTypeID as varchar)+''' as BillTypeID
					,bill.BillCode
					,bill.PosTime
					,bill.CreateTime
					,bill.BillDate
					,bill.Summary
					,bill.[Description]
					'
		,@sqlHisColumn='billH.BillNo 
					,'''+CAST(billTypeID as varchar)+''' as BillTypeID
					,billH.BillCode
					,billH.PosTime
					,billH.CreateTime
					,billH.BillDate
					,billH.Summary
					,billH.[Description]
					'					
					
					
		,@SqlBill+='UNION ALL
				SELECT '+@sqlColumn+'
				FROM '+tbName+' bill '	
											
		,@SqlBill+=' WHERE bill.BillDate BETWEEN @BillStartDate AND @BillEndDate   '+
						Case WHEN @ShowRed=0 THEN ' AND  bill.Red=0' ELSE ' ' END+
						CASE WHEN billTypeCount>1 THEN ' AND bill.BillTypeID='+CAST(billTypeID as varchar)+'' ELSE '' END 
						+' ' 
		,@SqlHis+='UNION ALL
				SELECT '+@sqlHisColumn+'
				FROM '+tbName+'_His billH '			
		,@SqlHis+=' WHERE billH.BillDate BETWEEN @BillStartDate AND @BillEndDate   '+
				Case WHEN @ShowRed=0 THEN ' AND  billH.Red=0' ELSE ' ' END+
				CASE WHEN billTypeCount>1 THEN ' AND billH.BillTypeID='+CAST(billTypeID as varchar)+'' ELSE '' END 
				+' ' 
	
FROM @billtypeTb





IF @isHistory=1
	SET @SqlBill=' BillData as ('+STUFF(Ltrim(@SqlBill+@SqlHis),1,9,'')+'),'
ELSE 
	SET @SqlBill=' BillData as ('+STUFF(Ltrim(@SqlBill),1,9,'')+'),'


---------------------------开始拼ListTable相关的Sql	,并分页
SET @sqlList=' ListData as ('

SET @sqlList+=' SELECT	l.LID
						,l.BillNO 
						,l.BillTypeID
						,l.FinanceID
						,l.JTotal
						,l.DTotal
						,l.BillDate
						,l.btypeid
						,l.DeptID
						,l.ElyID
						,l.Red
						,ftb.FinanceNo
						,ftb.FinanceName
						,ftb.LoanStt
				FROM PD_ListTable l '
if(@FinSonnum<=0)
BEGIN
	SET @sqlList+='	INNER JOIN BD_Finance ftb ON l.FinanceID=ftb.FinanceID'
END	


--IF @limitBType<>0 --有部分权限，全部权限时，才拼接传入的往来单位参数
--BEGIN		
	IF  @BtypeClassID<=0 AND @BtypeID<>'' 
		SET @sqlList+= ' INNER JOIN dbo.UF_OT_Split_Int(@BtypeID,'','') b ON b.typeid=l.btypeid'			
	ELSE IF  @BtypeClassID>0
		SET @sqlList+= ' INNER JOIN @bTb b ON b.typeid=l.btypeid'
	--IF @limitBType=1
	--	SET @sqlList+= ' INNER JOIN  dbo.UF_BD_BtypeLimit(@OperatorID) bl ON l.Btypeid=bl.BTypeID'
--END 
		

IF  @DeptID<>''
	SET @sqlList+= ' INNER JOIN @DTb d ON d.typeid=l.DeptID'		
		

IF   @ElyID<>'' 				
	SET @sqlList+= ' INNER JOIN dbo.UF_OT_Split_Int(@ElyID,'','') e ON e.typeid=l.ElyID'
	
IF @BillTypeID<>'0'		
	SET @sqlList+='  INNER JOIN  dbo.UF_OT_Split_Int(@billtype,'','') bt  ON bt.typeid=l.BillTypeID '	

IF @FinSonnum>0
	SET @sqlList+='  INNER JOIN  @financeTb ftb ON ftb.FinanceID=l.FinanceID '
	


if @limitAType=0  --无权限
BEGIN
	SET @sqlList+=' WHERE 1=0 '
END
ELSE 
BEGIN	
	SET @sqlList+='
					WHERE l.BillDate BETWEEN @BillStartDate AND @BillEndDate  '

	IF @ExPay<>0
		SET @sqlList+=' AND (l.ExPay=0)'				
	IF @ShowRed=0
		SET @sqlList+=' AND l.Red=0'		
	IF @FinSonnum<=0
		SET @sqlList+=' AND l.FinanceID=@FinanceID '	
		
END	
	
	
IF 	@isHistory=1 
BEGIN 	
	SET @sqlList+='
					UNION ALL
					 SELECT	l.LID
							,l.BillNO 
							,l.BillTypeID
							,l.FinanceID
							,l.JTotal
							,l.DTotal
							,l.BillDate
							,l.btypeid
							,l.DeptID
							,l.ElyID
							,l.Red
							,ftb.FinanceNo
							,ftb.FinanceName
							,ftb.LoanStt
					FROM PD_ListTable_His l '
	if(@FinSonnum<=0)
	BEGIN
		SET @sqlList+='	INNER JOIN BD_Finance ftb ON l.FinanceID=ftb.FinanceID'
	END	

	--IF @limitBType<>0 --有部分权限，全部权限时，才拼接传入的往来单位参数
	--BEGIN		
		IF  @BtypeClassID<=0 AND @BtypeID<>'' 
			SET @sqlList+= ' INNER JOIN dbo.UF_OT_Split_Int(@BtypeID,'','') b ON b.typeid=l.btypeid'			
		ELSE IF  @BtypeClassID>0
			SET @sqlList+= ' INNER JOIN @bTb b ON b.typeid=l.btypeid'
				
		--IF @limitBType=1
		--	SET @sqlList+= ' INNER JOIN  dbo.UF_BD_BtypeLimit(@OperatorID) bl ON l.Btypeid=bl.BTypeID'
					
	--END		

	IF  @DeptID<>''
		SET @sqlList+= ' INNER JOIN @DTb d ON d.typeid=l.DeptID'		
			

	IF   @ElyID<>'' 				
		SET @sqlList+= ' INNER JOIN dbo.UF_OT_Split_Int(@ElyID,'','') e ON e.typeid=l.ElyID'
		
	IF @BillTypeID<>'0'		
		SET @sqlList+='  INNER JOIN  dbo.UF_OT_Split_Int(@billtype,'','') bt  ON bt.typeid=l.BillTypeID '	

	IF @FinSonnum>0
		SET @sqlList+='  INNER JOIN  @financeTb ftb ON ftb.FinanceID=l.FinanceID '
		
	if @limitAType=0 --无权限
	BEGIN
			SET @sqlList+=' WHERE 1=0 '	
	END 
	ELSE 
	BEGIN	
		SET @sqlList+='
						WHERE l.BillDate BETWEEN @BillStartDate AND @BillEndDate  '

		IF @ShowRed=0
			SET @sqlList+=' AND l.Red=0'
		IF @ExPay<>0
			SET @sqlList+=' AND (l.ExPay=0)'			
		IF @FinSonnum<=0
			SET @sqlList+=' AND l.FinanceID=@FinanceID '	
	END
	
END	

SET @sqlList+=' ) '


--SET @sqlList+='	,BeforeTotalDATA AS (
--							 SELECT SUM(CASE WHEN loanStt>0 THEN JTotal ELSE DTotal END - CASE WHEN loanStt>0 THEN DTotal ELSE Jtotal END ) as OverTotal
--							 FROM (
									
--									SELECT	ROW_NUMBER() OVER( ORDER BY  billDate) AS ROWID
--										,JTotal
--										,DTotal
--										,loanStt
--									FROM ListData 			
--									) B
--							WHERE B.ROWID>0 AND B.ROWID<=(@PageNo-1)*@PageSize ) '



SET @sqlList+=',DATA AS ('
IF @pageNo<=1 
		SET @sqlList+='		SELECT * FROM (  SELECT COUNT(1) AS ''ROWCOUNT'',0 as  OverTotal FROM ListData'
ELSE 
BEGIN 
SET @sqlList+='							
							SELECT* FROM (
										 SELECT SUM(rowsc ) as ''ROWCOUNT'',sum(OverTotal) as   OverTotal
										  FROM (
													 SELECT COUNT(1) AS rowsc,0 as  OverTotal FROM ListData
													-- UNION ALL 
													-- SELECT 0 as  rowsc,  OverTotal FROM  BeforeTotalDATA
										 
										 )AD '
										 
										 
END 										 
SET @sqlList+='				) A
							CROSS JOIN
							(
								SELECT	ROW_NUMBER() OVER( ORDER BY  billDate) AS ROWID,* FROM ListData '
								
								
SET @sqlList+= '			) B
							WHERE B.ROWID>(@PageNo-1)*@PageSize AND B.ROWID<=@PageNo*@PageSize )
					SELECT	d.LID
							,d.FinanceID
							,d.loanStt
							,CASE WHEN d.loanStt>0 THEN d.JTotal ELSE d.DTotal END  as AddTotal   
							,CASE WHEN d.loanStt>0 THEN d.DTotal ELSE d.Jtotal END  as MinusTotal  
							,d.BtypeID
							,d.DeptID
							,d.ElyID
							,d.[ROWCOUNT]
							,d.Red
							, b.*
							,d.FinanceNo
							,d.FinanceName
							,be.ElyCode
							,be.ElyName'
							
if @limitBType=1
	SET @sqlList+= '        ,(CASE WHEN bl.Btypeid>0 OR d.btypeid=0 THEN  bb.BTypeCode  ELSE ''******'' END)  as  BTypeCode
							,(CASE WHEN bl.Btypeid>0  OR d.btypeid=0 THEN  bb.BTypeName  ELSE ''******'' END)  as  BTypeName '								
ELSE IF 	 @limitBType=0
	SET @sqlList+= '			,''******'' as BTypeCode
								,''******'' as BTypeName'
								
ELSE 
	SET @sqlList+= '			,bb.BTypeCode
								,bb.BTypeName'							
							
							
SET @sqlList+= '			,bd.DeptCode
							,bd.DeptName
							,bt.BillName
							,d.OverTotal'					
SET @sqlList+= '	FROM Data d 
								INNER JOIN BillData b ON  d.BillNO=b.BillNo AND d.BillTypeID=b.BillTypeID
								INNER JOIN pd_BillType bt On Bt.BillTypeID=d.BillTypeID '
								
if @limitBType=1								
	SET @sqlList+= '			LEFT JOIN  dbo.UF_BD_BtypeLimit(@OperatorID) bl ON d.Btypeid=bl.BTypeID '
								
SET @sqlList+= '				LEFT JOIN BD_Employee be ON d.ElyID=be.ElyID
								LEFT JOIN BD_Btype bb ON d.BtypeID=bb.btypeid
								LEFT JOIN BD_Dept bd ON d.DeptID=bd.DeptID
							ORDER BY  d.BillTypeID asc,d.billDate asc,b.PosTime  asc,d.financeid  asc '


-------------------------------------此前余额---------------------------------INNER JOIN  dbo.UF_BD_BtypeLimit(@OperatorID) bl ON l.Btypeid=bl.BTypeID

DECLARE @Sqloldparams nvarchar(max)

	SET @Sqloldparams=''
	SET @Sqlold+='  SELECT ' 
  

IF @isBeforeTotal=2
	SET @Sqlold+=' ISNULL(sum(CASE WHEN bf.loanStt>0 THEN pl.JTotal ELSE pl.DTotal END),0) as JSummaryTotal
				   ,ISNULL(sum(CASE WHEN bf.loanStt>0 THEN pl.DTotal ELSE pl.Jtotal END),0) as DSummaryTotal '
else 
	SET @Sqlold+='  ISNULL(sum((pl.JTotal-pl.DTotal)*bf.LoanStt),0) as BeforeTotal' 
	
	
SET @Sqlold+=' FROM ( 
						SELECT JTotal,Dtotal,FinanceID,btypeid,Elyid,BillTypeID,DeptID,BillDate  FROM   PD_ListTable pl '	
IF @isHistory=1
BEGIN						
	SET @Sqlold+=' 
							UNION ALL 
							SELECT JTotal,Dtotal,FinanceID,btypeid,Elyid,BillTypeID,DeptID,BillDate  FROM   PD_ListTable_His pl '
END
				
SET @Sqlold+=' 
				)pl INNER JOIN BD_Finance bf   On pl.FinanceID=bf.FinanceID	 '
						
						
						
IF @FinSonnum>0
	SET @Sqlold+='		INNER JOIN  @financeTb ftb ON ftb.FinanceID=pl.FinanceID '

--IF @limitBType<>0 --有部分权限，全部权限时，才拼接传入的往来单位参数
--BEGIN			
	IF  @BtypeClassID<=0 AND @BtypeID<>'' 
		SET @Sqlold+= ' INNER JOIN dbo.UF_OT_Split_Int(@BtypeID,'','') b ON b.typeid=pl.btypeid'			
	ELSE IF  @BtypeClassID>0
		SET @Sqlold+= ' INNER JOIN @bTb b ON b.typeid=pl.btypeid'	
				
--	IF @limitBType=1
--		SET @Sqlold+= ' INNER JOIN  dbo.UF_BD_BtypeLimit(@OperatorID) bl ON pl.Btypeid=bl.BTypeID'

--END
		
IF  @DeptID<>'' 
	SET @Sqlold+= ' INNER JOIN @DTb d ON d.typeid=pl.DeptID'		
			
IF   @ElyID<>'' 				
	SET @Sqlold+= ' INNER JOIN dbo.UF_OT_Split_Int(@ElyID,'','') e ON e.typeid=pl.ElyID'
	
IF @BillTypeID<>'0'		
	SET @Sqlold+='  INNER JOIN  dbo.UF_OT_Split_Int(@billtype,'','') bt  ON bt.typeid=pl.BillTypeID '		
				
if(@isBeforeTotal=1)				
	SET @Sqlold+=' where   pl.BillDate <@BillStartDate  '
else if(@isBeforeTotal=2)					
	SET @Sqlold+=' where   pl.BillDate  BETWEEN @BillStartDate AND @BillEndDate  '

IF @FinSonnum<=0
	SET @Sqlold+=' AND pl.FinanceID=@FinanceID '	
	

	
	


DECLARE @pageSql nvarchar(max)
SET @pageSql=''
SET @pageSql+= @DSql+@BSql
if(@isBeforeTotal=1 OR @isBeforeTotal=2)						
	SET @pageSql +=@sqlFinance+@Sqlold
ELSE
	SET @pageSql +=@sqlFinance+';With  '+@SqlBill+@sqlList


DECLARE @ParmDefinition nvarchar(500);
SET @ParmDefinition = N'@billtype		Nvarchar(700)
						,@FinanceID		int
						,@BillStartDate DATE
						,@BillEndDate	DATE
						,@BtypeID		VARCHAR(1000)
						,@DeptID		VARCHAR(1000)
						,@ElyID			VARCHAR(1000)
						,@PageNo		INT
						,@PageSize		INT
						,@BtypeTypeID   INT 
						,@OperatorID	INT
						'


EXEC sp_executesql @pageSql,@ParmDefinition,@billtype=@BillTypeID		
											,@FinanceID	=	@FinanceID
											,@BillStartDate =@BillStartDate 
											,@BillEndDate=	@BillEndDate
											,@BtypeID	=	@BtypeID
											,@DeptID=		@DeptID
											,@ElyID =@ElyID			
											,@PageNo =@PageNo	
											,@PageSize=	@PageSize
											,@BtypeTypeID=@BtypeClassID
											,@OperatorID=@OperatorID	


-----以下是print 的内容
--DECLARE @curPos INT = 1 , @count INT = 1
-- WHILE (@curPos < len(@pageSql))  
--	 BEGIN  
--		 PRINT substring(@pageSql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END   
 
 
GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：李文博
	日期：2014-08-01
	描述：项目对比查询[转换列数据]
-------------------------------------------*/
CREATE PROCEDURE UP_MF_FinanceHistory
(
	@FinanceID VARCHAR(MAX),
	@Period VARCHAR(MAX),
	@OperatorID INT=1,
	@ComContent TINYINT
)

AS
DECLARE @sql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = '', @TableSql NVARCHAR(MAX) = '', @WhereSql NVARCHAR(MAX) = ''
DECLARE @selectSql NVARCHAR(MAX) = '', @InSql NVARCHAR(MAX) = '', @TotalCol NVARCHAR(MAX) = '', @dtCol NVARCHAR(MAX) = ''
DECLARE @colSql NVARCHAR(MAX) = '', @leftSql NVARCHAR(MAX)= '', @ThisPeriod INT, @SumCol NVARCHAR(MAX) = '', @LimitSql NVARCHAR(MAX) = ''

SELECT @ThisPeriod = Period FROM SS_MonthProc WHERE Name = '本期'

IF dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 0
BEGIN
	SET @WhereSql = ' AND 1=2 '
END ELSE
IF dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 1
BEGIN
	SET @LimitSql += ' INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) al ON bf.FinanceID=al.FinanceID '
	SET @TableSql += ' INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) al ON bf.FinanceID=al.FinanceID '
END 

IF @FinanceID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @Atype Table(FinanceID INT)   
     INSERT  INTO @Atype SELECT typeid AS FinanceID  FROM dbo.UF_OT_Split_Int(@FinanceID,'','')   
     '  
 SET @TableSql+=' INNER JOIN @Atype A ON bf.FinanceID=A.FinanceID ' 
END

SELECT @selectSql = 'SELECT FinanceID'

DECLARE	@Count INT = 0, @i INT = 1, @P VARCHAR(10) = '', @PeriodName VARCHAR(50) = ''
DECLARE @soure TABLE (rowIndex INT IDENTITY,Period INT)
IF @Period <> ''
BEGIN
	INSERT INTO @soure
	SELECT typeid AS Period FROM dbo.UF_OT_Split_Int(@Period,',')
END ELSE
BEGIN
	INSERT INTO @soure
	SELECT 99999 AS Period
	UNION ALL
	SELECT Period FROM SS_MonthProc
END 
IF @ComContent = 0	SET @TotalCol = 'BqTotal' ELSE SET @TotalCol = 'Total'

IF EXISTS(SELECT 1 FROM @soure WHERE Period <> 99999 AND Period <> @ThisPeriod)
BEGIN
	SELECT @Count = COUNT(1) FROM @soure
	WHILE @i <= @Count
	BEGIN
		SELECT @P = CONVERT(VARCHAR(10),Period) FROM @soure WHERE rowIndex = @i
		SELECT @PeriodName = Name FROM SS_MonthProc WHERE Period = CONVERT(INT, @P)
		IF (@P = CONVERT(VARCHAR(10), @ThisPeriod)) OR (@P = '99999')
		BEGIN
			SET @i = @i+1
			CONTINUE
		END
		SET @selectSql += ' ,' + ' ['+ @P + '] AS Total'+ @P
		SET @SumCol += ', SUM(Total'+ @P +') AS Total'+ @P
		SET @dtCol += ', Total'+ @P+ ' AS '''+ @PeriodName +''' '
		SET @colSql += ', Total'+ @P
		SET @InSql += ', '+ '['+@P+']'
		SET @i = @i+1
	END
	SET @InSql = STUFF(@InSql,1,1,'')
	SET @leftSql += 'LEFT JOIN
		(
		'+@selectSql + 
			' FROM 
			(SELECT FinanceID, Period, CONVERT(FLOAT,'+ @TotalCol +') AS Total FROM SS_MonthBalance)  AS SourceData
			PIVOT (MAX(Total) FOR SourceData.Period IN ('+ @InSql +')) AS A
		) TbTotal ON bf.FinanceID = TbTotal.FinanceID '
END

IF EXISTS(SELECT 1 FROM @soure WHERE Period = 99999 OR Period = @ThisPeriod)
BEGIN
	IF @ComContent = 0 --发生额
	BEGIN
		IF EXISTS(SELECT 1 FROM SS_MonthBalance) --存在结存期间
		BEGIN
			SET @leftSql +=' LEFT JOIN 
			(SELECT bf.FinanceID, CONVERT(FLOAT, ISNULL(QcBalances, 0)) AS Total99999, 
			ISNULL(QmBalances, 0) - ISNULL(fun.Total, 0) AS Total'+CONVERT(VARCHAR(10), @ThisPeriod)+' FROM BD_Finance bf 
			LEFT JOIN (SELECT FinanceID, Total FROM SS_MonthBalance WHERE Period = '+ CONVERT(VARCHAR(10),@ThisPeriod-1) + ' )fun ON bf.FinanceID = fun.FinanceID
			LEFT JOIN BD_Funds fd ON  bf.FinanceID = fd.FinanceID 
			WHERE ISNULL(QmBalances, 0) - ISNULL(fun.Total, 0) <> 0 OR ISNULL(QcBalances,0) <> 0) fun
			ON bf.FinanceID = fun.FinanceID
			'
		END ELSE
		BEGIN
			SET @leftSql +=' LEFT JOIN 
			(SELECT FinanceID, CONVERT(FLOAT, QcBalances) AS Total99999, CONVERT(FLOAT, QmBalances-QcBalances) AS Total'+CONVERT(VARCHAR(10),@ThisPeriod)+' FROM BD_Funds )fun
			ON bf.FinanceID = fun.FinanceID
			'
		END
	END ELSE
	BEGIN
		SET @leftSql +=' LEFT JOIN 
		( SELECT FinanceID, CONVERT(FLOAT, QcBalances) AS Total99999, CONVERT(FLOAT, QmBalances) AS Total'+CONVERT(VARCHAR(10),@ThisPeriod)+' FROM BD_Funds)fun
		ON bf.FinanceID = fun.FinanceID
		'
	END
	IF EXISTS(SELECT 1 FROM @soure WHERE Period = 99999)
	BEGIN
		SET @colSql =', Total99999 '+@colSql
		SET @SumCol =', SUM(Total99999) AS Total99999 '+ @SumCol
		SET @dtCol = ', Total99999 AS ''期初'' '+ @dtCol
	END
	IF EXISTS(SELECT 1 FROM @soure WHERE Period = @ThisPeriod)
	BEGIN
		SET @colSql +=', Total'+CONVERT(VARCHAR(5),@ThisPeriod)+' '
		SET @SumCol += ', SUM(Total'+CONVERT(VARCHAR(5),@ThisPeriod) +') AS Total'+CONVERT(VARCHAR(5),@ThisPeriod)
		SET @dtCol += ', Total'+CONVERT(VARCHAR(5),@ThisPeriod)+ ' AS ''本期'''
	END
		
	
END

SET @sql += @CreateTableSql+ '
;WITH fData AS ( 
SELECT	bf.Path
		'+ @colSql +'
	FROM BD_Finance bf
	'+ @LimitSql +'
	'+ @leftSql +'
WHERE bf.FinanceID <> 1 AND bf.SonNum = 0 '+ @WhereSql +')


SELECT	bf.FinanceName, 
		dbo.UF_OT_StringReplace(bf.Lvl,2)+bf.[FinanceNO] AS FinanceCode
		'+ @dtCol +'
FROM BD_Finance bf
'+ @TableSql +' 
LEFT JOIN (
SELECT LEFT(Path,5) AS Path '+ @SumCol +' FROM fData WHERE LEN(Path)>5 GROUP BY LEFT(Path,5) 
UNION ALL
SELECT LEFT(Path,10) AS Path '+ @SumCol +' FROM fData WHERE LEN(Path)>10 GROUP BY LEFT(Path,10)
UNION ALL
SELECT LEFT(Path,15) AS Path '+ @SumCol +' FROM fData WHERE LEN(Path)>15 GROUP BY LEFT(Path,15)
UNION ALL
SELECT LEFT(Path,20) AS Path '+ @SumCol +' FROM fData WHERE LEN(Path)>20 GROUP BY LEFT(Path,20)
UNION ALL
SELECT * FROM fData
) HisTable ON bf.Path = HisTable.Path
WHERE bf.FinanceID <> 1 '+ @WhereSql +' ORDER BY bf.PATH
'
--PRINT(@sql)
EXEC sp_executesql @sql,N'@FinanceID VARCHAR(MAX), @OperatorID INT',@FinanceID, @OperatorID
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_MF_MoneyDistributedQuery]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_MoneyDistributedQuery]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*------------------------------------------
    作者：wwei
	日期：2014-07-29
	描述：费用分布表
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_MoneyDistributedQuery]
(			   
	 @columnPageIndex INT=1					--横向页码
	,@columnPageSize INT=10				--横向分页数
	,@BillDateType INT=1				--单据日期类型:1=录单日期,2=制单日期,3=过账日期  对应BillDate,CreateTime,PosTime
	,@BillStartDate DATE			--单据开始日期
	,@BillEndDate DATE				--单据结束日期
	,@BtypeID VARCHAR(1000) = ''	--往来单位
	,@DeptID VARCHAR(1000) = ''		--部门
	,@ElyID VARCHAR(1000) = ''		--经手人
	,@Summary int=0    --0=职员，1=部门，2=往来单位
	,@isHistory INT =0    ---是否包含历史数据
	,@ColumnCount int Output
	,@OperatorID INT 
	
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@isHistory=@isHistory
if( @re=1 )return @re;

DECLARE @isALL INT =0
SELECT @isALL=dbo.UF_BD_IsAllAtypeLimit(@OperatorID) --是否所有权限


--------------------------------------以上是关联相应的基础分布数据---------------------------------------------------------

Create Table  #ItemsFinance(FinanceID int, FinanceName nvarchar(300),FinanceCode varchar(200),[Path] varchar(80),sonnum int)


DECLARE  @sqlf Nvarchar(max)
SET @sqlf='
INSERT INTO #ItemsFinance(FinanceID,FinanceName,FinanceCode,[Path],sonnum)
SELECT fc.FinanceID
		,fc.FinanceName 
		,(dbo.UF_OT_StringReplace(fc.Lvl,2)+fc.[FinanceNO]) as FinanceCode
		,fc.[Path]
		,fc.sonnum
FROM BD_Finance f '


SET @sqlf+= ' INNER JOIN BD_Finance fc ON fc.[Path] like f.[Path]+''%'' '

if @isALL=1
	SET @sqlf+=' INNER JOIN dbo.UF_BD_AtypeLimit('+CAST(@OperatorID as nvarchar)+') al ON fc.FinanceID=al.FinanceID '
	
if @isALL=0
	SET @sqlf+=' where  1=0'	
ELSE 
	SET @sqlf+=' where  f.FinanceID=13 AND f.Stt=1 '	

execute sys.sp_executesql @sqlf

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

if(@columnPageIndex<=0)set @columnPageIndex=1

DECLARE @GroupCol Nvarchar(max)
SET @GroupCol=''
if @Summary=0 
	SET @GroupCol+=' l.ElyID '			
else if @Summary=1 
	SET @GroupCol+='l.DeptID '
else 
	SET @GroupCol+=' l.BtypeID  '



Create TABLE #SummaryTb(ID INT,Name varchar(100),colCount  INT )



IF @Summary=0  
BEGIN
	DECLARE @elySql  nvarchar(max)
	SET @elySql='
					;WITH PageData as (
						SELECT e.ElyID,e.ElyName+''（''+e.ElyCode+''）'' as name ,ROW_NUMBER()OVER(order by e.ElyName) as rowNumber 
						FROM BD_Employee e
							 INNER JOIN (
									SELECT  l.ElyID 
									FROM PD_ListTable l 
											INNER JOIN #ItemsFinance f ON l.FinanceID=f.FinanceID
									group by l.ElyID '
	if(@isHistory=1)
	BEGIN
		SET @elySql+='			UNION
								SELECT  h.ElyID 
								FROM PD_ListTable_his h
										INNER JOIN #ItemsFinance f ON h.FinanceID=f.FinanceID
								group by h.ElyID '
	END
							
	SET @elySql+='						) el ON e. ElyID=el.ElyID 
							 							 
						 WHERE  ( exists (SELECT * FROM dbo.UF_OT_Split_Int(@ElyID,'','') s WHERE s.typeid=e.elyid ) OR @ElyID='''' ) 
								AND e.ElyID<>1 
					)	
					,columnCount as ( 
											SELECT * FROM (SELECT COUNT(1) AS ColCount FROM PageData) A
											 CROSS JOIN(
															SELECT ElyID,name FROM  PageData  A 
															WHERE  A.rowNumber>(@columnPageIndex-1)*@columnPageSize  AND A.rowNumber<=@columnPageIndex*@columnPageSize     
														)B 
								
										)
						INSERT INTO #SummaryTb(colCount,id,Name) SELECT ColCount,ElyID,name  FROM 	columnCount		
				 '
				 
	
	EXEC sp_executesql  @elySql,N' @ElyID nvarchar(MAX),@columnPageIndex INT ,@columnPageSize INT '
						,@ElyID=@ElyID
						,@columnPageIndex=@columnPageIndex
						,@columnPageSize=@columnPageSize
END 
ELSE IF  @Summary =1 
BEGIN
	DECLARE @bmSql nvarchar(max)	
	SET @bmSql=''
	SET @bmSql+=' ;WITH PageData as ( '
	
					

	IF (@DeptID<>'')
	BEGIN	
		SET @bmSql+='	SELECT e.DeptID,e.DeptName+''（''+e.DeptCode+''）''  as name ,ROW_NUMBER()OVER(order by e.DeptName) as rowNumber
						FROM  BD_Dept d 
						INNER JOIN   dbo.UF_OT_Split_Int(@DeptID,'','') s ON d.DeptID=s.typeid
						INNER JOIN  BD_Dept  e ON e.[Path] like d.[Path]+''%''		 
					'
	END
	ELSE
	BEGIN 
		SET @bmSql+='	SELECT e.DeptID,e.DeptName+''（''+e.DeptCode+''）''  as name ,ROW_NUMBER()OVER(order by e.DeptName) as rowNumber
						FROM  BD_Dept e 
					'
	END
	
	SET @bmSql+='		INNER JOIN (
							SELECT  l.DeptID 
							FROM PD_ListTable l
								INNER JOIN #ItemsFinance f ON l.FinanceID=f.FinanceID
							group by l.DeptID '				
	if(@isHistory=1)
		SET @bmSql+='		UNION
							SELECT  l.DeptID 
							FROM PD_ListTable_his l
									INNER JOIN #ItemsFinance f ON l.FinanceID=f.FinanceID
							group by l.DeptID '

	SET @bmSql+='				) el ON e.DeptID=el.DeptID '


	SET @bmSql+='		 WHERE e.SonNum=0
					 ),columnCount as ( 
									SELECT * FROM (SELECT COUNT(1) AS ColCount FROM PageData) A
									 CROSS JOIN(
													SELECT DeptID,name FROM  PageData  A 
													WHERE  A.rowNumber>(@columnPageIndex-1)*@columnPageSize  AND A.rowNumber<=@columnPageIndex*@columnPageSize     
												)B 
								) '
	SET @bmSql+='	INSERT INTO #SummaryTb(colCount,id,Name) SELECT ColCount,DeptID,name  FROM 	columnCount	'	
	
	EXEC sp_executesql  @bmSql,N' @DeptID nvarchar(MAX),@columnPageIndex INT ,@columnPageSize INT '
						,@DeptID=@DeptID
						,@columnPageIndex=@columnPageIndex
						,@columnPageSize=@columnPageSize

	
END
ELSE 
BEGIN
	DECLARE @BSql  nvarchar(max)
	
	SET @BSql='
	;WITH PageData as (
		SELECT e.BTypeID,e.BTypeName+''（''+e.BTypeCode+''）'' as name ,ROW_NUMBER()OVER(order by e.BTypeName) as rowNumber
		FROM BD_Btype e
			 INNER JOIN (
							SELECT  l.BTypeID 
							FROM PD_ListTable l
								INNER JOIN #ItemsFinance f ON l.FinanceID=f.FinanceID
							group by l.BTypeID '

	if(@isHistory=1)
	BEGIN
		SET @BSql+='		UNION
							SELECT  l.BTypeID 
							FROM PD_ListTable_his l
								INNER JOIN #ItemsFinance f ON l.FinanceID=f.FinanceID
							group by l.BTypeID '
	END
		
	SET @BSql+='			) el ON e. BTypeID=el.BTypeID 	 
		WHERE  (exists (SELECT * FROM dbo.UF_OT_Split_Int(@BtypeID,'','') s WHERE s.typeid=e.BTypeID ) OR @BtypeID='''' ) 
	)
	,columnCount as ( 
						SELECT * FROM (SELECT COUNT(1) AS ColCount FROM PageData) A
						 CROSS JOIN(
										SELECT BTypeID,name FROM  PageData  A 
										WHERE  A.rowNumber>(@columnPageIndex-1)*@columnPageSize  AND A.rowNumber<=@columnPageIndex*@columnPageSize     
									)B 
			
					)
	INSERT INTO #SummaryTb(colCount,id,Name) SELECT ColCount,BTypeID,name  FROM 	columnCount		'
	EXEC sp_executesql  @BSql,N' @BtypeID nvarchar(MAX),@columnPageIndex INT ,@columnPageSize INT '
						,@BtypeID=@BtypeID
						,@columnPageIndex=@columnPageIndex
						,@columnPageSize=@columnPageSize

	
	
	
END

if EXISTS (SELECT 1 FROM #SummaryTb)
BEGIN
	SELECT  TOP 1 @ColumnCount= colCount FROM #SummaryTb
END
ELSE 
	SELECT @ColumnCount=0

if(@Summary=2) SET @ColumnCount=@ColumnCount+1

--------------------------------------以上是关联相应的财务数据---------------------------------------------------------
--DROP TABLE ##ItemsFinance
-- DROP TABLE ##SummaryTb
--SELECT * INTO ##ItemsFinance FROM #ItemsFinance
--SELECT * INTO ##SummaryTb FROM #SummaryTb

---开始拼条件

DECLARE @sqlParams nvarchar(Max),@sql nvarchar(MAX),@SqlSum nvarchar(max)
SELECT @sql='',@SqlSum='', @sqlParams=' '


IF(@BtypeID<>'')
BEGIN
	SET @sqlParams +='  INNER JOIN dbo.UF_OT_Split_Int(@BtypeID,'','') utb  ON utb.typeid=l.BtypeID  '
END


IF(@DeptID<>'' )
BEGIN
	if exists (select 1 from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#DeptTb') and type='U') 
		DROP TABLE #DeptTb	
		
	CREATE table #DeptTb(typeid INT)

	EXEC sp_executesql  N';WITH PageData as (
									SELECT e.DeptID
									FROM  BD_Dept d  
									INNER JOIN   dbo.UF_OT_Split_Int(@DeptID,'','') s ON d.DeptID=s.typeid
									INNER JOIN  BD_Dept  e ON e.[Path] like d.[Path]+''%''
									WHERE e.SonNum=0 		 
							)INSERT INTO  #DeptTb(typeid)SELECT DeptID FROM  PageData	'
			
						,N' @DeptID nvarchar(1000)'
						,@DeptID=@DeptID

	SET @sqlParams +=' INNER JOIN #DeptTb utd   ON utd.typeid=l.DeptID  '

END

IF(@ElyID<>'')
BEGIN
	SET @sqlParams +='  INNER JOIN dbo.UF_OT_Split_Int(@ElyID,'','') ute  ON ute.typeid=l.ElyID '
END



--------------------------------------以下:费用所属项目的明细---------------------------------------------------------
DECLARE @s NVARCHAR(MAX) ,@ColumnSql nvarchar(MAX),@OtherSql nvarchar(MAX) 
SELECT  @ColumnSql='',@OtherSql=''
SELECT 
		@s = ISNULL(@s + ',', '') +  QUOTENAME(A.ID)  
		,@ColumnSql+=',SUM(ISNULL('+CAST( QUOTENAME(A.ID) as varchar) +',0)) as ['+A.Name+']'
		--,@OtherSql+='-SUM(ISNULL('+CAST( QUOTENAME(A.ID) as varchar) +',0))'
FROM #SummaryTb A ---列名不要重复  
 
SET @s=ISNULL(@s + ',', '') +  QUOTENAME('-99999')  

if (@BtypeID='' AND  @Summary=2)
	SET @s=ISNULL(@s + ',', '') +  QUOTENAME('-11111')  

SET  @ColumnSql+=',SUM(ISNULL('+CAST( QUOTENAME('-99999') as varchar) +',0)) as [合计]'

if (@BtypeID='' AND  @Summary=2)
	SET  @OtherSql=',(SUM(ISNULL('+CAST( QUOTENAME('-11111') as varchar) +',0)) '+@OtherSql+') as [其他]'



SET @sql+='; with UserData as ('





SET @sql+='SELECT		
					SUM(l.Jtotal-l.Dtotal) as total
					,FinanceID
					,[Path]
					,ID
			FROM ( 	'

SET @sql+='
			SELECT		 l.Dtotal
						,l.Jtotal 
						,l.FinanceID
						,itf.[Path] 
						,' +@GroupCol +' as ID'
						
SET @sql+='	FROM  pd_ListTable l   '		
SET @sql+='	INNER JOIN #ItemsFinance  itf ON l. FinanceID=itf.FinanceID' 	

SET @sql+= @sqlParams  

SET @sql+=' WHERE  (l.BillDate BETWEEN @BillStartDate  AND @BillEndDate)  AND  itf.sonnum=0 '


IF @isHistory=1
BEGIN
	SET @sql+='  UNION ALL  SELECT	
							 l.Dtotal
							,l.Jtotal
							,l.FinanceID
							,itf.[Path] 
							,' +@GroupCol +' as ID'
							
	SET @sql+='	FROM  pd_ListTable_His l   '		
	SET @sql+='	INNER JOIN #ItemsFinance  itf ON l. FinanceID=itf.FinanceID' 	
	SET @sql+= @sqlParams  
	SET @sql+=' WHERE  (l.BillDate BETWEEN @BillStartDate  AND @BillEndDate)  AND  itf.sonnum=0 '
END 
	SET @sql+=' ) l'
	SET @sql+=' Group BY l.FinanceID ,l.[Path],l.ID'

SET @sql+=')'
SET @sql+='		, FinanceData as ( SELECT sum(total) as sumTotal,FinanceID,[Path] FROM UserData u  group by FinanceID, [Path]) ' 

if @Summary=2 AND  @BtypeID=''
	SET @sql+='	, BOtherData as ( SELECT sum(total) as sumTotal,FinanceID,[Path] FROM UserData u WHERE ID=0  group by FinanceID, [Path]) ' 


SET @sql+='  SELECT  i.FinanceID,i.FinanceCode,i.FinanceName '

if @Summary=2 AND @BtypeID=''
	SET @sql+= @OtherSql

SET @sql+=@ColumnSql+'
					FROM #ItemsFinance  i
							 LEFT JOIN (
										 select r.* from  (select u.total,u.ID,u.FinanceID,u.[path] from UserData  u  INNER JOIN #SummaryTb stb ON stb.ID=u.ID
															UNION ALL
															SELECT sumTotal as total ,''-99999'' as ID,FinanceID,[Path] FROM  FinanceData'
if @Summary=2 	 AND @BtypeID=''														
	SET @sql+='												 UNION ALL 
															SELECT sumTotal as total ,''-11111'' as ID,FinanceID,[Path] FROM  BOtherData '									
	
SET @sql+='													) as t  
											pivot  (  sum(t.total) for t.ID in ('+@s+')  ) as r
										) b ON b.[path] like i.path+''%''
									
					group by i.FinanceID,i.FinanceCode,i.FinanceName '     

					
EXEC sp_executesql  @sql,N' @BillStartDate date, @BillEndDate date, @DeptID varchar(1000),@BtypeID varchar(1000),@ElyID varchar(1000)'
,@BillEndDate=@BillEndDate
,@BillStartDate=@BillStartDate
,@BtypeID=@BtypeID
,@DeptID=@DeptID
,@ElyID=@ElyID


if exists (select 1 from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#DeptTb') and type='U')
BEGIN 
	DROP TABLE #DeptTb
END 
---删除临时表
DROP TABLE #SummaryTb,#ItemsFinance

GO







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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：hanlin
	日期：2014-7-28
	描述：经营利润表
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_OperatingProfitQuery]
(
	@Period INT=0,
	@StartDate DATE,
	@EndDate DATE,
	@Type INT,	--0=按时间查询 1=按期间查询
	@IsHistory INT=0
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(max),@Ret INT=0

EXEC @ret= UP_OT_CheckHistoryTime  @BillStartDate=@StartDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN
	
IF @Type=1 AND  EXISTS(SELECT 1 FROM SS_MonthProc WHERE Name='本期' AND Period=@Period)
BEGIN
	SET @Type=0
	SELECT @StartDate=StartDate FROM SS_MonthProc WHERE Period= @Period
	SELECT @EndDate=GETDATE()
END
IF @Type=0 
BEGIN
	SET @Sql='
		if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
		SELECT	fc.FinanceID,
			ParID,
			Path,
			SUM(b.Total)Total,
			SUM(b.BQTotal) BQTotal
		INTO #ExpenditureData
		FROM BD_Finance fc
		INNER JOIN
		(
			SELECT l.FinanceID,SUM(JTotal-DTotal)*LoanStt AS BQTotal,0 AS Total FROM PD_ListTable l INNER JOIN BD_Finance f ON f.FinanceID=l.FinanceID WHERE  BillDate>=@StartDate AND BillDate<=@EndDate	AND Red=0 GROUP BY l.FinanceID,LoanStt
			UNION ALL
			SELECT FinanceID,0 AS BQTotal,QcBalances AS Total  FROM BD_Funds
			UNION ALL
			SELECT l.FinanceID,0 AS BQTotal ,SUM(JTotal-DTotal)*LoanStt AS Total FROM PD_ListTable l INNER JOIN BD_Finance f ON f.FinanceID=l.FinanceID WHERE BillDate<=@EndDate	AND Red=0 GROUP BY l.FinanceID,LoanStt 
			UNION ALL
			SELECT l.FinanceID,0 AS BQTotal ,SUM(JTotal-DTotal)*LoanStt AS Total FROM PD_ListTable_His l INNER JOIN BD_Finance f ON f.FinanceID=l.FinanceID WHERE BillDate<=@EndDate	AND Red=0 GROUP BY l.FinanceID,LoanStt 	'
IF @IsHistory=1
	SET @Sql+='
		UNION ALL
		SELECT l.FinanceID,SUM(JTotal-DTotal)*LoanStt AS BQTotal,0 AS Total FROM PD_ListTable_His l INNER JOIN BD_Finance f ON f.FinanceID=l.FinanceID WHERE  BillDate>=@StartDate AND BillDate<=@EndDate	AND Red=0 GROUP BY l.FinanceID,LoanStt	'
SET @sql+='
		)b ON fc.FinanceID = b.FinanceID
		WHERE (Path LIKE ''00002%'' OR Path LIKE ''00003%'') AND SonNum=0 
		GROUP BY fc.FinanceID,ParID,Path'
END
ELSE --历史记录 
BEGIN
IF @Period=99999
	SET @Sql='
		;WITH FinanceData AS
		(
			SELECT	fc.FinanceID,
					ParID,
					Path,
					b.QcBalances As Total,
					b.QcBalances AS BqTotal
			FROM BD_Finance fc
			INNER JOIN BD_Funds b ON fc.FinanceID = b.FinanceID
			WHERE  (Path LIKE ''00002%'' OR Path LIKE ''00003%'') AND lvl>1 AND SonNum=0
		)
		'
ELSE IF @Period=0
	SET @Sql='
		if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
		SELECT	fc.FinanceID,
			ParID,
			Path,
			SUM(b.Total)Total,
			SUM(b.BQTotal) BQTotal
		INTO #ExpenditureData
		FROM BD_Finance fc
		INNER JOIN
		(
			SELECT FinanceID,SUM(JTotal-DTotal) AS BQTotal,0 AS Total  FROM PD_ListTable WHERE  BillDate>=@StartDate	AND Red=0 GROUP BY FinanceID
			UNION ALL
			SELECT FinanceID,0 AS BQTotal,QmBalances AS Total  FROM BD_Funds
		)b ON fc.FinanceID = b.FinanceID
		WHERE  (Path LIKE ''00002%'' OR Path LIKE ''00003%'') AND lvl>1 AND SonNum=0 
		GROUP BY fc.FinanceID,ParID,Path'
ELSE 
	SET @sql='
	;WITH FinanceData AS
	(
		SELECT	fc.FinanceID,
				ParID,
				Path,
				b.Total,
				b.BQTotal
		FROM BD_Finance fc
		INNER JOIN SS_MonthBalance b ON fc.FinanceID = b.FinanceID
		WHERE (Path LIKE ''00002%'' OR Path LIKE ''00003%'') AND  SonNum=0 AND b.Period=@Period
	)'
END
SET @Sql+='
	SELECT	fc.FinanceID,
			dbo.UF_OT_StringReplace(Lvl,2)+FinanceName AS FinanceName,
			--dbo.UF_OT_StringReplace(Lvl+2)+FinanceNO AS FinanceNO,
			--Lvl,
			fc.path,
			SonNum,
			ISNULL(SUM(fd.Total),0) AS Total,
			ISNULL(SUM(fd.BQTotal),0) AS BQTotal
	FROM BD_Finance fc
	LEFT JOIN '+CASE WHEN @Type=0 THEN '#ExpenditureData' ELSE 'FinanceData' END+' fd ON  fd.Path LIKE fc.Path+''%'' 
	WHERE fc.Path LIKE ''00002%'' OR fc.Path LIKE ''00003%''
	GROUP BY fc.FinanceID,FinanceName,fc.Path,SonNum,lvl,fc.LoanStt
	ORDER BY Path
	if object_id(''tempdb..#ExpenditureData'',''U'') is not null drop table #ExpenditureData
	'
--PRINT @Sql
EXEC sp_executesql @Sql,N'@Period int,@StartDate Date,@EndDate Date',@Period,@StartDate,@EndDate
GO



IF EXISTS ( SELECT  *
            FROM    sys.objects
            WHERE   OBJECT_ID = OBJECT_ID(N'[UP_MF_OtherMoneySummary]')
                    AND TYPE IN ( N'P', N'PC' ) )
    DROP PROCEDURE [UP_MF_OtherMoneySummary]
GO
/****** Object:  StoredProcedure [UP_MF_OtherMoneySummary]    Script Date: 07/31/2014 17:03:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO 
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/28
-- Description:	 其他收入汇总
-- =============================================
CREATE PROCEDURE [UP_MF_OtherMoneySummary] ( 
	@Period INT = 0,
	@OperatorID INT = 0                  --操作员ID
)
AS
    BEGIN
        SET NOCOUNT ON;	
        DECLARE @EarnFPath NVARCHAR(10) = N'00002' ,
            @SaleEarnFID INT = 8 ,
            @EarnFID INT = 3 ,
            @StartDate DATETIME ,
            @Sql NVARCHAR(MAX) = '', 
            @LimitSql NVARCHAR(1000) = '', 
	        @AtypeLimit INT = 0
    
        IF EXISTS ( SELECT  1
                    FROM    SS_MonthProc
                    WHERE   Name = '本期'
                            AND Period = @Period )
            SET @Period = 0
     
		--财务项目权限                    
		SELECT @AtypeLimit = dbo.UF_BD_IsAllAtypeLimit(@OperatorID)
		                    
		IF @AtypeLimit = 1  --部份权限
		   SET @LimitSql = ' INNER JOIN dbo.UF_BD_AtypeLimit(@OperatorID) rFinance ON rFinance.FinanceID = f.FinanceID '
		   
        IF @Period = 0
            BEGIN
                SELECT  @StartDate = StartDate
                FROM    SS_MonthProc
                WHERE   Name = '本期'
                        AND EndDate IS NULL;
                SET @Sql = 'IF OBJECT_ID(''tempdb..#OtherMoneyTemp'', ''U'') IS NOT NULL
                    DROP TABLE #OtherMoneyTemp
					 SELECT  SUM(lt.DTotal - lt.JTotal) AS Amount ,
                        lt.FinanceID
                INTO    #OtherMoneyTemp
                FROM    PD_ListTable lt
                        INNER JOIN BD_Finance b ON b.FinanceID = lt.FinanceID
                WHERE   b.[Path] LIKE @EarnFPath + ''%''
                        AND b.FinanceID <> @SaleEarnFID
                        AND b.SonNum = 0
                        AND lt.BillDate >= @StartDate
                GROUP BY lt.FinanceID
 
                SELECT  f.FinanceID ,
                        f.FinanceName ,
                        f.Stt ,
                        f.[Path] ,
                        f.SonNum ,
                        ( dbo.UF_OT_StringReplace(f.Lvl, 3) + f.FinanceNO ) AS FinanceCode ,
                        ISNULL(Data.Amount, 0) AS Amount ,
                        ISNULL(fs.QmBalances, 0) AS Balance
                FROM    BD_Finance f ' + @LimitSql +
					  ' LEFT JOIN BD_Funds fs ON fs.FinanceID = f.FinanceID
                        LEFT JOIN #OtherMoneyTemp DATA ON DATA.FinanceID = f.FinanceID				   
                WHERE   f.[Path] LIKE @EarnFPath + ''%''
                        AND f.FinanceID <> @SaleEarnFID
                        AND f.FinanceID <> @EarnFID
                ORDER BY f.[Path]
                IF OBJECT_ID(''tempdb..#OtherMoneyTemp'', ''U'') IS NOT NULL
                    DROP TABLE #OtherMoneyTemp'
            END	             
        ELSE
			IF @Period = 99999 --期初
				SET @Sql = ' SELECT  f.FinanceID ,
						f.FinanceName ,
						f.Stt ,
						f.[Path] ,
						f.SonNum ,
						( dbo.UF_OT_StringReplace(f.Lvl, 3) + f.FinanceNO ) AS FinanceCode ,
						ISNULL(fs.QcBalances, 0) AS Amount ,
						ISNULL(fs.QcBalances, 0) AS Balance
				FROM    BD_Finance f ' + @LimitSql +
						' LEFT JOIN BD_Funds fs ON fs.FinanceID = f.FinanceID
				WHERE   f.[Path] LIKE @EarnFPath + ''%''
						AND f.FinanceID <> @SaleEarnFID
                        AND f.FinanceID <> @EarnFID 
				ORDER BY f.[Path] '
			ELSE --月结期间
				SET @Sql = ' SELECT  f.FinanceID ,
						f.FinanceName ,
						f.Stt ,
						f.[Path] ,
						f.SonNum ,
						( dbo.UF_OT_StringReplace(f.Lvl, 3) + f.FinanceNO ) AS FinanceCode ,
						ISNULL(mb.BqTotal, 0) AS Amount ,
						ISNULL(mb.Total, 0) AS Balance
				FROM    BD_Finance f ' + @LimitSql +
						' LEFT JOIN SS_MonthBalance mb ON mb.FinanceID = f.FinanceID
														AND mb.Period = @Period
				WHERE   f.[Path] LIKE @EarnFPath + ''%''
						AND f.FinanceID <> @SaleEarnFID
                        AND f.FinanceID <> @EarnFID
				ORDER BY f.[Path] '	
				
		IF @AtypeLimit = 0
			SET @Sql = N' SELECT * FROM BD_Finance WHERE 1 <> 1'
			
        EXEC sp_executesql @Sql,
            N'@Period int, @StartDate Date, @SaleEarnFID INT, @EarnFPath NVARCHAR(5), @EarnFID INT, @OperatorID INT',
            @Period, @StartDate, @SaleEarnFID, @EarnFPath, @EarnFID, @OperatorID 
    END
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_QueryFeeRecBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_MF_QueryFeeRecBill]
GO
/****** Object:  StoredProcedure [UP_MF_QueryFeeRecBill]    Script Date: 06/16/2014 14:04:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/6/16
-- Description:	 查询其他收入
-- =============================================
CREATE PROCEDURE [UP_MF_QueryFeeRecBill]( 
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	declare @IsAccounts int =0
	if exists(select 1 from PD_MulAccounts where BillTypeID = 405 and BillNo = @BillNo)
		select @IsAccounts = 1
	DECLARE @SqlMain NVARCHAR(4000), @SqlDetail NVARCHAR(4000), 
	        @MainTable NVARCHAR(40) = 'MF_FeeRecBill', @DetailTable NVARCHAR(40) = 'MF_FeeRecDetail'
	IF NOT EXISTS (SELECT 1 FROM MF_FeeRecBill WHERE BillNo = @BillNo)
		BEGIN
			SET @MainTable += '_His'
			SET @DetailTable += '_His'
		END
	SET @SqlMain = 'SELECT fee.BillNo, fee.BillTypeID, fee.BillCode, fee.BillDate, fee.BTypeID, fee.DeptID, fee.ElyID, fee.Creator AS CreatorID,
						   CASE @IsAccounts WHEN 0 THEN fee.FinanceID ELSE -100 end as FinanceID, fee.PayRecTotal, fee.Total, fee.PaidTotal, creator.ElyName AS CreatorName, fee.CreateTime, fee.PosElyID, 
						   fee.PosTime, fee.Summary, fee.[Description], fee.IsDraft, fee.Red, fee.StlTag, fee.IsOS, 
						   dept.DeptName, ely.ElyName, btype.BTypeName, CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '''+'【多账户】'+''' end as FinanceName, pos.ElyName AS PosName,@IsAccounts as IsAccounts
						   ,fee.AuditStatus
						   FROM ' + @MainTable + ' fee
						   LEFT JOIN BD_Dept dept ON fee.DeptID = dept.DeptID
						   LEFT JOIN BD_Employee ely ON fee.ElyID = ely.ElyID
						   LEFT JOIN BD_Employee creator ON fee.Creator = creator.ElyID
						   LEFT JOIN BD_Employee pos ON fee.PosElyID = pos.ElyID
						   LEFT JOIN BD_Btype btype ON fee.BTypeID = btype.BTypeID
						   LEFT JOIN BD_Finance f ON fee.FinanceID = f.FinanceID
						 WHERE fee.BillNo = @BillNo'  --查询主表
						
	EXEC sp_executesql @SqlMain, N'@BillNo INT,@IsAccounts int', @BillNo,@IsAccounts
         
	SET @SqlDetail = 'SELECT detail.DID, detail.BillNo, detail.FinanceID, detail.Total, detail.Remark, f.FinanceNO, f.FinanceName  
						   FROM ' + @DetailTable + ' detail
						   LEFT JOIN BD_Finance f ON detail.FinanceID = f.FinanceID
						WHERE detail.BillNo = @BillNo'  --查询项目明细
						
	EXEC sp_executesql @SqlDetail, N'@BillNo INT,@IsAccounts int', @BillNo,@IsAccounts
	
	SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 405 and BillNo = @BillNo    
	
END
GO




/****** Object:  StoredProcedure [UP_MF_QueryYBFYBillData]    Script Date: 06/17/2014 18:06:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_MF_QueryYBFYBillData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_MF_QueryYBFYBillData]
GO


/****** Object:  StoredProcedure [UP_MF_QueryYBFYBillData]    Script Date: 06/17/2014 18:06:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		liuke
-- Create date:  2014-06-17
-- Modify date:  2014-07-08
-- Description:	 查询一般费用单
-- =============================================
CREATE PROCEDURE [UP_MF_QueryYBFYBillData]( 
     @BillNo INT=0
   ) 
AS
BEGIN
	declare @IsAccounts int =0
	if exists(select 1 from PD_MulAccounts where BillTypeID = 404 and BillNo = @BillNo)
		select @IsAccounts = 1
	IF EXISTS (SELECT 1 FROM MF_FeeRecBill b WHERE b.BillNo=@BillNo)
	BEGIN		--当前数据
		--查询主表
		SELECT TOP 1 
			f.IsDraft,f.PaidTotal
			,f.BillNo,f.BillTypeID,f.BillCode,f.BillDate
			,f.BTypeID,b.BTypeName,f.PaidTotal
			,f.ElyID,e.ElyName
			,f.DeptID,d.DeptName
			,f.Summary,f.[Description],f.Red
			,f.Creator[CreatorID],ec.ElyName[CreatorName]
			,f.PosElyID,ep.ElyName[PosName],
			CASE @IsAccounts WHEN 0 THEN f.FinanceID ELSE -100 end as FinanceID,
			CASE @IsAccounts WHEN 0 THEN fi.FinanceName ELSE '【多账户】' end as FinanceName
			--,f.FinanceID,fi.FinanceName
			,f.Total,f.PayRecTotal,f.IsOS ,@IsAccounts as IsAccounts,
			f.AuditStatus
		FROM MF_FeeRecBill f
		INNER JOIN BD_Btype b ON f.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON f.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON f.DeptID=d.DeptID 
		LEFT JOIN BD_Employee ec ON f.Creator=ec.ElyID 
		LEFT JOIN BD_Employee ep ON f.PosElyID=ep.ElyID 
		LEFT JOIN BD_Finance fi ON fi.FinanceID = f.FinanceID 
		WHERE f.BillNo = @BillNo 
		
		--查询项目明细
		SELECT dtl.DID,f.FinanceID,f.FinanceNO,f.FinanceName,dtl.Total,dtl.Remark 
		FROM MF_FeeRecDetail dtl 
		LEFT JOIN BD_Finance f ON dtl.FinanceID=f.FinanceID 
		WHERE dtl.BillNo = @BillNo
		--查询多账户
		SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 404 and BillNo = @BillNo    
		
	END
	ELSE
	BEGIN		--历史数据
		--查询主表
		SELECT TOP 1 
			f.IsDraft,f.PaidTotal
			,f.BillNo,f.BillTypeID,f.BillCode,f.BillDate
			,f.BTypeID,b.BTypeName,f.PaidTotal
			,f.ElyID,e.ElyName
			,f.DeptID,d.DeptName
			,f.Summary,f.[Description],f.Red
			,f.Creator[CreatorID],ec.ElyName[CreatorName]
			,f.PosElyID,ep.ElyName[PosName],
			CASE @IsAccounts WHEN 0 THEN f.FinanceID ELSE -100 end as FinanceID,
			CASE @IsAccounts WHEN 0 THEN fi.FinanceName ELSE '【多账户】' end as FinanceName
			--,f.FinanceID,fi.FinanceName
			,f.Total,f.PayRecTotal,f.IsOS,@IsAccounts as IsAccounts,
			f.AuditStatus
		FROM MF_FeeRecBill_His f
		INNER JOIN BD_Btype b ON f.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON f.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON f.DeptID=d.DeptID 
		LEFT JOIN BD_Employee ec ON f.Creator=ec.ElyID 
		LEFT JOIN BD_Employee ep ON f.PosElyID=ep.ElyID 
		LEFT JOIN BD_Finance fi ON fi.FinanceID = f.FinanceID 
		WHERE f.BillNo = @BillNo 
		
		--查询项目明细
		SELECT dtl.DID,f.FinanceID,f.FinanceNO,f.FinanceName,dtl.Total,dtl.Remark 
		FROM MF_FeeRecDetail_His dtl 
		LEFT JOIN BD_Finance f ON dtl.FinanceID=f.FinanceID 
		WHERE dtl.BillNo = @BillNo
		--查询多账户
		SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 404 and BillNo = @BillNo    
	END
END

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：hanlin
	日期：2014-7-15
	描述：销售回款统计
-------------------------------------------*/
CREATE PROCEDURE [UP_MF_ReturnStatistics]
(
	@PageNo INT,
	@PageSize INT,
	@BeginDate DATE,
	@EndDate DATE,
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CollectType INT=1,
	@Layer INT =1,
	@OrderField VARCHAR(MAX),
	@Type INT,
	@IsHistory INT=0,
	@UserID INT=1
)

AS
SET NOCOUNT ON


DECLARE @CashPath VARCHAR(20),@BankPath VARCHAR(20),@AssurePath VARCHAR(20),@Sql NVARCHAR(max),@TypeName VARCHAR(10),@FromTableStr VARCHAR(max),
		@JoinStr VARCHAR(max)='',@TableStr VARCHAR(max)='',@Ret INT=0,@TypeJoinStr VARCHAR(max)=''

EXEC @ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN

IF @CollectType=1
	SET @TypeName='BtypeID'
ELSE IF @CollectType=2
	SET @TypeName='DeptID'
ELSE
	SET @TypeName='ElyID'

IF(@DeptID<>'')
BEGIN
	SET @TableStr =' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @JoinStr=' INNER JOIN @Dtype d on a.DeptID=d.TypeID '
	IF @CollectType=2
		SET @TypeJoinStr= ' INNER JOIN @Dtype d1 on D.DeptID=d1.TypeID '
END
IF @BTypeID<>'' OR dbo.UF_BD_IsAllBtypeLimit(@UserID)<>2
BEGIN
	SET @TableStr+=' DECLARE @BType Table(TypeID INT) insert into @BType '
	IF @BTypeID<>'' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)=2 
		SET @TableStr+='	Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	ELSE IF @BTypeID='' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)<>2
		SET @TableStr+='	Select Btypeid from dbo.UF_BD_BtypeLimit(@UserID) UNION ALL SELECT 99999 '
	ELSE
		SET @TableStr+='	Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') a inner join dbo.UF_BD_BtypeLimit(@UserID) b ON b.BtypeID =a.typeid '
			

	SET @JoinStr+=' INNER JOIN @Btype b on a.BTypeID=b.TypeID '
	IF @CollectType=1
		SET @TypeJoinStr= ' INNER JOIN @Btype b1 on b.BTypeID=b1.TypeID '
END   
IF(@ElyID<>'')
BEGIN
	SET @TableStr +=' DECLARE @EType Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @JoinStr+=' INNER JOIN @Etype e on a.ElyID=e.TypeID '
	IF @CollectType=3
		SET @TypeJoinStr= ' INNER JOIN @Etype e1 on e.ElyID=e1.TypeID  '
END
		
SELECT @CashPath=Path+'%' FROM BD_Finance WHERE FinanceNO='1001'
SELECT @BankPath=Path+'%' FROM BD_Finance WHERE FinanceNO='1002'
SELECT @AssurePath=Path+'%' FROM BD_Finance WHERE FinanceNO='1003'
SET @sql=@TableStr
SET @Sql+='

if object_id(''tempdb..#RssPagingData'',''U'') is not null drop table #RssPagingData
;WITH SaleTotal AS
(
	SELECT '+@TypeName+',Sum(Total) as Total,SUM(Privilege) AS Privilege
	from
	(
	SELECT BTypeID,ElyID,DeptID,201 AS Billtype,BillDate,Total,Privilege,red,IsDraft FROM PD_SellBill 
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,202 AS Billtype,BillDate,-Total,-Privilege,red,IsDraft FROM PD_SellretBill
	UNION ALL
	SELECT 99999 AS BTypeID,ElyID,DeptID,602 AS Billtype,BillDate,0 AS Total,Privilege,red,IsDraft FROM VS_VipChargeBill
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,402 AS Billtype,BillDate,0 AS Total,Privilege,red,IsDraft FROM MF_PayRecBill   '
IF @IsHistory=1
	SET @Sql+='
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,201 AS Billtype,BillDate,Total,Privilege,red,IsDraft FROM PD_SellBill_his 
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,202 AS Billtype,BillDate,-Total,-Privilege,red,IsDraft FROM PD_SellretBill_His	'
SET @sql+='
	)a '+@JoinStr+'
	WHERE BillDate BETWEEN @BeginDate AND @EndDate  AND IsDraft=0 AND red=0
	GROUP BY '+@TypeName+'
), FinceTotal AS 
(
	SELECT '+@TypeName+',SUM(CASE WHEN f.Type =0 THEN PayRecTotal ELSE 0 END )AS CashTotal,SUM(CASE WHEN f.Type =1 THEN PayRecTotal ELSE 0 END) AS BankTotal,SUM(CASE WHEN f.Type =2 THEN PayRecTotal ELSE 0 END) AS AssureTotal FROM 
	(
		SELECT BTypeID,ElyID,DeptID,201 AS Billtype,ISNull(m.Total,s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM PD_SellBill s
		LEFT JOIN PD_MulAccounts m ON m.BillNo=s.BillNo AND m.BillTypeID=201
		UNION ALL
		SELECT BTypeID,ElyID,DeptID, 202 AS Billtype,ISNull(-m.Total,-s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM PD_SellretBill s
		LEFT JOIN PD_MulAccounts m ON m.BillNo=s.BillNo AND m.BillTypeID=202
		UNION ALL
		SELECT BTypeID,ElyID,DeptID,BilltypeID AS BillType,d.Total,d.FinanceID,BillDate,red,IsDraft FROM MF_PayRecBill b INNER JOIN MF_PayRecDetail d ON b.BillNo = d.BillNo WHERE BillTypeID=402
		UNION ALL
		SELECT BTypeID,ElyID,DeptID,s.BilltypeID AS BillType,ISNull(m.Total,s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM MF_FeeRecBill s
		LEFT JOIN PD_MulAccounts m ON m.BillNo=s.BillNo AND m.BillTypeID=s.BillTypeID WHERE s.BillTypeID=405 '
IF @BTypeID=''		
	SET @sql+='
		UNION ALL
		SELECT 99999 ,ElyID,DeptID,602 AS Billtype,ISNull(m.Total,s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM VS_VipChargeBill s
		LEFT JOIN PD_MulAccounts m ON m.BillNo=s.BillNo AND m.BillTypeID=602 '
IF @IsHistory=1
	SET @Sql+='
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,201 AS Billtype,ISNull(m.Total,s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM PD_SellBill_his s
	LEFT JOIN PD_MulAccounts_His m ON m.BillNo=s.BillNo AND m.BillTypeID=201
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,202 AS Billtype,ISNull(-m.Total,-s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM PD_SellretBill_His s 
	LEFT JOIN PD_MulAccounts_His m ON m.BillNo=s.BillNo AND m.BillTypeID=202
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,BilltypeID AS BillType,d.Total,d.FinanceID,BillDate,red,IsDraft FROM MF_PayRecBill_His b INNER JOIN MF_PayRecDetail_His d ON b.BillNo = d.BillNo WHERE BillTypeID=402
	UNION ALL
	SELECT BTypeID,ElyID,DeptID,s.BilltypeID AS BillType,ISNull(m.Total,s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM MF_FeeRecBill_His s 
	LEFT JOIN PD_MulAccounts_His m ON m.BillNo=s.BillNo AND m.BillTypeID=s.BillTypeID WHERE s.BillTypeID=405 '
IF @BTypeID=''	
	SET @sql+='
	UNION ALL
	SELECT 99999,ElyID,DeptID,602 AS Billtype,ISNull(m.Total,s.PayRecTotal)PayRecTotal,ISNull(m.FinanceID,s.FinanceID) FinanceID,BillDate,red,IsDraft FROM VS_VipChargeBill_His s
	LEFT JOIN PD_MulAccounts_His m ON m.BillNo=s.BillNo AND m.BillTypeID=602 '
	
SET @sql+='	
	)a  INNER JOIN (SELECT FinanceID, CASE WHEN Path LIKE @CashPath THEN 0 WHEN Path LIKE @BankPath THEN 1  ELSE 2 END AS Type  FROM BD_Finance WHERE Path LIKE @CashPath OR Path LIKE @BankPath OR Path Like @AssurePath) f ON a.FinanceID = f.FinanceID
	'+@JoinStr+'
	WHERE PayRecTotal<>0 AND BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 AND red=0 
	GROUP by '+@TypeName+'
)'

IF @CollectType=1
BEGIN
	IF @Layer<>6
	BEGIN
		SET @sql +=' ,PagingData AS (SELECT bt2.TypeCode As UserCode,bt2.TypeName as FullName,Bt2.BTypeTypeID as TypeID '
		SELECT @FromTableStr=' bd_btype_type bt2 inner join bd_btype_type bt On LEFT(bt.Path,5*'+CAST(@Layer AS VARCHAR)+')=bt2.Path INNER JOIN BD_Btype b ON b.BtypeTypeID=bt.BtypeTypeID '+@TypeJoinStr+' LEFT JOIN SaleTotal s On s.BTypeID=b.BTypeID 
		LEFT JOIN FinceTotal f on f.btypeID=b.BtypeID WHERE bt2.lvl='+CAST(@Layer AS VARCHAR)+' OR( bt2.lvl<'+CAST(@Layer AS VARCHAR)+' AND bt2.Sonnum=0) Group By bt2.TypeCode,bt2.TypeName,Bt2.BTypeTypeID )'
	END
	ELSE
	BEGIN
		SET @sql +=' ,PagingData AS(SELECT B.BtypeCode as UserCode,B.BtypeName as FullName,B.BTypeID as TypeID '
		SELECT @FromTableStr=' (SELECT BTypeID,BTypeCode,BTypeName FROM BD_Btype UNION ALL SELECT 99999,''会员储值'',''会员储值'') b '+@TypeJoinStr+' LEFT JOIN SaleTotal s ON b.BtypeID=S.BtypeID LEFT join FinceTotal f ON b.BTypeID=f.BTypeID Group By B.BtypeCode,B.BtypeName,B.BTypeID) '
	END
END
ELSE IF @CollectType=2
BEGIN
	SET @sql +=' ,PagingData AS (SELECT D2.DeptCode As UserCode,D2.DeptName AS FullName,D2.DeptID as TypeID '
	SELECT @FromTableStr=' BD_Dept D2 inner join BD_Dept D ON d2.Path=LEFT(D.Path,5*'+CAST(@Layer AS VARCHAR)+')'+@TypeJoinStr+' LEFT JOIN SaleTotal s ON s.DeptID=D.DeptID LEFT JOIN FinceTotal f ON D.DeptID=f.DeptID  WHERE D2.lvl='+CAST(@Layer AS VARCHAR)+' OR( d2.lvl<'+CAST(@Layer AS VARCHAR)+' AND d2.Sonnum=0)  Group By D2.DeptName,D2.DeptCode,D2.DeptID)'
END
ELSE
BEGIN
	SET @sql +=' ,PagingData AS (SELECT E.ElyCode AS UserCode,E.ElyName As FullName,E.ElyID AS TypeID '
	SELECT @FromTableStr=' BD_Employee E '+@TypeJoinStr+' LEFT JOIN SaleTotal s ON s.ElyID=E.ElyID LEFT JOIN FinceTotal f ON E.ElyID=f.ElyID WHERE E.ElyID>1  Group By E.ElyCode,E.ElyName,E.ElyID )'
END
	
SET @sql+=' ,IsNUll(SUM(Total),0)AS Total,IsNUll(SUM(Privilege),0) AS Privilege,IsNUll(SUM(CashTotal),0) AS CashTotal,IsNUll(SUM(BankTotal),0) AS BankTotal,IsNUll(SUM(AssureTotal),0) AS AssureTotal,IsNUll(SUM(CashTotal+BankTotal+AssureTotal),0) AS ReturnTotal FROM'+@FromTableStr

IF @Type<>3
SET @sql+='
	SELECT * INTO #RssPagingData FROM PagingData	
   SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM #RssPagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderField+' ) AS ROWID,
	*
	FROM #RssPagingData
   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	DROP TABLE #RssPagingData --option(recompile)

'
ELSE
	SET @sql+='
	select SUM(Total)Total,SUM(Privilege)Privilege,SUM(BankTotal)BankTotal,SUM(CashTotal)CashTotal,SUM(AssureTotal)AssureTotal,SUM(ReturnTotal)ReturnTotal from PagingData
	'
--PRINT(@sql)
EXEC sp_executesql @sql,N'@BeginDate Date,@EndDate Date,@CashPath VarChar(20),@BankPath VarChar(20),@AssurePath VarChar(20),@PageNo int,@PageSize INT,@BTypeID VarChar(max),@DeptID varchar(max),@ElyID varchar(max),@UserID INT',@BeginDate,@EndDate,@CashPath,@BankPath,@AssurePath,@PageNo,@PageSize,@bTypeid,@DeptID,@ElyID,@UserID

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_MF_SaleInvoiceM]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_MF_SaleInvoiceM
GO
/****** Object:  StoredProcedure [UP_MF_SaleInvoiceM]    Script Date: 02/12/2015 15:12:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/2/12
-- Description:	 销售发票管理
-- =============================================
CREATE PROCEDURE [UP_MF_SaleInvoiceM](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @InvoiceStartDate DATETIME,                    --开始日期
	 @InvoiceEndDate DATETIME,                    --结束日期
	 @BTypeID VARCHAR(1000) = '',            --往来单位
     @InvoiceBillCodeMatch INT = 0,   --发票单据编号匹配方式
     @InvoiceBillCode VARCHAR(50) = '', --发票单据编号
	 @ElyID VARCHAR(1000) = '',            --经手人
	 @InvoiceMode INT = 0,            --开票方式
     @InvoiceCodeMatch INT = 0,   --发票号匹配方式
	 @InvoiceCode VARCHAR(100) = '',            --发票号
	 @InvoiceType INT = 0,            --发票类型
	 @CheckStt INT = 0,            --审核状态
	 @BillStartDate DATETIME = NULL,                    --单据开始日期
	 @BillEndDate DATETIME = NULL,                    --单据结束日期
	 @BillType INT = 0,            --单据类型
     @BillCodeMatch INT = 0,   --单据编号匹配方式
	 @BillCode VARCHAR(100) = '',         --单据编号
	 @OrderStr VARCHAR(50) = '',         --排序字符串
	 @OperatorID INT = 0,                  --操作员ID   
	 @IsHistory BIT = 0,    --是否查询历史记录 
	 --------------------跳转报表的参数-----------------------
	 @BillNo INT = 0,                  --单据ID   
	 @InBTypeID INT = 0    --往来单位  
   ) 
AS
BEGIN
	SET NOCOUNT ON;		
	DECLARE @Re INT 
	EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @InvoiceStartDate, @isHistory = @IsHistory
	IF @Re = 1 RETURN @Re;
	
	EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @BillStartDate, @isHistory = @IsHistory
	IF @Re = 1 RETURN @Re;
	
	DECLARE @Sql NVARCHAR(MAX) = '', @HeadSql NVARCHAR(MAX) = '',
		    @SqlParam NVARCHAR(1000) = N' WHERE 1 = 1 ',
		    @SttParam NVARCHAR(1000) = N'',
	        @SumSql NVARCHAR(MAX) = N'', 
	        @DataSql NVARCHAR(2000) = N'', 
	        @BaseSql NVARCHAR(2000) = N'',
	        @BillSql NVARCHAR(4000) = N'',
	        @BillParam NVARCHAR(2000) = N' WHERE 1= 1 ',
	        @BtypeLimit INT = 0,
	        @SaleBill INT = 201,
	        @SaleBackBill INT = 202
    DECLARE @TVP_Dept AS [TVP_Type]
    IF @InvoiceStartDate IS NOT NULL AND @InvoiceEndDate IS NOT NULL
		SET @SqlParam += ' AND bill.BillDate BETWEEN @InvoiceStartDate AND @InvoiceEndDate '
	SET @SumSql = N' PagingData AS (SELECT  DISTINCT bill.BillNo, bill.InvoiceTotal FROM  MF_SellInvoiceBill bill '	
	SET @HeadSql = N' PagingData AS (SELECT DISTINCT bill.BillNo, bill.BillCode, bill.BTypeID, bill.DeptID, bill.ElyID, bill.BillDate
											   , bill.CreateTime, bill.Creator AS CreatorID, bill.Summary, bill.[Description], bill.IsDraft
											   , bill.InvoiceTotal, bill.InvoiceType, bill.InvoiceMode, bill.InvoiceCode, 0 as IsHistory	  
										 FROM  MF_SellInvoiceBill bill '	   
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)   
	                 
    IF @BtypeLimit = 1  --部份权限
	   BEGIN
			IF OBJECT_ID('tempdb..#SellIMBtypeLimit', 'U') IS NOT NULL
				DROP TABLE #SellIMBtypeLimit
			SELECT * INTO #SellIMBtypeLimit FROM dbo.UF_BD_BtypeLimit(@OperatorID)
			SET @Sql +=' INNER JOIN #SellIMBtypeLimit rBtype ON rBtype.BTypeID = bill.BTypeID '
	   END
       
    IF @BTypeID <> ''     --往来单位
	   BEGIN
			IF OBJECT_ID('tempdb..#SellIMBtypeList', 'U') IS NOT NULL
				DROP TABLE #SellIMBtypeList
			SELECT * INTO #SellIMBtypeList FROM dbo.UF_OT_Split_Int(@BTypeID, ',')
			SET @Sql +=' INNER JOIN #SellIMBtypeList _btype ON _btype.typeid = bill.BTypeID '
	   END
       
    IF @InBTypeID <> 0     --往来单位
	   SET @SqlParam += N' AND bill.BTypeID = @InBTypeID ' 
	     							
	IF @InvoiceBillCode <> ''   --单据编号
	   BEGIN 
		   IF @InvoiceBillCodeMatch = 0
			   SET @SqlParam += N' AND bill.BillCode LIKE ''%'' + @InvoiceBillCode +''%'''
		   ELSE IF @InvoiceBillCodeMatch = 1
			   SET @SqlParam += N' AND bill.BillCode = @InvoiceBillCode ' 
	   END
	   
    IF @ElyID <> ''     --经手人
	   BEGIN
			IF OBJECT_ID('tempdb..#SellIMElyList', 'U') IS NOT NULL
				DROP TABLE #SellIMElyList
			SELECT * INTO #SellIMElyList FROM dbo.UF_OT_Split_Int(@ElyID, ',')
			SET @Sql +=' INNER JOIN #SellIMElyList _Emp ON _Emp.typeid = bill.ElyID '
	   END
	   
	IF @InvoiceMode <> 9999  --开票方式 
	    SET @SqlParam += ' AND bill.InvoiceMode = @InvoiceMode '
	     							
	IF @InvoiceCode <> ''   --发票号
	   BEGIN 
		   IF @InvoiceCodeMatch = 0
			   SET @SqlParam += N' AND bill.InvoiceCode LIKE ''%'' + @InvoiceCode +''%'''
		   ELSE IF @InvoiceCodeMatch = 1
			   SET @SqlParam += N' AND bill.InvoiceCode = @InvoiceCode ' 
	   END
	   
	IF @InvoiceType <> 9999  --发票类型
	    SET @SqlParam += ' AND bill.InvoiceType = @InvoiceType '
	   
	IF @CheckStt <> 9999  --审核状态
	    SET @SqlParam += ' AND bill.IsDraft = @CheckStt '
	    
	IF @BillNo <> 0 OR @InBTypeID <> 0 --报表跳转只查已审核的
	    SET @SqlParam += ' AND bill.IsDraft = 0 '
	    
	IF (@InvoiceMode <> 9999 AND @InvoiceMode <> 3) OR @BillNo <> 0 OR @BillType <> 9999 OR @BillCode <> '' OR (@BillStartDate IS NOT NULL AND @BillEndDate IS NOT NULL) --开票方式不为手工开票时关联单据
	    BEGIN
			IF @BillStartDate IS NOT NULL AND @BillEndDate IS NOT NULL
				SET @BillParam += ' AND BillDate BETWEEN  @BillStartDate AND @BillEndDate '	     							
			IF @BillCode <> ''   --单据编号
			   BEGIN 
				   IF @BillCodeMatch = 0
					   SET @BillParam += N' AND BillCode LIKE ''%'' + @BillCode +''%'''
				   ELSE IF @BillCodeMatch = 1
					   SET @BillParam += N' AND BillCode = @BillCode ' 
			   END
			IF @BillNo <> 0
				SET @BillParam += N' AND BillNo = @BillNo ' 
			IF @BillType = 9999 OR @BillType = 201
				BEGIN
					SET @BillSql += ';WITH BillData AS (SELECT BillNo, @SaleBill AS BillType FROM PD_SellBill' + @BillParam +
									' UNION ALL (SELECT BillNo, @SaleBill AS BillType FROM PD_SellBill_His ' + @BillParam + ' ) '
					IF @BillType = 9999
						SET @BillSql += ' UNION ALL (SELECT BillNo, @SaleBackBill AS BillType FROM PD_SellRetBill ' + @BillParam + ' )
										   UNION ALL (SELECT BillNo, @SaleBackBill AS BillType FROM PD_SellRetBill_His ' + @BillParam + ' ) '
					SET @BillSql += ' ) '
				END
			ELSE
				SET @BillSql += ';WITH BillData AS (SELECT BillNo, @SaleBackBill AS BillType FROM PD_SellRetBill ' + @BillParam + ' 
								   UNION ALL (SELECT BillNo, @SaleBackBill AS BillType FROM PD_SellRetBill_His ' + @BillParam + ' )) '
			IF @BillNo <> 0 OR @BillType <> 9999 OR @BillCode <> '' OR (@BillStartDate IS NOT NULL AND @BillEndDate IS NOT NULL)
				BEGIN
					IF @InBTypeID <> 0
						BEGIN
							SET @SqlParam +=' AND ((bill.InvoiceMode <> 3 AND EXISTS (SELECT 1 FROM MF_SellInvoiceDetail detail 
												INNER JOIN BillData bData ON bData.BillNo = detail.SellBillNo
												AND detail.BillType = bData.BillType AND detail.BillNo = bill.BillNo ))
												  OR (bill.InvoiceMode = 3 AND bill.BillDate BETWEEN @BillStartDate AND @BillEndDate ))'
						END
					ELSE
						BEGIN
							SET @Sql +=' INNER JOIN MF_SellInvoiceDetail detail ON detail.BillNo = bill.BillNo
										 INNER JOIN BillData bData ON bData.BillNo = detail.SellBillNo AND detail.BillType = bData.BillType '
							SET @SqlParam +=' AND bill.InvoiceMode <> 3'
						END
				END
			SET @HeadSql = @BillSql + ',' + @HeadSql
			SET @SumSql = @BillSql + ',' + @SumSql
	    END
	ELSE
		BEGIN
			SET @HeadSql = ';WITH ' + @HeadSql
			SET @SumSql =  ';WITH' + @SumSql
		END
       
    SET @BaseSql += N', _DATA_Btype AS (SELECT BTypeID AS BID, BTypeCode, BTypeName FROM BD_Btype)
					  , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName FROM BD_Dept)
					  , _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName FROM BD_Employee)
					  , _DATA_Creator AS (SELECT ElyID AS CID, ElyCode AS CreatorCode, ElyName AS Creator FROM BD_Employee)'  
                   
    SET @DataSql += N' LEFT JOIN _DATA_Btype ON Data.BTypeID = _DATA_Btype.BID
					   LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID
					   LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID 
					   LEFT JOIN _DATA_Creator ON Data.CreatorID = _DATA_Creator.CID '
	SET @HeadSql = @HeadSql + @Sql + @SqlParam
	SET @SumSql = @SumSql + @Sql + @SqlParam
	IF @IsHistory = 1
		BEGIN
			SET  @SumSql = @SumSql + ' UNION ALL (SELECT DISTINCT bill.BillNo, bill.InvoiceTotal FROM  MF_SellInvoiceBill_His bill ' + REPLACE(@Sql,'MF_SellInvoiceDetail','MF_SellInvoiceDetail_His') + REPLACE(@SqlParam,'MF_SellInvoiceDetail','MF_SellInvoiceDetail_His') + ' ) '
			SET  @Sql = @HeadSql + ' UNION ALL (SELECT DISTINCT bill.BillNo, bill.BillCode, bill.BTypeID, bill.DeptID, bill.ElyID, bill.BillDate
											   , bill.CreateTime, bill.Creator AS CreatorID, bill.Summary, bill.[Description], bill.IsDraft
											   , bill.InvoiceTotal, bill.InvoiceType, bill.InvoiceMode, bill.InvoiceCode, 1 as IsHistory	   
										 FROM  MF_SellInvoiceBill_His bill '+ REPLACE(@Sql,'MF_SellInvoiceDetail','MF_SellInvoiceDetail_His') + REPLACE(@SqlParam,'MF_SellInvoiceDetail','MF_SellInvoiceDetail_His') + ' ) ' 
	    END	
    ELSE
       SET @Sql = @HeadSql    
    SET @Sql = N'SET NOCOUNT ON;'
               + @Sql + ')' + @BaseSql + 
			   N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
						    CROSS JOIN
						   (SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM PagingData ) B
						    WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				   SELECT *, (CASE IsDraft WHEN 0 THEN ''已审核'' ELSE ''未审核'' END) AS SttName FROM DATA ' + @DataSql + ' ORDER BY ROWID'	
				   
    SET @SumSql = N'SET NOCOUNT ON;'
               + @SumSql + ') 
			    SELECT SUM(PagingData.InvoiceTotal) AS TotalSum FROM PagingData '		
				   
	IF @BtypeLimit = 0
		BEGIN
			SET @Sql = N' SELECT * FROM MF_SellInvoiceBill WHERE 1 <> 1'
			SET @SumSql = N' SELECT 1 FROM MF_SellInvoiceBill WHERE 1 <> 1'
		END
			
	--print @Sql	
	EXEC sp_executesql @Sql,  N'@PageNo INT, @PageSize INT, @InvoiceStartDate DATETIME, @InvoiceEndDate DATETIME, @InvoiceBillCode VARCHAR(50), 
								@InvoiceMode INT, @InvoiceCode VARCHAR(100), @InvoiceType INT, @BillStartDate DATETIME, @BillEndDate DATETIME,
								@BillCode VARCHAR(100), @InBTypeID INT, @BillNo INT, @SaleBill INT, @SaleBackBill INT, @CheckStt INT ',
								@PageNo, @PageSize, @InvoiceStartDate, @InvoiceEndDate, @InvoiceBillCode, @InvoiceMode, @InvoiceCode, @InvoiceType, 
								@BillStartDate, @BillEndDate, @BillCode, @InBTypeID, @BillNo, @SaleBill, @SaleBackBill, @CheckStt		
			
	--print @SumSql								
	EXEC sp_executesql @SumSql,  N'@InvoiceStartDate DATETIME, @InvoiceEndDate DATETIME, @InvoiceBillCode VARCHAR(50), 
								@InvoiceMode INT, @InvoiceCode VARCHAR(100), @InvoiceType INT, @BillStartDate DATETIME, @BillEndDate DATETIME,
								@BillCode VARCHAR(100), @InBTypeID INT, @BillNo INT, @SaleBill INT, @SaleBackBill INT, @CheckStt INT ',
								@InvoiceStartDate, @InvoiceEndDate, @InvoiceBillCode, @InvoiceMode, @InvoiceCode, @InvoiceType, 
								@BillStartDate, @BillEndDate, @BillCode, @InBTypeID, @BillNo, @SaleBill, @SaleBackBill, @CheckStt	
								 
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OS_BackChangeStatistics]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_OS_BackChangeStatistics
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：hanlin
	日期：2015-4-16
	描述：退换货统计
-------------------------------------------*/
CREATE PROCEDURE UP_OS_BackChangeStatistics
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate DATETIME,	--录单日期查询开始时间
	@BillEndDate DATETIME,	--录单日期查询结束时间
	@PICID VARCHAR(100),
	@BackType INT,
	@BackReason VARCHAR(50)
)

AS
SET NOCOUNT ON

DECLARE @sql NVARCHAR(max)='',@JoinSql VARCHAR(max)='',@BillCodeStr VARCHAR(max)='',@FullNameStr VARCHAR(max)='',@IsAll VARCHAR(3)='All'

IF @PICID<>''
BEGIN
	SET @sql='DECLARE @EType Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@PICID,'','')'
	SET @JoinSql=' INNER JOIN @EType E ON B.PICID=E.TypeID ' 
END	
SET @sql+='
;WITH Data AS
(
SELECT	Convert(VarChar(10),BillDate,120)BillDate,
		CASE WHEN BackType=1 THEN ''补换'' ELSE ''退货'' END BackType,
		BackReason,
		Summary,
		Description,
		E1.ElyName AS PICName
FROM  OS_OrderBillAll b 
'+@JoinSql+'
LEFT JOIN BD_Employee E1 ON B.PICID=E1.ElyID
WHERE B.BillDate BETWEEN @BillStartDate AND @BillEndDate AND BillType=1 AND ISCreate=1 '
IF @BackType<>2
	SET @sql+=' AND BackType=@BackType'
IF @BackReason<>'全部'
	SET @sql+=' AND BackReason=@BackReason'	
SET @sql+='
)
SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM Data) A
CROSS JOIN
(
SELECT	ROW_NUMBER() OVER( ORDER BY BillDate) AS ROWID,
		*
FROM Data
) B
WHERE B.ROWID>(@PageNo-1)*@PageSize
AND B.ROWID<=@PageNo*@PageSize

'
--PRINT @sql
EXEC sp_executesql @sql,N'@PageNo INT,@PageSize INT,@BillStartDate DATETIME,@BillEndDate DATETIME,@BackType INT,@BackReason Varchar(max),@PICID VarChar(max)
		',@PageNo,@PageSize,@BillStartDate,@BillEndDate,@BackType,@BackReason,@PICID
GO








IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OS_GetOrderData]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_OS_GetOrderData
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：hanlin
	日期：2014-10-16
	描述：获取订单具体数据
-------------------------------------------*/
CREATE PROCEDURE [UP_OS_GetOrderData]
(
	@BillNo BIGINT
)

AS
SET NOCOUNT ON

DECLARE @FinanceName VARCHAR(50)='',@ConfigName VARCHAR(50)='',@BillType INT=0,@ShopID BIGINT=0
SELECT @BillType=BillType,@ShopID=ShopID FROM OS_OrderBill WHERE BillNo=@BillNo
IF @BillType=0
	SET @ConfigName='RecFinanceID'
ELSE
	SET @ConfigName='PayFinanceID'
	
SELECT @FinanceName=FinanceName FROM BD_Finance WHERE FinanceID=(SELECT ConfigValue FROM OS_PostConfig WHERE ConfigName=@ConfigName AND ShopID=@ShopID)

SELECT	BillNo ,
		BillType ,
		BillCode ,
		BillDate ,
		ShopID ,
		@FinanceName AS FinanceName,
		ISNULL(e.ElyID,0) ElyID ,
		e.ElyName,
		ISNULL(d.DeptID,0) DeptID,
		ISNULL(w.WhsID,0) WhsID ,
		w.WhsName,
		Summary,
		Description ,
		BillQty ,
		CASE WHEN @FinanceName='' THEN 0 ELSE Total END Total ,
		MallFee ,
		CodFee,
		LogistBTypeCode,
		ISNULL(db.BTypeID,0) AS LogistBTypeID,
		db.BTypeName AS LogistBtypeName,
		db.BTypeName,
		FreightBillNo ,
		Freight ,
		PaidFreight ,
		BuyerAccount ,
		ContactWay ,
		Receiver ,
		b.Address ,
		BuyerMsg ,
		SaleComment ,
		BackReason ,
		SrcSendBillNo ,
		BackType ,
		DestSendBillNo ,
		IsCreate
FROM	OS_OrderBill b
LEFT JOIN BD_Employee e ON b.ElyID = e.ElyID AND b.ElyID<>1 AND stt=1
LEFT JOIN BD_Dept d ON d.DeptID=e.DeptId
LEFT JOIN BD_Whs w ON b.WhsID=w.WhsID AND w.Stt=1
LEFT JOIN BD_Btype db ON db.BTypeCode=b.LogistBTypeCode AND db.Stt=1
WHERE	BillNo=@BillNo 

SELECT  BillDate ,
		BillNo ,
		d.MerchantCode,
		d.OSGoodsName,
		d.PropsName,
		g.GoodsID,
		g.GoodsID AS McOnly,--商家编码是否只读
		g.GoodsName,
		g.GoodsNo,
		ISNULL(p1.Ppt1ID,0) Ppt1ID,
		p1.Value AS Ppt1Name,
		ISNULL(p2.Ppt2ID,0) Ppt2ID,
		p2.Value AS Ppt2Name,
		u.UnitID,
		u.Unit,
		ISNULL(u.BarCode,'') BarCode,
		ISNULL(wp.WhsPtID,0) WhsPtID,
		wp.WhsPtID AS WhsOnly,
		wp.WhsPtName,
		Qty ,
		Price ,
		Total ,
		ISNULL(u.Convfactor,1) AS Convfactor,
		MallFee ,
		Gift 
FROM	OS_OrderDetail d
LEFT JOIN OS_GoodsRelation r ON d.MerchantCode=r.MerchantCode
LEFT JOIN 
(
	SELECT	GoodsID,
			GoodsName,
			GoodsNo,
			Ppt1ID,
			Ppt2ID
	FROM	BD_Goods g 
	LEFT JOIN BD_Goods_PptGroup p ON g.PptGroupID=p.PptGroupID 
	WHERE g.stt=1
)g
 ON g.GoodsID=CASE WHEN d.GoodsID=0 THEN r.GoodsID ELSE d.GoodsID  END AND CASE WHEN d.GoodsID=0 THEN r.Ppt1ID ELSE d.Ppt1ID END=ISNULL(g.Ppt1ID,0)  AND CASE WHEN d.GoodsID=0 THEN r.Ppt2ID ELSE d.Ppt2ID END=ISNULL(g.Ppt2ID,0) 
LEFT JOIN BD_Goods_Ppt1 p1 ON g.Ppt1ID = p1.Ppt1ID
LEFT JOIN BD_Goods_Ppt2 p2 ON g.Ppt2ID = p2.Ppt2ID
LEFT JOIN BD_Goods_Price u ON CASE WHEN d.GoodsID=0 THEN r.UnitID ELSE d.UnitID END = u.UnitID AND u.GoodsID=g.GoodsID
LEFT JOIN BD_Whs_Position wp ON wp.WhsPtID=d.WhsPtID AND wp.Stt=1
WHERE	BillNo=@BillNo  

GO








IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_OS_QueryFreightList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_OS_QueryFreightList
GO
/****** Object:  StoredProcedure [UP_OS_QueryFreightList]    Script Date: 21/10/2014 19:37:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/10/21
-- Description:	 运费结算单据查询
-- =============================================
CREATE PROCEDURE [UP_OS_QueryFreightList](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @BillStartDate DATETIME,                    --开始日期
	 @BillEndDate DATETIME,                    --结束日期
	 @BTypeID VARCHAR(1000) = '',            --往来单位
	 @ElyID VARCHAR(1000) = '',            --经手人
     @BillCodeMatch INT = 0,   --单据编号匹配方式
     @BillCode VARCHAR(100) = '', --单据编号
     @CreateStt INT = 2, --单据生成状态
     @HasError BIT = 0, --单据信息状态
     @IsPager BIT = 1, --是否分页
	 @OperatorID INT = 0                  --操作员ID  
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @Sql NVARCHAR(MAX) = '', @SqlParam NVARCHAR(1000) = N''
	SET @Sql = N'SELECT f.BillNo AS OSBillNo, f.BillCode, f.BillDate, f.ElyID,	f.Creator, f.LogistBTypeCode, f.IsCreate, 
	                    f.FreightFeeTotal, f.GatherTotal, CAST(f.SettleDate AS DATE) AS SettleDate, f.Summary, f.[Description], f.HasError, f.LogistBTypeCode AS BTypeCode '
	IF @IsPager = 0
	   BEGIN
	       SET @Sql = N' SELECT f.BillNo AS OSBillNo FROM OS_FreightBill f '
	   END
	ELSE
	   SET @Sql = N';WITH PagingData AS (' + @Sql + N' , r.BillNo FROM OS_FreightBillAll f 
	                                     LEFT JOIN OS_BillRelation r ON r.OSBillNo = f.BillNo AND OSOrderType = 1'
										 
    SET @SqlParam = ' WHERE f.BillDate BETWEEN @BillStartDate AND @BillEndDate AND HasError = @HasError '
       
    IF @BTypeID <> ''     --往来单位
	   SET @Sql += N' INNER JOIN BD_Btype btype ON btype.BTypeCode = f.LogistBTypeCode 
					  INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = btype.BTypeID'
	   
    IF @ElyID <> ''     --经手人
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = f.ElyID '
	     							
	IF @BillCode <> ''   --单据编号
	   BEGIN 
		   IF @BillCodeMatch = 0
			   SET @SqlParam += N' AND f.BillCode LIKE ''%'' + @BillCode +''%'''
		   ELSE IF @BillCodeMatch = 1
			   SET @SqlParam += N' AND f.BillCode = @BillCode ' 
	   END 
	
	IF @CreateStt <> 2
	    SET @SqlParam += N' AND f.IsCreate = @CreateStt '

	SET @Sql = @Sql + @SqlParam;
	
	IF @IsPager = 1
		SET @Sql = N'SET NOCOUNT ON;'
				   + @Sql + ')' + 
				   N', _DATA_BType AS (SELECT BTypeID, BTypeCode AS LocalBTypeCode, BTypeName, Stt AS BTypeStt FROM BD_Btype WHERE BtypeTypeID = 4)
					 , _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName, DeptId, Stt AS ElyStt FROM BD_Employee)
					 , _DATA_Creator AS (SELECT ElyID AS CreatorID, ElyCode AS CreatorCode, ElyName AS CreatorName FROM BD_Employee) ' + 
				   N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
								CROSS JOIN
							   (SELECT ROW_NUMBER() OVER(ORDER BY OSBillNo) AS ROWID,* FROM PagingData ) B
								WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
					   SELECT * FROM DATA 
						   LEFT JOIN _DATA_BType ON Data.LogistBTypeCode = _DATA_BType.LocalBTypeCode
						   LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID
						   LEFT JOIN _DATA_Creator ON Data.Creator = _DATA_Creator.CreatorID  ORDER BY ROWID'				
	--print @Sql	
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillStartDate DATETIME, 
							   @BillEndDate DATETIME, @BTypeID VARCHAR(1000), 
							   @ElyID VARCHAR(1000), @BillCode VARCHAR(100), @CreateStt INT, @HasError INT', 
	                         @PageNo, @PageSize, @BillStartDate, @BillEndDate, @BTypeID, @ElyID, @BillCode, @CreateStt, @HasError
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OS_QueryOrderBillList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_OS_QueryOrderBillList
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：hanlin
	日期：2014-10-16
	描述：网店订单管理
-------------------------------------------*/
CREATE PROCEDURE [UP_OS_QueryOrderBillList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate DATETIME,	--录单日期查询开始时间
	@BillEndDate DATETIME,	--录单日期查询结束时间
	@ElyNameMatch INT=0,
	@ElyName VARCHAR(100),
	@OSBillCode VARCHAR(100),
	@OSBillCodeMatch INT=0,
	@BillCode VARCHAR(100),
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100),
	@FullNameMatch INT=0,
	@IsCreate INT,
	@HasError INT,
	@BillType INT=0,
	@ShopID BIGINT
)

AS
SET NOCOUNT ON

if object_id('tempdb..#temp','U') is not null 
	drop table #temp
DECLARE @sql NVARCHAR(max)='',@JoinSql VARCHAR(max)='',@BillCodeStr VARCHAR(max)='',@OSBillCodeStr VARCHAR(max)='',@FullNameStr VARCHAR(max)='',@IsAll VARCHAR(3)='All'
IF @HasError=1 OR @IsCreate=0
	SET @IsAll=''
IF @billcode <>'' 
	SET @BillCodeStr = ' AND BillCode'+CASE @BillCodeMatch WHEN 0 THEN ' Like''%''+@BillCode+''%''' ELSE ' =@BillCode' END
IF @osbillcode <>'' 
	SET @OSBillCodeStr = ' AND OSBillCode'+CASE @OSBillCodeMatch WHEN 0 THEN ' Like''%''+@OSBillCode+''%''' ELSE ' =@OSBillCode' END
IF @FullName <>'' 
	SET @FullNameStr = ' AND EXISTS(SELECT 1 FROM OS_OrderDetail od WHERE od.BillNo=b.BillNo AND OSGoodsName'+CASE @FullNameMatch WHEN 0 THEN ' Like''%''+@FullName+''%''' ELSE ' =@FullName' END+') '
IF @ElyName<>''
BEGIN
	SET @JoinSql=' INNER JOIN BD_Employee E ON B.ElyID=E.ElyID ' 
END	
SET @sql+='
;WITH Data AS
(
SELECT	  0 AS selected,
		  b.BillNo,
		  b.BillCode ,
		  b.OSBillCode,
		  b.Summary,
		  BillType,
          CONVERT(VARCHAR(10),b.BillDate,120) BillDate ,
          CONVERT(VARCHAR(10),b.CreateTime,120) CreateTime,
          ShopID ,
          b.ElyID ,
          WhsID ,
          Description ,
          LogistBTypeCode ,
          FreightBillNo ,
          Freight ,
          PaidFreight ,
          BuyerAccount ,
          ContactWay ,
          Receiver ,
          Address ,
          BuyerMsg ,
          SaleComment ,
          BackReason ,
          SrcSendBillNo ,
          BackType ,
          DestSendBillNo ,
          IsCreate,
          OSGoodsName ,
          MerchantCode,
          PropsName,
          Qty ,
          Price ,
          d.DID,
          d.Total ,
          d.WhsPtID,
          d.MallFee,
          d.GoodsID,
          d.Ppt1ID,
          d.Ppt2ID,
          d.UnitID
FROM OS_OrderDetail'+@ISAll+' d
INNER JOIN OS_OrderBill'+@ISAll+' b ON d.BillNo = b.BillNo
'+@JoinSql+'
WHERE d.BillDate BETWEEN @BillStartDate AND @BillEndDate AND BillType=@BillType AND @HasError=HasError '

IF @ShopID<>0
	SET @sql+=' AND ShopID=@ShopID '
IF @BillCode<>''
	SET @sql +=@BillCodeStr	
IF @OSBillCode<>''
	SET @sql +=@OSBillCodeStr	
IF @FullName<>''
	SET @sql +=@FullNameStr	
IF @ElyName<>''	
	SET @sql +=' AND E.ElyName'+CASE @ElyNameMatch WHEN 2 THEN ' Like ''%''+@ElyName+''%''' WHEN 1 THEN ' =@ElyName' WHEN 0 THEN ' <>@ElyName' END
IF @IsCreate<>2
	SET @sql+=' AND IsCreate=@IsCreate'
	
SET @sql+=
')

SELECT * INTO #temp FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM Data) A
CROSS JOIN
(
SELECT	ROW_NUMBER() OVER( ORDER BY billno,DID) AS ROWID,
		RANK() OVER(PARTITION BY billno ORDER BY DID) Sort, 
		*
FROM Data
) B
WHERE B.ROWID>(@PageNo-1)*@PageSize
AND B.ROWID<=@PageNo*@PageSize

SELECT	t.*,
		g.GoodsName,
		g.GoodsNo, 
		p2.Value AS Ppt2Name,
		p1.Value AS Ppt1Name,
		u.Unit UnitName,
		w.WhsName,
		wp.WhsPtName,
		e.ElyName 
FROM #temp t
LEFT JOIN BD_Employee e ON e.ElyID=t.ElyID
LEFT JOIN OS_GoodsRelation r ON t.MerchantCode=r.MerchantCode
LEFT JOIN BD_Goods g ON g.GoodsID=CASE WHEN t.GoodsID=0 THEN r.GoodsID ELSE t.GoodsID END
LEFT JOIN BD_Goods_Ppt1 p1 ON CASE WHEN t.GoodsID=0 THEN r.Ppt1ID ELSE t.Ppt1ID END = p1.Ppt1ID
LEFT JOIN BD_Goods_Ppt2 p2 ON CASE WHEN t.GoodsID=0 THEN r.Ppt2ID ELSE t.Ppt2ID END = p2.Ppt2ID
LEFT JOIN BD_Goods_Price u ON CASE WHEN t.GoodsID=0 THEN r.UnitID ELSE t.UnitID END = u.UnitID AND u.GoodsID=g.GoodsID
LEFT JOIN BD_Whs w ON t.WhsID=w.WhsID
LEFT JOIN BD_Whs_Position wp ON wp.WhsPtID=t.WhsPtID
ORDER BY ROWID
DROP TABLE #temp'
--PRINT @sql
EXEC sp_executesql @sql,N'@PageNo INT,@PageSize INT,@BillStartDate DATETIME,@BillEndDate DATETIME,@BillType INT,@ShopID BIGINT,@IsCreate INT
		,@BillCode varchar(100),@OSBillCode VarChar(100),@FullName varchar(100),@HasError INT,@ElyName VarChar(MAX)',@PageNo,@PageSize,@BillStartDate,@BillEndDate,@BillType,@ShopID
		,@IsCreate,@billCode,@OSBillCode,@FullName,@HasError ,@ElyName
GO








IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OS_QueryOrderBillNo]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_OS_QueryOrderBillNo
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：hanlin
	日期：2014-10-16
	描述：网店订单管理
-------------------------------------------*/
CREATE PROCEDURE [UP_OS_QueryOrderBillNo]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate DATETIME,	--录单日期查询开始时间
	@BillEndDate DATETIME,	--录单日期查询结束时间
	@ElyNameMatch INT=0,
	@ElyName VARCHAR(100),
	@OSBillCode VARCHAR(100),
	@OSBillCodeMatch INT=0,
	@BillCode VARCHAR(100),
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100),
	@FullNameMatch INT=0,
	@IsCreate INT,
	@BillType INT=0,
	@ShopID BIGINT,
	@HasError INT=0
)

AS
SET NOCOUNT ON

DECLARE @sql NVARCHAR(max)='',@JoinSql VARCHAR(max)='',@BillCodeStr VARCHAR(max)='',@OSBillCodeStr VARCHAR(max)='',@FullNameStr VARCHAR(max)=''
IF @billcode <>'' 
	SET @BillCodeStr = ' AND BillCode'+CASE @BillCodeMatch WHEN 0 THEN ' Like''%''+@BillCode+''%''' ELSE ' =@BillCode' END
IF @osbillcode <>'' 
	SET @OSBillCodeStr = ' AND OSBillCode'+CASE @OSBillCodeMatch WHEN 0 THEN ' Like''%''+@OSBillCode+''%''' ELSE ' =@OSBillCode' END
IF @FullName <>'' 
	SET @FullNameStr = ' AND EXISTS(SELECT 1 FROM OS_OrderDetail od WHERE od.BillNo=b.BillNo AND OSGoodsName'+CASE @FullNameMatch WHEN 0 THEN ' Like''%''+@FullName+''%''' ELSE ' =@FullName' END+') '
IF @ElyName<>''
BEGIN
	SET @JoinSql=' INNER JOIN BD_Employee E ON B.ElyID=E.ElyID ' 
END	
SET @sql='
SELECT	 b.BillNo
FROM OS_OrderBill b '
+@JoinSql+
'WHERE b.BillDate BETWEEN @BillStartDate AND @BillEndDate AND BillType=@BillType AND HasError=@HasError '
IF @ShopID<>0
	SET @sql+=' AND ShopID=@ShopID '
IF @BillCode<>''
	SET @sql +=@BillCodeStr	
IF @OSBillCode<>''
	SET @sql +=@OSBillCodeStr	
IF @FullName<>''
	SET @sql +=@FullNameStr	
IF @ElyName<>''	
	SET @sql +=' AND E.ElyName'+CASE @ElyNameMatch WHEN 2 THEN ' Like ''%''+@ElyName+''%''' WHEN 1 THEN ' =@ElyName' WHEN 0 THEN ' <>@ElyName' END	
IF @IsCreate<>2
	SET @sql+=' AND IsCreate=@IsCreate'
EXEC sp_executesql @sql,N'@PageNo INT,@PageSize INT,@BillStartDate DATETIME,@BillEndDate DATETIME,@BillType INT,@ShopID BIGINT,@IsCreate INT,@BillCode varchar(100),
@FullName varchar(100),@HasError INT,@ElyNameMatch INT=0,@ElyName VARCHAR(100),@OSBillCode VARCHAR(100),@OSBillCodeMatch INT=0'
,@PageNo,@PageSize,@BillStartDate,@BillEndDate,@BillType,@ShopID,@IsCreate,@billCode,@FullName,@HasError,@ElyNameMatch,@ElyName,@OSBillCode,@OSBillCodeMatch
GO








IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OS_QueryOrderBillReport]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_OS_QueryOrderBillReport
GO

SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：sunzhiyuan
	日期：2015-4-2
	描述：网店订单统计
-------------------------------------------*/
CREATE PROCEDURE [UP_OS_QueryOrderBillReport]
(
	@PageNo INT=1,              -- 页码
	@PageSize INT=10,           -- 页大小
	@BillStartDate DATETIME,	-- 录单日期查询开始时间
	@BillEndDate DATETIME,	    -- 录单日期查询结束时间
	@ShopID VARCHAR(MAX),       -- 网店
	@BuyerID VARCHAR(100),      -- 买家账号
	@Province VARCHAR(100),     -- 省
	@City VARCHAR(100),         -- 市
	@District VARCHAR(100),     -- 区
	@SumParam INT = 1,          -- 汇总条件
	@OrderStr VARCHAR(50) = ''  -- 排序字符串
)
AS
BEGIN
SET NOCOUNT ON
	DECLARE @HeadSql NVARCHAR(2000)= N'',
			@BillHeadSql NVARCHAR(2000)= N'',
			@CostHeadSql NVARCHAR(2000)= N'',
			@PageHeadSql NVARCHAR(2000)= N'',
	        @Sql NVARCHAR(MAX) = N'', 
	        @SqlGroup NVARCHAR(1000) = N'', 
		    @SqlParam NVARCHAR(1000) = N'',
	        @PageDataName NVARCHAR(20) = N'PagingData',
	        @ShopSql NVARCHAR(1000)= N'',
	        @BillParam NVARCHAR(1000) = N''

	-- 赠品成本 isnull((SELECT SUM(Total) from OS_OrderDetailAll where Gift = 1),0) as GiftCost,     
	-----------------------查询条件----------------------
	-- 网店	   
	IF @ShopID <> ''
	BEGIN
		SET @ShopSql = N' INNER JOIN dbo.UF_OT_Split(@ShopID, '','') ShopID ON ShopID.a = bill.ShopID '
		
	END
	
	-- 买家账号	   
	IF @BuyerID <> ''
	BEGIN
		SET @SqlParam += N' AND BuyerAccount = @BuyerID '
		SET @BillParam += @SqlParam
	END
	
	-- 省
	IF @Province <> ''
	BEGIN
		SET @SqlParam += N' AND ReceiverProvince = @Province '
		SET @BillParam += @SqlParam
	END
	
	-- 市
	IF @City <> ''
	BEGIN
		SET @SqlParam += N' AND ReceiverCity = @City '
		SET @BillParam += @SqlParam
	END
	
	-- 区
	IF @District <> ''
	BEGIN
		SET @SqlParam += N' AND ReceiverDistrict = @District '
		SET @BillParam += @SqlParam
	END
	-----------------------汇总条件-------------------------
	-- 网店
	IF @SumParam = 1
	BEGIN
	
		SET @PageHeadSql += N',SUM(BuyerNum) AS BuyerNum,SUM(SaleTotal)/SUM(BuyerNum) AS BuyPrice,ShopID'
		SET @CostHeadSql += N', 0 AS BuyerNum,ShopID'
		SET @BillHeadSql += N',COUNT(distinct bill.BuyerAccount) AS BuyerNum,ShopID'
		--,COUNT(bill.BuyerAccount) AS BuyerNum,SUM(bill.Total)/COUNT(bill.BuyerAccount) AS BuyPrice '
		SET @SqlGroup = N' ShopID'
		SET @BillParam += N' AND a.ShopID = bill.ShopID '
	END
	
	-- 买家
	IF @SumParam = 2
	BEGIN
		SET @CostHeadSql += N', BuyerAccount '
		SET @BillHeadSql += N', BuyerAccount '
		SET @PageHeadSql += N', BuyerAccount '
		SET @SqlGroup = N' BuyerAccount'
		SET @BillParam += N' AND a.BuyerAccount = bill.BuyerAccount '
	END
	
	-- 省
	IF @SumParam = 3
	BEGIN
		SET @CostHeadSql += N', ReceiverProvince '
		SET @BillHeadSql += N', ReceiverProvince '
		SET @PageHeadSql += N', ReceiverProvince '
		SET @SqlGroup = N' ReceiverProvince'
		SET @BillParam += N' AND a.ReceiverProvince = bill.ReceiverProvince '
	END
	
	-- 市
	IF @SumParam = 4
	BEGIN
		SET @CostHeadSql += N', ReceiverProvince,ReceiverCity '
		SET @BillHeadSql += N', ReceiverProvince,ReceiverCity '
		SET @PageHeadSql += N', ReceiverProvince,ReceiverCity '
		SET @SqlGroup = N' ReceiverProvince,ReceiverCity'
		SET @BillParam += N' AND a.ReceiverCity = bill.ReceiverCity '
	END
	
	-- 区
	IF @SumParam = 5
	BEGIN
		SET @BillHeadSql += N', ReceiverProvince,ReceiverCity,ReceiverDistrict '
		SET @CostHeadSql += N', ReceiverProvince,ReceiverCity,ReceiverDistrict '
		SET @PageHeadSql += N', ReceiverProvince,ReceiverCity,ReceiverDistrict '
		SET @SqlGroup = N' ReceiverProvince,ReceiverCity,ReceiverDistrict'
		SET @BillParam += N' AND a.ReceiverDistrict = bill.ReceiverDistrict '
	END
	
	--查询条件
	IF @SqlParam <> ''  
	BEGIN
		SET @SqlParam = ' WHERE IsCreate = 1 AND BillType = 0 AND bill.BillDate BETWEEN @BillStartDate AND @BillEndDate ' + @SqlParam
    END
    ELSE
    BEGIN
		SET @SqlParam = ' WHERE IsCreate = 1 AND BillType = 0 AND bill.BillDate BETWEEN @BillStartDate AND @BillEndDate '
    END
    
    -- 拼接SQL
    -- costdata:计算成本金额
    -- billdata:计算销售笔数 销售收入 商城扣费 买家运费 预计运费 销售比重
    -- AllData:合并costdata和billdata数据
    -- PagingData:最后
    SET @Sql += N';With costdata as(
							SELECT 
								0 AS SaleNum,
								0 AS SaleTotal,
								0 AS StoreCost,
								0 AS BuyFreight,
								0 AS PaidFreight,
								0 AS Salepercent,
								SUM(SellDetail.GoodsCostTotal) AS CostTotal
							' + @CostHeadSql + '		
							FROM OS_orderbillall bill 
							' + @ShopSql + '
							
							INNER JOIN PD_SellBill Sell ON bill.BillCode = Sell.Description AND Sell.IsOS = 1 AND Sell.IsDraft = 0
							INNER join PD_SellDetail SellDetail on Sell.BillNo = SellDetail.BillNo 
							'+ @SqlParam + 
							 ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1) + '
							),
						billdata AS(
							SELECT 
								(SELECT COUNT(1) FROM OS_orderbillall a WHERE a.BillDate BETWEEN @BillStartDate AND @BillEndDate and IsCreate = 1 AND BillType = 0 '+@BillParam+') AS SaleNum,             
								SUM(bill.Total) AS SaleTotal,
								SUM(bill.MallFee) AS StoreCost,
								SUM(bill.Freight) AS BuyFreight,
								SUM(bill.PaidFreight)  AS PaidFreight,
								CAST(SUM(bill.Total)/(SELECT SUM(Total) FROM os_orderbillall a WHERE a.BillDate BETWEEN @BillStartDate AND @BillEndDate and IsCreate = 1 AND BillType = 0) AS DECIMAL(18,4)) * 100 AS Salepercent, 
								0 AS CostTotal
								' + @BillHeadSql + '
							 FROM OS_orderbillall bill
							 ' + @ShopSql + 
							 + @SqlParam + 
							 ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1) + '
						), 
						AllData AS(
							SELECT * FROM  costdata
							UNION ALL 
							SELECT * FROM billdata
						),
						PagingData AS (
							SELECT 
								   SUM(SaleNum) AS SaleNum ,
								   SUM(SaleTotal) AS SaleTotal,
								   SUM(StoreCost) AS StoreCost,
								   SUM(BuyFreight) AS BuyFreight,
								   SUM(PaidFreight) AS PaidFreight,
								   SUM(Salepercent) AS Salepercent,
								   SUM(CostTotal) AS CostTotal,
								   SUM(SaleTotal - CostTotal) AS SaleGross
								   ' + @PageHeadSql + '
							FROM AllData 
							'+ ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1) + '
						)'
    

    -- 分页
    SET @Sql+=' SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
				CROSS JOIN
				(SELECT	ROW_NUMBER() OVER( ORDER BY ' + @OrderStr + ') AS ROWID,* FROM PagingData) B
				WHERE B.ROWID > (@PageNo - 1) * @PageSize AND B.ROWID <= @PageNo * @PageSize '
    
	print @Sql
    EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillStartDate DATETIME, @BillEndDate DATETIME, @ShopID VARCHAR(MAX),
	                           @BuyerID VARCHAR(100), @Province VARCHAR(100), @City VARCHAR(100), @District VARCHAR(100)', 
	                         @PageNo, @PageSize, @BillStartDate, @BillEndDate, @ShopID, 
	                         @BuyerID,@Province, @City, @District
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OS_QueryOrderBillReportDetail]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_OS_QueryOrderBillReportDetail
GO

SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：sunzhiyuan
	日期：2015-4-8
	描述：网店订单统计明细
	updateDate:2015.5.20 sunzhiyuan 增加列原始网店订单号
-------------------------------------------*/
CREATE PROCEDURE [UP_OS_QueryOrderBillReportDetail]
(
	@PageNo INT=1,              -- 页码
	@PageSize INT=10,           -- 页大小
	@BillStartDate DATETIME,	-- 录单日期查询开始时间
	@BillEndDate DATETIME,	    -- 录单日期查询结束时间
	@ShopID VARCHAR(max),       -- 网店
	@BuyerID VARCHAR(100),      -- 买家账号
	@Province VARCHAR(100),     -- 省
	@City VARCHAR(100),         -- 市
	@District VARCHAR(100),     -- 区
	@SumParam INT = 1,          -- 汇总条件
	@OrderStr VARCHAR(50) = ''  -- 排序字符串
)
AS
BEGIN
SET NOCOUNT ON
	DECLARE @HeadSql NVARCHAR(2000),
	        @Sql NVARCHAR(MAX), 
		    @SqlParam NVARCHAR(1000) = N'',
	        @PageDataName NVARCHAR(20) = N'PagingData'
	
	
	
	-- 单据日期 发货日期 网店单据编号 经手人 摘要 说明
	-- 网店商品名称 网店商品属性 发货仓库 数量 单价 
	-- 商城扣费 商品编码 商品名称 计量单位 
	SET @HeadSql = N';With PagingData AS (
						SELECT CONVERT(VARCHAR(10),bill.CreateTime,120) CreateTime,CONVERT(VARCHAR(10),bill.BillDate,120) BillDate,BillCode,employee.ElyName,Summary,Description,OSBillCode,
							   OSGoodsName,PropsName,WhsName,detail.Qty,detail.Price,detail.Total,
							   detail.MallFee,Goods.GoodsNo,Goods.GoodsName,Goods_Price.Unit  
					'
							   
	SET @Sql = N' FROM OS_OrderBillAll bill 
					LEFT JOIN OS_OrderDetailAll detail ON bill.BillNo = detail.BillNo
					LEFT JOIN BD_Employee employee ON employee.ElyID = bill.ElyID
					LEFT JOIN OS_GoodsRelation GoodsRelation ON detail.MerchantCode=GoodsRelation.MerchantCode
					LEFT JOIN BD_Goods Goods ON Goods.GoodsID=CASE WHEN detail.GoodsID=0 THEN GoodsRelation.GoodsID ELSE detail.GoodsID END
					LEFT JOIN BD_Whs Whs ON bill.WhsID =Whs.WhsID
					LEFT JOIN BD_Whs_Position Whs_Position ON Whs_Position.WhsPtID=detail.WhsPtID
					LEFT JOIN BD_Goods_Price Goods_Price ON CASE WHEN detail.GoodsID=0 THEN detail.UnitID ELSE detail.UnitID END = Goods_Price.UnitID AND Goods_Price.GoodsID = Goods.GoodsID
				'     
	
	-----------------------查询条件----------------------
	-- 网店	   
	IF @ShopID <> ''
	BEGIN
		SET @Sql += N' INNER JOIN dbo.UF_OT_Split(@ShopID, '','') ShopID ON ShopID.a = bill.ShopID '
	END
	
	
	-- 买家账号	   
	IF @BuyerID <> ''
	BEGIN
		SET @SqlParam += N' AND BuyerAccount = @BuyerID '
	END
	ELSE IF @SumParam = 2
	BEGIN
		SET @SqlParam += N' AND BuyerAccount = @BuyerID '
	END
	
	
	-- 省
	IF @Province <> ''
	BEGIN
		SET @SqlParam += N' AND ReceiverProvince = @Province '
	END
	
	-- 市
	IF @City <> ''
	BEGIN
		SET @SqlParam += N' AND ReceiverCity = @City '
	END
	
	-- 区
	IF @District <> ''
	BEGIN
		SET @SqlParam += N' AND ReceiverDistrict = @District '
	END
	-----------------------汇总条件-------------------------
	-- 网店
	IF @SumParam = 1
	BEGIN
		SET @HeadSql += N', bill.ShopID '
	END
	
	-- 买家
	IF @SumParam = 2
	BEGIN
		SET @HeadSql += N', bill.BuyerAccount '
	END
	
	-- 省
	IF @SumParam = 3
	BEGIN
		SET @HeadSql += N', bill.ReceiverProvince '
	END
	
	-- 市
	IF @SumParam = 4
	BEGIN
		SET @HeadSql += N', bill.ReceiverProvince,bill.ReceiverCity '
	END
	
	-- 区
	IF @SumParam = 5
	BEGIN
		SET @HeadSql += N', bill.ReceiverProvince,bill.ReceiverCity,bill.ReceiverDistrict '
	END
	
	--查询条件
	IF @SqlParam <> ''  
	BEGIN
		SET @SqlParam = ' WHERE IsCreate = 1 AND BillType = 0 AND bill.BillDate BETWEEN @BillStartDate AND @BillEndDate ' + @SqlParam
    END
    ELSE
    BEGIN
		SET @SqlParam = ' WHERE IsCreate = 1 AND BillType = 0 AND bill.BillDate BETWEEN @BillStartDate AND @BillEndDate '
    END
    
    -- 拼接SQL
    SET @Sql = @HeadSql + @Sql + @SqlParam 
    
    
    -- 分页
    SET @Sql+=') SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
				CROSS JOIN
				(SELECT	ROW_NUMBER() OVER( ORDER BY BillCode ) AS ROWID,* FROM PagingData) B
				WHERE B.ROWID > (@PageNo - 1) * @PageSize AND B.ROWID <= @PageNo * @PageSize '
    
    EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillStartDate DATETIME, @BillEndDate DATETIME, @ShopID VARCHAR(MAX),
	                           @BuyerID VARCHAR(100), @Province VARCHAR(100), @City VARCHAR(100), @District VARCHAR(100)', 
	                         @PageNo, @PageSize, @BillStartDate, @BillEndDate, @ShopID, 
	                         @BuyerID,@Province, @City, @District
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_OS_QuerySyncStockError]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_OS_QuerySyncStockError
GO
/****** Object:  StoredProcedure [UP_OS_QuerySyncStockError]    Script Date: 7/16/2015 11:02:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/7/16
-- Description:	 同步库存的异常记录
-- =============================================
CREATE PROCEDURE [UP_OS_QuerySyncStockError](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @OperatorID INT = 0                  --操作员ID  
   ) 
AS
BEGIN
	SET NOCOUNT ON;
    ;WITH PagingData AS (
	SELECT err.WhsID, err.GoodsID, err.Ppt1ID, err.Ppt2ID, err.SyncTime, err.ErrorMsg, w.WhsNO, w.WhsName, g.GoodsNo, g.GoodsName, SUM(ISNULL(s.Qty,0)) AS StockQty
		   FROM dbo.OS_SyncStockError err
		   INNER JOIN dbo.OS_SyncStockWhs sync ON err.WhsID = sync.WhsID
		   INNER JOIN dbo.BD_Whs w ON err.WhsID = w.WhsID
		   INNER JOIN dbo.BD_Goods g ON g.GoodsID = err.GoodsID
		   INNER JOIN dbo.PD_GoodsStock gs ON gs.GoodsID = err.GoodsID AND gs.WhsID = err.WhsID
		   LEFT JOIN dbo.PD_GoodsStock_Detail s ON s.StockID = gs.StockID AND s.Ppt1ID = err.Ppt1ID AND s.Ppt2ID = err.Ppt2ID
		   WHERE g.IsOS = 1 AND w.Stt = 1
		   GROUP BY err.WhsID, err.GoodsId, err.Ppt1ID, err.Ppt2ID, err.SyncTime, err.ErrorMsg, w.WhsNO, w.WhsName, g.GoodsNo, g.GoodsName
		   )
		   ,DATA AS (SELECT * FROM (SELECT COUNT(1) AS 'ROWCOUNT' FROM PagingData ) A 
					CROSS JOIN
				  (SELECT ROW_NUMBER() OVER(ORDER BY WhsNO) AS ROWID,* FROM PagingData ) B
					WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
	SELECT DATA.*, p.Unit, p1.Value AS Ppt1Name, p2.Value AS Ppt2Name FROM DATA 
	LEFT JOIN dbo.BD_Goods_Price p ON p.GoodsID = DATA.GoodsID AND p.UnitID = 1
	LEFT JOIN dbo.BD_Goods_Ppt1 p1 ON p1.Ppt1ID = DATA.Ppt1ID
	LEFT JOIN dbo.BD_Goods_Ppt2 p2 ON p2.Ppt2ID = DATA.Ppt2ID
	ORDER BY ROWID
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_OS_QuerySyncStockWhs]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_OS_QuerySyncStockWhs
GO
/****** Object:  StoredProcedure [UP_OS_QuerySyncStockWhs]    Script Date: 5/6/2015 16:11:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/5/6
-- Description:	 同步库存的仓库
-- =============================================
CREATE PROCEDURE [UP_OS_QuerySyncStockWhs](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @OperatorID INT = 0                  --操作员ID  
   ) 
AS
BEGIN
	SET NOCOUNT ON;
    DECLARE @Sql NVARCHAR(MAX) = '', @KtypeLimit INT

	SET @Sql = N';WITH PagingData AS (SELECT a.WhsID, a.WhsNO, a.WhsName, b.WhsID AS CheckWhsID, 
	              CASE WHEN b.WhsID IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END AS IsChecked FROM dbo.BD_Whs a '
	                    
    --仓库权限   
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)       
	        
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = a.WhsID '
	   
    SET @Sql += ' LEFT JOIN dbo.OS_SyncStockWhs b ON a.WhsID = b.WhsID '
    
	SET @Sql = N'SET NOCOUNT ON;'
			   + @Sql + ' WHERE a.Stt = 1)' + 
			   N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
							CROSS JOIN
						   (SELECT ROW_NUMBER() OVER(ORDER BY WhsNO) AS ROWID,* FROM PagingData ) B
							WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				   SELECT * FROM DATA ORDER BY ROWID'				

	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @OperatorID INT', @PageNo, @PageSize, @OperatorID
END
GO




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

/*------------------------------------------
    作者：Hlin
	日期：2014-05-15
	描述：商家编码TC查询
-------------------------------------------*/
CREATE PROCEDURE UP_OS_TCMcCodeList
(
	@PageNo INT=1,
	@PageSize INT=50,
	@Type INT=0,
	@SearchStr VARCHAR(max)
)

AS

DECLARE @sql NVARCHAR(max),@LikeStr VARCHAR(500)=''
IF @Type=0
	SET @LikeStr= 'LIKE ''%'+@SearchStr+'%'''	
ELSE
	SET @LikeStr= '='''+@SearchStr+''''
	
SET @sql='
WITH CodeData AS
(
	SELECT	MerchantCode,
			r.GoodsID,
			g.GoodsName,
			g.GoodsNo,
			ISNULL(p1.Ppt1ID,0) Ppt1ID,
			p1.VALUE AS Ppt1Name,
			ISNULL(p2.Ppt2ID,0) Ppt2ID,
			p2.VALUE AS Ppt2Name,
			r.UnitID,
			u.Unit
	FROM OS_GoodsRelation r
	INNER JOIN BD_Goods g ON r.GoodsID = g.GoodsID
	LEFT JOIN BD_Goods_PptGroup p ON g.PptGroupID=p.PptGroupID 
	LEFT JOIN BD_Goods_Ppt1 p1 ON r.Ppt1ID=p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON r.Ppt2ID=p2.Ppt2ID
	INNER JOIN BD_Goods_Price u ON r.UnitID=u.UnitID AND g.GoodsID=u.GoodsID
	WHERE g.Stt=1 AND u.Stt=1 AND ISNULL(p.Ppt1ID,0)=r.Ppt1ID  AND ISNULL(p.Ppt2ID,0)= r.Ppt2ID 
		 AND ( MerchantCode '+@LikeStr+' OR g.GoodsNo '+@LikeStr+' OR g.GoodsName '+@LikeStr+')'
SET @sql+='
)
SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM CodeData) A
CROSS JOIN
(
	SELECT	ROW_NUMBER() OVER( ORDER BY  MerchantCode) AS ROWID,
	*
	FROM CodeData
) B
WHERE B.ROWID>(@PageNo-1)*@PageSize
AND B.ROWID<=@PageNo*@PageSize
'
EXEC sp_executesql @sql,N'@PageNo INT,@PageSize INT',@PageNo,@PageSize
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OT_CheckHistoryTime]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_OT_CheckHistoryTime]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*------------------------------------------
    作者：wwei
	日期：2014-08-18
	描述：检查查询历史数据是否小于搬移的时期
-------------------------------------------*/
CREATE PROCEDURE [UP_OT_CheckHistoryTime]
(			   
	@BillStartDate DATE			--单据开始日期
	,@IsHistory INT=0				--是否勾选查询历史数据
)

AS
SET NOCOUNT ON

DECLARE @Date date
SELECT @Date=Max(EndDate) FROM SS_MonthProc where [State]=1 
if(@Date IS NULL)return 0;
IF(@IsHistory=0  AND @BillStartDate<=@Date)
BEGIN
	declare @tip NVarchar(300)
		SET @tip=CAST(@Date as nvarchar(50))+'前的数据已归档,请修改查询日期范围或勾选【包含已归档数据】选项后再进行查询' 
	RAISERROR (@tip, 16, 1) WITH NOWAIT
	RETURN 1
END
	return 0;
GO







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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-6-26
	描述：数据归档
-------------------------------------------*/
CREATE PROCEDURE [UP_OT_DataArchive]
(
	@startDate Date,
	@endDate Date,
	@BillTypeID Int
)

AS
SET NOCOUNT ON

Declare @TagStr1 varchar(200)='',@TagStr2 varchar(200)='',@TagStr3 varchar(200)='',@TagStr4 varchar(200)='',@TagStr5 varchar(200)='',@TagStr6 varchar(200)=''
if exists(select 1 from SS_SysCfg where CfgName='AccountType' and CfgValue = 1 and ID=101)
Begin
	Set @TagStr1 += ' and ((FreightStlTag = 2 And StlTag = 2) or Red in (1,2)) '
	Set @TagStr2 += ' or Red in (1,2) '
	Set @TagStr3 += ' and (StlTag = 2 or Red in (1,2))'
	Set @TagStr4 += ' and ((FreightStlTag = 2 And StlTag = 2) or B.Red in (1,2)) '
	Set @TagStr5 += ' or B.Red in (1,2) '
	Set @TagStr6 += ' and (StlTag = 2 or B.Red in (1,2))'
	
End

declare @sqlBill nvarchar(max)='
	SET XACT_ABORT ON
	BEGIN TRAN T
	BEGIN
	' 
-------归档财务，调拨类单据数据-------		
	select @sqlBill += ' 
		insert into '+ BillTable + '_His(' + dbo.UF_OT_GetColumns(BillTable,'','')+') select ' + dbo.UF_OT_GetColumns(BillTable,'','')+' from '+BillTable+' where IsDraft = 0 and BillDate <= @endDate '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+ ' Insert into '+ BillDetail +'_His(' + dbo.UF_OT_GetColumns(BillDetail,'','')+') select ' + dbo.UF_OT_GetColumns(BillDetail,'a.','')+' from '+ BillDetail +' a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 and B.BillDate <= @endDate	'
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+Case When BillTypeID In (401,402) then ' Insert Into MF_PayRecList_His('+dbo.UF_OT_GetColumns('MF_PayRecList','','')+') Select ' + dbo.UF_OT_GetColumns('MF_PayRecList','a.','')+' from MF_PayRecList a Inner Join MF_PayRecBill b on a.PayRecBillNo = b.BillNo where IsDraft = 0 and BillDate <= @endDate AND B.BillTypeID='+Cast(BillTypeID AS varchar) else '' end
		+' Insert Into PD_ListTable_His(LID,BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,JTotal,DTotal,IsReconciled,[Order],Red) Select a.LID,a.BillNo,a.BillTypeID,a.BillDate,a.FinanceID,a.BtypeID,a.DeptID,a.ElyID,a.JTotal,a.DTotal,a.IsReconciled,a.[Order],a.Red from PD_ListTable a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 and B.BillDate <= @endDate and A.BillTypeID = ' + CONVERT(varchar(5), BillTypeID)
	from PD_BillType where BillTypeID in (301,302,303,304,305,306,309,310,401,402,406,600,602) and BillTypeID= @BillTypeID

-------归档财务，物流类单据数据-------		
	Select @sqlBill +='
		insert into '+ BillTable + '_His(' + dbo.UF_OT_GetColumns(BillTable,'','')+') select ' + dbo.UF_OT_GetColumns(BillTable,'','')+' from '+BillTable+' where IsDraft = 0 '
		+ ' and BillDate <= @endDate '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+ case when BillTypeID in (101,201) then @TagStr1 when BillTypeID = 403 then @TagStr2 else @TagStr3 end 
		+' Insert into '+ BillDetail +'_His(' + dbo.UF_OT_GetColumns(BillDetail,'','')+') select ' + dbo.UF_OT_GetColumns(BillDetail,'a.','')+' from '+ BillDetail +' a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 '
		+ ' and B.BillDate <= @endDate	'
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND B.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+ case when  BillTypeID in (101,201) then @TagStr1 when BillTypeID = 403 then @TagStr2 else @TagStr3 end 
		+' Insert Into PD_ListTable_His(LID,BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,JTotal,DTotal,IsReconciled,[Order],Red) Select a.LID,a.BillNo,a.BillTypeID,a.BillDate,a.FinanceID,a.BtypeID,a.DeptID,a.ElyID,a.JTotal,a.DTotal,a.IsReconciled,a.[Order],a.Red from PD_ListTable a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 '
		+' and B.BillDate <= @endDate And A.BillTypeID = ' + CONVERT(varchar(5), BillTypeID)
		+ case when  BillTypeID in (101,201) then @TagStr4 when BillTypeID = 403 then @TagStr5 else @TagStr6 end 
	from PD_BillType where BillTypeID in (101,102,201,202,403,404,405,501,502,503,504) and BillTypeID= @BillTypeID

-------归档序列号信息--------
	Select @sqlBill += ' insert into '+BillSerial + '_his(' + dbo.UF_OT_GetColumns(BillSerial,'','')+') select ' + dbo.UF_OT_GetColumns(BillSerial,'a.','')+ ' from ' + BillSerial + ' a inner join ' +BillDetail+ ' b on a.BillDid = b.DID Inner Join ' + BillTable + ' c on b.BillNo = c.BillNo '
		+ ' where c.IsDraft = 0 '
		+ case when BillTypeID in (101,201) then @TagStr1 When BillTypeID in (102,202) then @TagStr3 else '' end
		+ ' And C.BillDate <= @endDate '	
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND C.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	from PD_BillType where BillTypeID in (101,102,201,202,301, 302, 303, 304, 305, 306, 309,310,600) And BillTypeID = @BillTypeID

-------归档订单申请单数据-------		
	Select @sqlBill += '
		 insert into '+ BillTable + '_His(' + dbo.UF_OT_GetColumns(BillTable,'','')+') select ' + dbo.UF_OT_GetColumns(BillTable,'','')+' from '+ BillTable + '  where BillDate <= @endDate and BillNo not in (select distinct BillNo from '+ BillDetail +' where (ComQty < BSQty)) or StopTag = 1 
		 insert into '+ BillDetail +'_His(' + dbo.UF_OT_GetColumns(BillDetail,'','')+') select ' + dbo.UF_OT_GetColumns(BillDetail,'a.','')+' from  '+ BillDetail +' a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where b.BillDate <= @endDate and b.BillNo not in (select distinct BillNo from '+ BillDetail +' where (ComQty < BSQty)) or b.StopTag = 1 
		 '
	from PD_BillType where BillTypeID in (100,200,308) and BillTypeID= @BillTypeID
-------归档采购、销售开票金额数据-----
	if(@BillTypeID = 10101)
	begin
		Select @sqlBill += '
		 insert into MF_PchInvoiceBill_His(' + dbo.UF_OT_GetColumns('MF_PchInvoiceBill','','')+') select ' + dbo.UF_OT_GetColumns('MF_PchInvoiceBill','','')+' from MF_PchInvoiceBill where BillDate <= @endDate And IsDraft = 0  
		 insert into MF_PchInvoiceDetail_His(' + dbo.UF_OT_GetColumns('MF_PchInvoiceDetail','','')+') select ' + dbo.UF_OT_GetColumns('MF_PchInvoiceDetail','a.','')+' from MF_PchInvoiceDetail a Inner join MF_PchInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0
		 insert into MF_PchInvoiceContent_His(' + dbo.UF_OT_GetColumns('MF_PchInvoiceContent','','')+') select ' + dbo.UF_OT_GetColumns('MF_PchInvoiceContent','a.','')+' from MF_PchInvoiceContent a Inner join MF_PchInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0
		 '
	End
	if(@BillTypeID = 20101)
	begin
		Select @sqlBill += '
		 insert into MF_SellInvoiceBill_His(' + dbo.UF_OT_GetColumns('MF_SellInvoiceBill','','')+') select ' + dbo.UF_OT_GetColumns('MF_SellInvoiceBill','','')+' from MF_SellInvoiceBill where BillDate <= @endDate And IsDraft=0  
		 insert into MF_SellInvoiceDetail_His(' + dbo.UF_OT_GetColumns('MF_SellInvoiceDetail','','')+') select ' + dbo.UF_OT_GetColumns('MF_SellInvoiceDetail','a.','')+' from MF_SellInvoiceDetail a Inner join MF_SellInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0
		 insert into MF_sellInvoiceContent_His(' + dbo.UF_OT_GetColumns('MF_sellInvoiceContent','','')+') select ' + dbo.UF_OT_GetColumns('MF_sellInvoiceContent','a.','')+' from MF_sellInvoiceContent a Inner join MF_SellInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0
		 '
	End
	
-------删除序列号信息-------
	select @sqlBill += ' Delete '+BillSerial+' from '+ BillSerial + ' a inner join ' +BillDetail+ ' b on a.BillDid = b.DID Inner Join  ' + BillTable + ' c on b.BillNo = c.BillNo '
		+ ' where c.IsDraft = 0 '
		+ case when BillTypeID in (101,201) then @TagStr1 When BillTypeID in (102,202) then @TagStr3 else '' end
		+ ' And C.BillDate <= @endDate '	
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND C.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	from PD_BillType where BillTypeID in (101,102,201,202,301, 302, 303, 304, 305, 306, 309,310,600) And BillTypeID = @BillTypeID
	
-------删除财务，调拨类单据归档成功数据-------		
	select @sqlBill += '
	 Delete '+BillDetail+' from '+BillDetail+' a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 and B.BillDate <= @endDate '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND b.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+Case When BillTypeID In (401,402) then ' Delete MF_PayRecList from  MF_PayRecList a Inner Join  '+BillTable+' b on a.PayRecBillNo = b.BillNo where IsDraft = 0 and B.BillDate <= @endDate AND B.BillTypeID='+Cast(BillTypeID AS varchar) else '' end
		+' Delete PD_ListTable from PD_ListTable a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 and b.BillDate <= @endDate And A.BillTypeID=' + CONVERT(varchar(5), BillTypeID)
		+' Delete '+BillTable+' where IsDraft = 0 and BillDate <= @endDate '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		from PD_BillType where BillTypeID in (301,302,303,304,305,306,309,310,401,402,406,600,602) and BillTypeID= @BillTypeID
-------删除财务，物流类单据归档成功数据-------		
	select @sqlBill += '
	 Delete '+BillDetail+' from '+BillDetail+' a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 '
		+ ' and B.BillDate <= @endDate '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND B.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+ case when  BillTypeID in (101,201) then @TagStr1 when BillTypeID = 403 then @TagStr2 else @TagStr3 end 
		+' Delete PD_ListTable from PD_ListTable a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where IsDraft = 0 '
		+ ' and B.BillDate <= @endDate And A.BillTypeID = ' + CONVERT(varchar(5), BillTypeID)
		+ case when  BillTypeID in (101,201) then @TagStr4 when BillTypeID = 403 then @TagStr5 else @TagStr6 end 
		+' Delete '+BillTable+' where IsDraft = 0 '
		+ ' and BillDate <= @endDate '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+ case when  BillTypeID in (101,201) then @TagStr1 when BillTypeID = 403 then @TagStr2 else @TagStr3 end
	from PD_BillType where BillTypeID in (101,102,201,202,403,404,405,501,502,503,504) and BillTypeID= @BillTypeID
-------删除采购、销售订单和调拨申请单归档成功数据-------	
	select @sqlBill += ' Delete '+BillDetail+' from '+BillDetail+'  a Inner Join  '+BillTable+' b on a.BillNo = b.BillNo where B.BillDate <= @endDate and b.BillNo not in (select distinct BillNo from '+ BillDetail +' where (ComQty < BSQty)) or b.StopTag = 1  
		 Delete '+BillTable+' Where BillDate <= @endDate and BillNo not in (select distinct BillNo from '+ BillDetail +' where (ComQty < BSQty)) or StopTag = 1 '
	from PD_BillType where BillTypeID in (100,200,308) and BillTypeID= @BillTypeID
	
-------删除采购、销售开票金额归档成功数据-------	
	if @BillTypeID = 10101
	begin
		select @sqlBill += ' Delete MF_PchInvoiceDetail from MF_PchInvoiceDetail a Inner join MF_PchInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0 '
		select @sqlBill += ' Delete MF_PchInvoiceContent from MF_PchInvoiceContent a Inner join MF_PchInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0 '
		select @sqlBill += ' Delete MF_PchInvoiceBill where BillDate <= @endDate And IsDraft = 0 '
	End
	if @BillTypeID = 20101
	begin
		select @sqlBill += ' Delete MF_SellInvoiceDetail from MF_SellInvoiceDetail a Inner join MF_SellInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0 '
		select @sqlBill += ' Delete MF_sellInvoiceContent from MF_sellInvoiceContent a Inner join MF_SellInvoiceBill b on a.BillNo = b.BillNo where a.BillDate <= @endDate and IsDraft = 0 '
		select @sqlBill += ' Delete MF_SellInvoiceBill where BillDate <= @endDate And IsDraft = 0 '
	End
	select @sqlBill += '
	End
	COMMIT Tran T
	
'
	--END TRY
	--BEGIN CATCH
	--	RAISERROR (''' + 'error'+ ''',16,1)
	--END CATCH
	--'
 	--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 --WHILE (@curPos < len(@sqlBill))  
	 --BEGIN  
		-- PRINT substring(@sqlBill, @curPos, @curPos + 3999)  
		-- SET @curPos += 3999 + 1  
		-- SET @count += 1  
	 --END  
EXEC sp_executesql @sqlBill,N'@startDate Date,@endDate Date',@startDate,@endDate
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*************************************************/
--功能说明：       数据整理，包括收缩事务日志，重建数据索引
--创建日期：       2014-08-20
--返回结果：       @strErrMsg返回出错原因
/*************************************************/

CREATE PROCEDURE [Up_OT_DataBaseClean]
(
	@ContrackDb		BIT = 0,                --收缩数据库
	@ReIndex		BIT = 0,				--重建索引
	@Update			BIT = 0,				--更新统计信息
	@strErrMsg      VARCHAR(255)='' OUT     --出错原因，默认为空
)

AS
DECLARE @strSQL VARCHAR(4000),
		@strDataBaseName VARCHAR(100)

SET @strDataBaseName = DB_NAME();

----设置单用户模式并回滚所有未完成的事务   
SET @strSQL = 'ALTER DATABASE [' + @strDataBaseName + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;';
EXEC(@strSQL);

/****************************************************************/
--1、收缩数据库
/****************************************************************/
IF @ContrackDb = 1
BEGIN
	--修改数据库日志模式为简单
	SET @strSQL = 'ALTER DATABASE [' + @strDataBaseName + '] set recovery simple with no_wait;';
	EXEC(@strSQL);

	SET @strSQL = 'ALTER DATABASE [' + @strDataBaseName + '] set recovery simple ;';
	EXEC(@strSQL);

	--收缩文件
	SELECT @strSQL='DBCC SHRINKDATABASE(N''' + @strDataBaseName + ''',  TRUNCATEONLY );'
	EXEC(@strSQL);

	--修改数据库日志模式为完整
	SET @strSQL = 'alter database [' + @strDataBaseName + '] set recovery full with no_wait;';
	EXEC(@strSQL);

	SET @strSQL = 'alter database [' + @strDataBaseName + '] set recovery full ;';
	EXEC(@strSQL);
END

/****************************************************************/
--2、重建索引
/****************************************************************/

IF @ReIndex = 1
BEGIN
	CREATE TABLE #TableName(name VARCHAR(200))

	INSERT INTO #TableName
		SELECT name 
			FROM SYS.OBJECTS 
				WHERE type = 'U';

	DECLARE @strTableName VARCHAR(200);
	DECLARE cursor_TableName cursor FOR SELECT name FROM #TableName;

	OPEN cursor_TableName
	WHILE @@FETCH_STATUS = 0
	BEGIN
		FETCH NEXT FROM cursor_TableName INTO @strTableName;
		SET @strSql = 'DBCC DBREINDEX(' + @strTableName + ','''',90) WITH NO_INFOMSGS';
		EXEC(@strSql);
	END
	CLOSE cursor_TableName
	DEALLOCATE cursor_TableName

	DROP TABLE #TableName
END

IF @Update = 1
BEGIN
	-----更新统计信息
	EXEC sp_updatestats
END

----还原多用户模式
SET @strSQL = 'ALTER DATABASE [' + @strDataBaseName + '] SET MULTI_USER;';
EXEC(@strSQL);


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-6-27
	描述：数据还原
-------------------------------------------*/
CREATE PROCEDURE [UP_OT_DataRestore]
(
	@startDate nvarchar(10),
	@endDate nvarchar(10),
	@BillTypeID Int
)

AS
SET NOCOUNT ON
SET XACT_ABORT ON
declare @sqlBill nvarchar(max)='
	BEGIN TRAN T1
	BEGIN '
-----还原其他库表数据ListTable数据-----
if(@BillTypeID = -1)
begin 	
	select @sqlBill += ' SET IDENTITY_INSERT PD_listTable ON 
			Insert into PD_listTable(LID,BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,JTotal,DTotal,IsReconciled,[Order],Red)
			select LID,BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,JTotal,DTotal,IsReconciled,[Order],Red From PD_listTable_His where BillDate between @startDate and @endDate
			SET IDENTITY_INSERT PD_listTable OFF  
			Delete PD_listTable_His where BillDate between @startDate and @endDate
			'
END
-----还原MF_PayRecList数据-----
if (@BillTypeID = 401 or @BillTypeID = 402)
Begin
	Select @sqlBill += ' SET IDENTITY_INSERT MF_PayRecList ON 
			Insert into MF_PayRecList('+dbo.UF_OT_GetColumns('MF_PayRecList','','')+')
			select '+ dbo.UF_OT_GetColumns('MF_PayRecList','a.','')+' from MF_PayRecList_His a Inner Join MF_PayRecBill_His b on a.PayRecBillNo = b.billno where b.BillDate between @startDate and @endDate
			SET IDENTITY_INSERT MF_PayRecList OFF 
			delete MF_PayRecList_His from MF_PayRecList_His a  Inner Join MF_PayRecBill_His b on a.PayRecBillNo = b.billno where b.BillDate between @startDate and @endDate ' 
End

-----还原单据数据-----		
select @sqlBill += ' 
	SET IDENTITY_INSERT '+ BillTable + ' ON
	insert into '+ BillTable + '(' + dbo.UF_OT_GetColumns(BillTable,'','')+') select ' + dbo.UF_OT_GetColumns(BillTable,'','')+' from '+BillTable+'_His where BillDate between @startDate and @endDate '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	+ ' SET IDENTITY_INSERT '+ BillTable + ' OFF
	'
from PD_BillType where BillTypeID in (100,101,102,200,201,202,301,302,303,304,305,306,308,309,310,401,402,403,404,405,406,501,502,503,504,600,602) And BillTypeID = @BillTypeID

-------还原序列号信息--------
	Select @sqlBill += ' 
		SET IDENTITY_INSERT '+ BillSerial + ' ON
		insert into '+BillSerial + '(' + dbo.UF_OT_GetColumns(BillSerial,'','')+') select ' + dbo.UF_OT_GetColumns(BillSerial,'a.','')+ ' from ' + BillSerial + '_His a inner join ' +BillDetail+ '_His b on a.BillDid = b.DID Inner Join ' + BillTable + '_His c on b.BillNo = c.BillNo '
		+ ' where C.BillDate between @startDate and @endDate'
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND C.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+' SET IDENTITY_INSERT '+ BillSerial + ' OFF 
		Delete ' +BillSerial+'_His from ' + BillSerial + '_His a inner join ' +BillDetail+ '_His b on a.BillDid = b.DID Inner Join ' + BillTable + '_His c on b.BillNo = c.BillNo '
		+ ' where C.BillDate between @startDate and @endDate'		
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND C.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	from PD_BillType where BillTypeID in (101,102,201,202,301, 302, 303, 304, 305, 306, 309,310,600) And BillTypeID = @BillTypeID
-----------------------	
select @sqlBill += ' 
	SET IDENTITY_INSERT '+ BillDetail + ' ON
	Insert into '+ BillDetail +'(' + dbo.UF_OT_GetColumns(BillDetail,'','')+') select ' + dbo.UF_OT_GetColumns(BillDetail,'a.','')+' from '+ BillDetail +'_His a Inner Join  '+BillTable+'_His b on a.BillNo = b.BillNo where b.BillDate between @startDate and @endDate '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND b.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	+' SET IDENTITY_INSERT '+ BillDetail + ' OFF
	Delete '+BillDetail+'_His from '+BillDetail+'_His a Inner Join  '+BillTable+'_His b on a.BillNo = b.BillNo where b.BillDate between @startDate and @endDate '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND B.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	+ 'Delete '+BillTable+'_His where BillDate between @startDate and @endDate'
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
from PD_BillType where BillTypeID in (100,101,102,200,201,202,301,302,303,304,305,306,308,309,310,401,402,403,404,405,406,501,502,503,504,600,602) And BillTypeID = @BillTypeID



-----还原采购、销售开票数据------
if @BillTypeID = 10101
begin
select @sqlBill += ' 
	SET IDENTITY_INSERT MF_PchInvoiceBill ON
	insert into MF_PchInvoiceBill(' + dbo.UF_OT_GetColumns('MF_PchInvoiceBill','','')+') select ' + dbo.UF_OT_GetColumns('MF_PchInvoiceBill','','')+' from MF_PchInvoiceBill_His where BillDate between @startDate and @endDate 	
	SET IDENTITY_INSERT MF_PchInvoiceBill OFF 
	SET IDENTITY_INSERT MF_PchInvoiceDetail ON
	insert into MF_PchInvoiceDetail(' + dbo.UF_OT_GetColumns('MF_PchInvoiceDetail','','')+') select ' + dbo.UF_OT_GetColumns('MF_PchInvoiceDetail','','')+' from MF_PchInvoiceDetail_His where BillDate between @startDate and @endDate	
	SET IDENTITY_INSERT MF_PchInvoiceDetail OFF 
	SET IDENTITY_INSERT MF_PchInvoiceContent ON
	insert into MF_PchInvoiceContent(' + dbo.UF_OT_GetColumns('MF_PchInvoiceContent','','')+') select ' + dbo.UF_OT_GetColumns('MF_PchInvoiceContent','','')+' from MF_PchInvoiceContent_His where BillDate between @startDate and @endDate 	
	SET IDENTITY_INSERT MF_PchInvoiceContent OFF '
	select @sqlBill += ' Delete MF_PchInvoiceBill_His where BillDate between @startDate and @endDate '
	select @sqlBill += ' Delete MF_PchInvoiceDetail_His where BillDate between @startDate and @endDate '
	select @sqlBill += ' Delete MF_PchInvoiceContent_His where BillDate between @startDate and @endDate '	
End
if @BillTypeID = 20101
begin
select @sqlBill += ' 
	SET IDENTITY_INSERT MF_SellInvoiceBill ON
	insert into MF_SellInvoiceBill(' + dbo.UF_OT_GetColumns('MF_SellInvoiceBill','','')+') select ' + dbo.UF_OT_GetColumns('MF_SellInvoiceBill','','')+' from MF_SellInvoiceBill_His where BillDate between @startDate and @endDate 	
	SET IDENTITY_INSERT MF_SellInvoiceBill OFF 
	SET IDENTITY_INSERT MF_SellInvoiceDetail ON
	insert into MF_SellInvoiceDetail(' + dbo.UF_OT_GetColumns('MF_SellInvoiceDetail','','')+') select ' + dbo.UF_OT_GetColumns('MF_SellInvoiceDetail','','')+' from MF_SellInvoiceDetail_His where BillDate between @startDate and @endDate	
	SET IDENTITY_INSERT MF_SellInvoiceDetail OFF 
	SET IDENTITY_INSERT MF_sellInvoiceContent ON
	insert into MF_sellInvoiceContent(' + dbo.UF_OT_GetColumns('MF_sellInvoiceContent','','')+') select ' + dbo.UF_OT_GetColumns('MF_sellInvoiceContent','','')+' from MF_sellInvoiceContent_His where BillDate between @startDate and @endDate 	
	SET IDENTITY_INSERT MF_sellInvoiceContent OFF '
	select @sqlBill += ' Delete MF_SellInvoiceBill_His where BillDate between @startDate and @endDate '
	select @sqlBill += ' Delete MF_SellInvoiceDetail_His where BillDate between @startDate and @endDate '
	select @sqlBill += ' Delete MF_sellInvoiceContent_His where BillDate between @startDate and @endDate '	
End


--if(@BillTypeID = -2)
--select @sqlBill+=' select 1/0 '

select @sqlBill += '
	END
	COMMIT Tran T1
	'
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
-- WHILE (@curPos < len(@sqlBill))  
-- BEGIN  
--	 PRINT substring(@sqlBill, @curPos, @curPos + 3999)  
--	 SET @curPos += 3999 + 1  
--	 SET @count += 1  
-- END  
EXEC sp_executesql @sqlBill,N'@startDate Date,@endDate Date',@startDate,@endDate
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-4-30
	描述：删除草稿单据
-------------------------------------------*/
CREATE PROCEDURE [UP_OT_DeleteDraftBill]
(
	@BillNo Int = 0,
	@BillTypeID Int = 0
)

AS
SET NOCOUNT ON
Declare @sql nvarchar(max)=''
IF(@BillTypeID IN (101,102,201,202,301,302,303,304,305,306,307,309,310)) -- 删除序列号信息
	SELECT @sql += ' Delete Serial FROM ' + BillSerial + ' Serial INNER JOIN ' + BillDetail + ' Detail ON Serial.BillDID = Detail.DID WHERE BillNo = @BillNo '
		FROM PD_BillType WHERE BillTypeID = @BillTypeID 
if(@BillTypeID in (201,202,305,404,405))
begin
	Select @sql +='	declare @IsOS int
			select @IsOS = IsOS from '+ BillTable +' where BillNo = @BillNo
			if(@IsOS = 1)
			Begin
				declare @OSBillNo varchar(50),@OSOrderType int
				select @OSOrderType = OSOrderType,@OSBillNo = OSBillNo from OS_BillRelation where BillNo = @BillNo and BillTypeID = @BillTypeID
				--select @OSBillNo = a.BillNo from OS_OrderBillAll A Inner Join OS_BillRelation B on a.BillNo = b.OSBillNo where b.BillNo = @BillNo and b.BillTypeID = @BillTypeID
				if(@OSOrderType = 0)
				begin
					update OS_OrderBillAll set IsCreate = 0 where BillNo = @OSBillNo
					if not exists(select 1 from OS_OrderBill where BillNo =  @OSBillNo)
					Begin
						insert into OS_OrderBill select * from OS_OrderBillAll where BillNo = @OSBillNo
						SET IDENTITY_INSERT OS_OrderDetail ON
						insert into OS_OrderDetail('+dbo.UF_OT_GetColumns('OS_OrderDetail','','')+') select '+ dbo.UF_OT_GetColumns('OS_OrderDetail','','')+' from OS_OrderDetailAll where BillNo = @OSBillNo
						SET IDENTITY_INSERT OS_OrderDetail OFF 
					End
				ENd 
				Else
				Begin
					update OS_FreightBillAll set IsCreate = 0 where BillNo = @OSBillNo
					if not exists(select 1 from OS_FreightBill where BillNo =  @OSBillNo)
					Begin
						insert into OS_FreightBill select * from OS_FreightBillAll where BillNo = @OSBillNo
					End
				End
				delete OS_BillRelation where BillNo = @BillNo and BillTypeID = @BillTypeID
			End '	
		from PD_BillType where BillTypeID = @BillTypeID 	
			
end
if(@BillTypeID in (101,102,201,202,403,404,405))
	Select @sql +=' Delete PD_MulAccounts where BillNo = @BillNo and BillTypeID = @BillTypeID '
Select @sql += ' Delete ' + BillTable + ' where BillNo = @BillNo  Delete ' + BillDetail + ' where BillNo = @BillNo'
		from PD_BillType where BillTypeID = @BillTypeID 
if(@BillTypeID = 401 or @BillTypeID= 402)
	Select @sql += ' Delete MF_PayRecList where PayRecBillNo = @BillNo'

exec sp_executesql @sql,N'@BillNo Int,@BillTypeID Int', @BillNo,@BillTypeID
GO



if exists (select * from sysobjects where id = object_id(N'[UP_OT_GetStartRight]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_OT_GetStartRight]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		wubin
-- Create date:  2014/9/25
-- Description:	 导航页菜单权限
-- =============================================
CREATE PROCEDURE [UP_OT_GetStartRight](
     @UserID int = 0
   ) 
AS
BEGIN
     DECLARE @Sql NVARCHAR(MAX), @JoinSql NVARCHAR(1000) = '',  @WhereSql NVARCHAR(2000) = '', @Opp NVARCHAR(20) = ' 1 ',
             @colSql NVARCHAR(100) = ''
     
     IF @UserID <> 1
        BEGIN
            IF EXISTS ( SELECT 1 FROM SS_Oper_Role WHERE OperID = @UserID )
                BEGIN
                    SET @JoinSql = ' LEFT JOIN SS_Role_Jur _jur ON _jur.JurID = jur.JurID
				                     LEFT JOIN SS_Oper_Role _role ON _role.RoleID = _jur.RoleID AND _role.OperID = @UserID AND _role.Stt = 1  '
                    SET @WhereSql = ' AND ((_role.RoleID IS NOT NULL AND _jur.RoleID IS NOT NULL) 
                                            OR (_role.RoleID IS NULL AND _jur.RoleID IS NULL)
                                            OR (_role.RoleID IS NULL AND _jur.RoleID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM                                                       SS_Role_Jur _J INNER JOIN SS_Oper_Role _R ON _J.RoleID = _R.RoleID 
                                                WHERE _R.OperID = @UserID AND _J.JurID = _jur.JurID)))
                                      GROUP BY menu.MenuID, menu.ParID, menu.Caption, jur.JurID, _role.RoleID, _jur.RoleID '
                    SET @Opp = ' MAX(_jur.opp) '
                    SET @colSql = ' WHEN _role.RoleID IS NULL AND _jur.RoleID IS NOT NULL THEN 0 '
                END
            ELSE
                SET @Opp = ' 0 '
        END
     
	 SET @Sql = N'DECLARE @IsHasProperty TINYINT = 0, @IsHasWhsPt TINYINT = 0, @AccountType TINYINT = 1, @AllotWithInspect TINYINT = 0, @SerialNoMgt TINYINT = 0
	             SELECT @IsHasProperty = CfgValue FROM SS_SysCfg WHERE CfgName=''PropertyM''
				 SELECT @IsHasWhsPt = CfgValue FROM SS_SysCfg WHERE CfgName=''HasWhsPt''
				 SELECT @AccountType = CfgValue FROM SS_SysCfg WHERE CfgName=''AccountType''
				 SELECT @AllotWithInspect = CfgValue FROM SS_SysCfg WHERE CfgName=''AllotWithInspect''
				 SELECT @SerialNoMgt = CfgValue FROM SS_SysCfg WHERE CfgName=''SerialNoMgt''
				 SELECT DISTINCT menu.MenuID, menu.ParID, jur.JurID,
				 (CASE WHEN @IsHasProperty = 0 AND menu.MenuID = 2008 THEN ''货位库存调整'' 
					  WHEN @IsHasWhsPt = 0 AND menu.MenuID = 2008 THEN ''属性库存调整''
					  ELSE menu.Caption END) AS Caption, 
				 (CASE WHEN @IsHasProperty = 0 AND (menu.MenuID = 2508 OR menu.MenuID = 2509) THEN 0 
					  WHEN @IsHasWhsPt = 0 AND menu.MenuID = 2516 THEN 0 
					  WHEN @IsHasWhsPt = 0 AND @IsHasProperty = 0 AND menu.MenuID = 2008  THEN 0 
					  WHEN @AccountType = 2 AND menu.MenuID = 3518 THEN 0 
					  WHEN @AllotWithInspect = 0 AND menu.MenuID = 2024 THEN 0 ' + @colSql + '
					  WHEN @SerialNoMgt = 0 AND (menu.MenuID = 2025 OR menu.MenuID = 2026) THEN 0 
					  WHEN '+@Opp+' IS NULL THEN 0
					  ELSE '+@Opp+' END) AS opp
				 FROM SS_WebMenu menu
				  INNER JOIN SS_Jurisdiction jur ON jur.MenuID = menu.MenuID '
				  + @JoinSql +
				  ' WHERE (menu.MenuID LIKE ''10%'' OR  menu.MenuID LIKE ''15%'' OR  menu.MenuID LIKE ''20%'' OR  menu.MenuID LIKE ''35%'' OR  menu.MenuID LIKE ''50%'')
					AND menu.ParID <> 0 AND menu.ParID <> 2530
					AND menu.IsRoot = 0
					AND menu.Stt = 1
					AND jur.JurID LIKE ''%10''
					AND jur.JurID NOT IN (1230010,1230110,1330010,1330110,1430410,1431110,1630110,1630210,1630310,1630410)
					AND (JurTypeID = 1 
					OR (JurTypeID = 2 AND menu.MenuID <> 5002 AND menu.MenuID <> 5003)
					OR (JurTypeID = 13 AND menu.MenuID <> 5003)
					OR (menu.MenuID = 2007 AND (JurTypeID = 3 OR JurTypeID = 4))) ' + @WhereSql +
				  ' ORDER BY menu.MenuID '
					--print @sql
	 EXEC sp_executesql @Sql,N'@UserID INT',@UserID	  
End             
GO




if exists (select * from sysobjects where id = object_id(N'[UP_OT_GetWebMenu]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_OT_GetWebMenu]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		雷洋
-- Create date:  2014/7/10
-- Description:	 获取菜单
-- =============================================
CREATE PROCEDURE [UP_OT_GetWebMenu](
     @UserID int = 0
   ) 
AS
BEGIN

	 declare @MaxLvl int 
	 if object_id('tempdb..#RootMenu','U') is not null drop table #RootMenu
	 CREATE TABLE #RootMenu(MenuID int,MenuName varchar(30),Caption varchar(30),parid int,Lvl int,IsRoot int,OrderID int,HotKey varchar(50),WebURL varchar(100),Stt bit,IsGroup bit)
	 if(@UserID = 1)
	 Begin
		Insert Into #RootMenu Select MenuID,MenuName,Caption,ParID,Lvl,IsRoot,OrderID,HotKey,WebURL,Stt,IsGroup from SS_WebMenu
	 End
	 Else
	 Begin
		 ;WITH data as (
			 SELECT sj.jurID,max(sj.opp) as  opp
			 FROM SS_Role_Jur  sj
				  INNER JOIN  SS_Oper_Role so ON sj.RoleID=so.RoleID
			 WHERE so.OperID=@UserID AND so.Stt=1 AND sj.opp=1
			  GROUP by sj.JurID
		), MenuLimits as
		(
			SELECT d.*, sjur.JurName,sjur.MenuID,sjt.JurTypeID,sjt.TypeName,sjt.TypeCode FROM data d 
			INNER JOIN SS_Jurisdiction sjur ON d.JurID=sjur.JurID
			 INNER JOIN SS_Jur_Type sjt  ON sjur.JurTypeID=sjt.JurTypeID where d.JurID like '%10' 
			 AND d.JurID not in (1120010,1120110,1120210,1230010,1230110,1330010,1330110,1430410,1430610,1430510,1431110,1630110,1630210,1630310,1630410,2030010,2030110,2030210,2030410,2030510,2030610,2030710,2030810)--排除其他权限影响菜单显示
		),Menu as
		(
			SELECT DisTinct M.* FROM SS_WebMenu M Inner join MenuLimits ML on M.MenuID = ML.MenuID WHERE Stt=1 And IsRoot = 0
		),RootMenu as
		(
			Select * from SS_WebMenu where IsRoot = 1
		),AllMenu as
		(
			Select MenuID,MenuName,Caption,ParID,Lvl,OrderID,IsRoot,HotKey,Stt,WebURL,IsGroup from RootMenu 
			Union All 
			Select MenuID,MenuName,Caption,ParID,Lvl,OrderID,IsRoot,HotKey,Stt,WebURL,IsGroup from Menu
		)
		Insert Into #RootMenu Select MenuID,MenuName,Caption,ParID,Lvl,IsRoot,OrderID,HotKey,WebURL,Stt,IsGroup from AllMenu
		Select @MaxLvl = MAX(Lvl) from SS_WebMenu
		while (@MaxLvl <> 1)
		Begin
			 Delete #RootMenu where MenuID not in (select distinct parid from #RootMenu where Lvl = @MaxLvl) and Lvl = (@MaxLvl-1) and IsRoot = 1 and MenuID <> 4000
			 Set @MaxLvl -= 1
		End
		Insert Into #RootMenu Select MenuID,MenuName,Caption,ParID,Lvl,IsRoot,OrderID,HotKey,WebURL,Stt,IsGroup from SS_WebMenu where MenuID = 4003
	End
	if(Exists(select 1 from SS_SysCfg where CfgName='PropertyM' and CfgValue = 0)) --判断是否启用属性值设置
	Begin
		Delete #RootMenu where MenuID in (2508,2509) 
		UpDate #RootMenu Set Caption = '货位库存调整' where MenuID=2008
	End
	if(Exists(select 1 from SS_SysCfg where CfgName ='HasWhsPt' And CfgValue = 0 ))
	Begin
		Delete #RootMenu where MenuID in (2516) 
		UpDate #RootMenu Set Caption = '属性库存调整' where MenuID=2008
	End
	if(Exists (select 1 from SS_SysCfg where CfgName ='SerialNoMgt' and CfgValue = 0))
	begin
		Delete #RootMenu where MenuID in (2025,2026) 
	End
	if(Exists(select 1 from SS_SysCfg where CfgName ='HasWhsPt' And CfgValue = 0 ) and Exists(select 1 from SS_SysCfg where CfgName ='PropertyM' And CfgValue = 0 ))
	Begin
		Delete #RootMenu where MenuID in (2008) 
	END
	if(Exists(select 1 from SS_SysCfg where CfgName ='AccountType' And CfgValue = 2 ))
	Begin
		Delete #RootMenu where MenuID in (3518,3549) 
	End
	if(Exists(select 1 from SS_SysCfg where CfgName ='AllotWithInspect' And CfgValue = 0 ))
	BEGIN
		Delete #RootMenu where MenuID in (2024) 
	END
	
    Select MenuID,MenuName,Caption,ParID,Lvl,OrderID,IsRoot,HotKey,Stt,WebURL,IsGroup from #RootMenu 
    drop table  #RootMenu   
End             
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2014-6-18
	描述：业务草稿
-------------------------------------------*/
CREATE PROCEDURE [UP_OT_QueryDraftBill]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(max)='',
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@InWhsID VARCHAR(max)='',
	@OutWhsID VARCHAR(max)='',
	@FinanceID VARCHAR(max)='',
	@BillCode VARCHAR(50)='',
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100)='',
	@FullNameMatch INT=0,
	@UserCode VARCHAR(100)='',
	@UserCodeMatch INT=0,
	@LogistBillNo VARCHAR(50) = '',
	@LogistBillNoMatch INT=0,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=0,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=0,
	@AuditStatus VARCHAR(100)='',
	@OrderType1 INT=0,
	@OrderSeq1 INT=0,
	@UserID int = 0
)

AS
SET NOCOUNT ON

DECLARE @sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlWhs nvarchar(max),@SqlWhs1 nvarchar(max),
		@SqlWhs2 nvarchar(max),@SqlDept nvarchar(max),@SqlEly nvarchar(max),@SqlBtype nvarchar(max),@SqlCreator nvarchar(max)='',
		@BillCodeStr VARCHAR(max)='',@UserCodeStr VARCHAR(max)='',@FullNameStr VARCHAR(max)='',@LogistBillNoStr VARCHAR(max)='',@AuditStr varchar(max)='',
		@SummaryStr VARCHAR(max)='',@DescriptionStr VARCHAR(max)='',@sqlLimit varchar(100)='',@LimitSql varchar(500)='',@LimitBtypeSql varchar(500)='',
		@LimitSqlInOut varchar(500)='',@SqlFreight varchar(500)='',@OrderStr varchar(50)='',@SqlAtype varchar(500)='',@BTypeStr varchar(200)=''
		,@LogistBtypeStr varchar(200)='',@BtypeLimit INT=0,@KtypeLimit INT=0,@IsInAndOut Int = 0
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@UserID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@UserID) 
--SELECT @AtypeLimit = dbo.UF_BD_IsAllAtypeLimit(@UserID)
IF @BillTypeID<>'' AND NOT EXISTS(SELECT 1 FROM dbo.UF_OT_Split_Int(@BillTypeID,',') A WHERE a.typeid NOT IN(301,309,310))
	SET @IsInAndOut=1
if object_id('tempdb..#BillType','U') is not null drop table #BillType
CREATE TABLE #BillType(billtype int)
IF @BillTypeID<>''		
	INSERT INTO #BillType SELECT A.typeid FROM  dbo.UF_OT_Split_Int(@BillTypeID,',') A Inner Join dbo.UF_OT_BillTypeLimit(@UserID) B on A.typeid = B.Typeid
ELSE
	INSERT INTO #BillType SELECT A.BillTypeID  FROM PD_BillType A Inner Join dbo.UF_OT_BillTypeLimit(@UserID) B on A.BillTypeID = B.Typeid  WHERE CanPost=1 
--------------------根据条件筛选单据类型---------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM #BillType WHERE billtype=0)
BEGIN
	IF @BTypeID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504)
	IF @FinanceID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,201,102,202,403,404,405,406,602)   
	IF @UserCode<>'' OR @FullName<>'' OR @WhsID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,301,302,303,304,305,306,309,301)   
	IF @LogistBillNo<>''
		DELETE FROM #BillType WHERE billtype<>201
	--IF @AuditStatus <> '' and not exists ( select 1 from dbo.UF_OT_Split_Int(@AuditStatus,',') where typeid = 0)
	--	DELETE FROM #BillType WHERE billtype<>101
END  
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@UserID) '
	SET @LimitSql += ' INNER JOIN @LimitKType kl ON kl.TypeID =I.WhsID '
	Set @LimitSqlInOut +=' INNER JOIN @LimitKType kl ON kl.TypeID =i.OutWhsID or kl.TypeID =i.InWhsID' 
END
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@UserID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =I.BtypeID '
End
if(@UserID <> 1 And not exists(select 1 from SS_Role_Jur a left join SS_Oper_Role b on a.RoleID = b.RoleID where b.OperID = @UserID and JurID=1710710 and opp = 1))
	Select @sqlLimit = ' AND I.Creator = @UserID '
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @BTypeStr+=' And Exists( select 1 from  @BType B where  i.BTypeID=B.TypeID ) '
	SET @LogistBtypeStr+=' And Exists( select 1 from  @BType B where  i.BTypeID=B.TypeID OR I.LogistBTypeID=B.TypeID)'	
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON I.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON I.ElyID=E.TypeID ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' INNER JOIN @CreateEType CE ON I.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
END	
IF @InWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @InKType As Table(TypeID INT) insert into @InKType Select typeid from dbo.UF_OT_Split_Int(@InWhsID,'','') '
	SET @SqlTable+=' INNER JOIN @InKType Wi ON I.InWhsID=Wi.TypeID ' 
END	
IF @OutWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @OutKType As Table(TypeID INT) insert into @OutKType Select typeid from dbo.UF_OT_Split_Int(@OutWhsID,'','') '
	SET @SqlTable+=' INNER JOIN @OutKType Wo ON I.OutWhsID=Wo.TypeID ' 
END	
IF @FinanceID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @AType Table(TypeID INT) insert into @AType Select f2.FinanceID from BD_Finance f INNER JOIN dbo.UF_OT_Split_Int(@FinanceID,'','')f1 ON f1.TypeID=f.FinanceID INNER JOIN BD_Finance f2 On f2.path Like f.Path+''%'''
	--if @AtypeLimit =1
	--	SET @SqlCreateTable+= ' INNER JOIN  dbo.UF_BD_AtypeLimit(@UserID) f3 ON f3.FinanceID=f2.financeID '
	SET @SqlAtype+=' And Exists( select 1 from  @AType A where  i.FinanceID=A.TypeID EXISTS(SELECT 1 FROM PD_MulAccounts M WHERE M.BillTypeID= AND M.BillNo=I.BillNo)) ' 
	SET @SqlFreight+=' And Exists( select 1 from  @AType A where  i.FinanceID=A.TypeID or i.FreightFinanceID = a.TypeID ) ' 
END	
IF @AuditStatus <> ''
Begin
	Select @AuditStr += ' And I.AuditStatus in ('+@AuditStatus+') '
END
Select @OrderStr = Case @OrderType1 when 0 then ' BillDate '
									When 1 then ' BillTypeID '
									When 2 then ' BillCode '
									When 3 then ' CreateTime '
									When 4 then ' PosTime '
									else ' BillDate ' end
Select @OrderStr += case @OrderSeq1 when 2 then ' DESC ' else '' End
SELECT @OrderStr += Case @OrderType1 when 0 then ',BillNo Desc ' else '' end
IF @billcode <>'' 
	SET @BillCodeStr = ' AND BillCode'+CASE @BillCodeMatch WHEN 0 THEN ' Like''%''+@BillCode+''%''' ELSE ' =@BillCode' END
IF @LogistBillNo <>'' 
	SET @LogistBillNoStr = ' AND LogistBillNo'+CASE @LogistBillNoMatch WHEN 0 THEN ' Like''%''+@LogistBillNo+''%''' ELSE ' =@LogistBillNo' END
IF @Summary <>'' 
	SET @SummaryStr = ' AND Summary'+CASE @SummaryMatch WHEN 0 THEN ' Like''%''+@Summary+''%''' ELSE ' =@Summary' END
IF @Description <>'' 
	SET @DescriptionStr = ' AND Description'+CASE @DescriptionMatch WHEN 0 THEN ' Like''%''+@Description+''%''' ELSE ' =@Description' END
IF @FullName <>'' 
	SET @FullNameStr = ' AND GoodsName'+CASE @FullNameMatch WHEN 0 THEN ' Like''%''+@FullName+''%''' ELSE ' =@FullName' END
IF @UserCode <>'' 
	SET @UserCodeStr = ' AND g.GoodsNo'+CASE @UserCodeMatch WHEN 0 THEN ' Like''%''+@UserCode+''%''' ELSE ' =@UserCode' END
   	
SELECT @sql+='
UNION ALL 
SELECT  ' + case when billtypeid in (301,309,310) then 'distinct' else '' end +' BillNo,
		BillDate,
		BillCode,
		'+Cast(BillTypeID AS varchar)+' AS BillTypeID,
		'''+billname+''' AS BillName,
		DeptID,
		ElyID,'
		+CASE WHEN billtypeid IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504,600) THEN 'BtypeID' ELSE '0' END+' as BtypeID,'
		+CASE WHEN billtypeid IN(101,102,201,202,302,303,304,305,306,600) THEN 'I.WhsID' WHEN billtypeid in (301,309,310) THEN 'OutWhsID'  ELSE '0' END+' as WhsID,'
		+CASE WHEN @IsInAndOut=1 THEN 'OutWhsID,' ELSE '' END				--单独选择调拨单的时候需要显示出入库两个仓库
		+CASE WHEN @IsInAndOut=1 THEN 'InWhsID,' ELSE '' END
		+CASE WHEN billtypeid=310 THEN ' InToTal As Total,' ELSE ' Total,' END
		+CASE WHEN billtypeid IN(101,102,201,202,401,402,602) THEN 'Privilege' ELSE '0' END+' as Privilege,'	--优惠券金额
		+CASE WHEN billtypeid IN(101,201,102,202,403,404,405,406) THEN 'PayRecTotal' ELSE '0' END+' as PayRecTotal,'
		+CASE WHEN billtypeid IN(101,201,102,202,403,404,405) THEN 'PaidTotal' ELSE '0' END+' as PaidTotal,'
		+CASE WHEN billtypeid =201 THEN 'LogistBillNo' ELSE '''''' END+' as LogistBillNo,
		Creator As CreatorID,
		CONVERT(varchar(100), CreateTime, 120) AS CreateTime,
		PosElyID,
		CONVERT(varchar(100), PosTime, 120) AS PosTime,0 as multi
		,I.AuditStatus as AuditStatus,
		I.Description,
		I.Summary		
FROM '+BillTable+' I ' 
+ CASE WHEN billtypeid IN(101,102,201,202,302,303,304,305,306) THEN @LimitSql When billtypeid in (301,309,310) then @LimitSqlInOut Else '' end 
+ CASE WHEN BillTypeID IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504) THEN @LimitBtypeSql ELSE '' END
+CASE WHEN @WhsID='' THEN '' ELSE ' INNER JOIN @KType W ON I.'+ case WHEN billtypeid in (301,309,310) THEN 'OutWhsID' else 'WhsID' END +'=W.TypeID ' END
+ @SqlTable 
+' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=1 '
		--+ Case when BillTypeID in (101,201) then @SqlFreight else case when @FinanceID<> '' then 'And Exists( select 1 from  @AType A where  i.FinanceID=A.TypeID or EXISTS(SELECT 1 FROM PD_MulAccounts M WHERE M.BillTypeID= '+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo))' else '' end end
		+CASE WHEN @FinanceID='' OR billtypeid NOT IN(101,201,102,202,403,404,405,406,602) THEN '' ELSE ' AND EXISTS(SELECT 1 FROM @AType A WHERE I.FinanceID=A.TypeID '+case when billtypeid in (101,201) THEN 'OR I.FreightFinanceID=A.TypeID ' ELSE '' END+'
			OR EXISTS(SELECT 1 FROM PD_MulAccounts M WHERE M.BillTypeID='+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo and M.FinanceID= a.TypeID))' END
		+ Case When billtypeid = 201 then @LogistBtypeStr Else @BTypeStr End
		--+' AND '+CASE @DateType WHEN 0 THEN 'BillDate' WHEN 1 THEN 'CreateTime' ELSE 'PosTime' END +' BETWEEN @BeginDate AND @EndDate' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+ @AuditStr 
		+@BillCodeStr 
		+@LogistBillNoStr
		+@SummaryStr
		+@DescriptionStr
		+@sqlLimit
		+CASE WHEN @FullName='' AND @UserCode=''THEN '' ELSE ' AND EXISTS(SELECT 1 FROM '+BillDetail+' d INNER JOIN BD_Goods g ON d.GoodsID=g.GoodsID WHERE I.BillNo=D.BillNo '+@FullNameStr+@UserCodeStr+')' END 
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0
WHERE CanPost=1 

drop table #BillType

SELECT @sql=@SqlCreateTable+'
;WITH PagingData AS 
('	+STUFF(@sql,1,12,'')+'
)'

PRINT(@sql)

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

SET @sql+='	
	 ,DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderStr+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	) 
	SELECT * INTO #PostBillData FROM DATA
	SELECT Data.*, '
if @IsInAndOut=1
	SET @sql+='wi.WhsName AS InWhsName,wi.WhsNO as InWhsNO,wo.WhsName AS OutWhsName,wo.WhsNO as OutWhsNO,d.DeptName,D.DeptCode,e.ElyName,e.ElyCode,e1.ElyName as CreatorName,e1.ElyCode as CreatorCode,b.BTypeName,b.BTypeCode
	,case AuditStatus when 0 then '''+'无审核流程'+'''
					  when 1 then '''+'未达审核条件'+'''
					  when 2 then '''+'原始单据'+'''
					  when 3 then '''+'审核中'+'''
					  when 4 then '''+'审核通过'+'''
					  when 5 then '''+'审核不通过'+'''
					  else '''+'无审核流程'+''' end as AuditType
	FROM #PostBillData Data
	LEFT JOIN BD_Whs wi ON Data.InWhsID = wi.WhsID
	LEFT JOIN BD_Whs wo ON Data.OutWhsID = wo.WhsID'	
ELSE
	set @sql+= 'w.WhsName,w.WhsNO,d.DeptName,D.DeptCode,e.ElyName,e.ElyCode,e1.ElyName as CreatorName,e1.ElyCode as CreatorCode,b.BTypeName,b.BTypeCode
	,case AuditStatus when 0 then '''+'无审核流程'+'''
					  when 1 then '''+'未达审核条件'+'''
					  when 2 then '''+'原始单据'+'''
					  when 3 then '''+'审核中'+'''
					  when 4 then '''+'审核通过'+'''
					  when 5 then '''+'审核不通过'+'''
					  else '''+'无审核流程'+''' end as AuditType
	FROM #PostBillData Data
	LEFT JOIN BD_Whs w ON Data.WhsID = w.WhsID '
SET @sql+='
	LEFT JOIN BD_Dept d ON Data.DeptID = d.DeptID 
	LEFT JOIN BD_Employee e ON Data.ElyID = e.ElyID 
	LEFT JOIN BD_Employee e1 ON Data.CreatorID = e1.ElyID 
	LEFT JOIN BD_Btype b ON Data.BtypeID = b.BtypeID 
	ORDER BY '+@OrderStr+'
	DROP Table #PostBillData
	'
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  

--PRINT(@sql)	
EXEC sp_executesql @sql,N'@BeginDate Date,@EndDate Date,@BTypeID VarChar(MAX),@DeptID VarChar(MAX),@ElyID VarChar(MAX),@CreatorID VarChar(MAX),@WhsID VarChar(MAX),@inWhsID VarChar(MAX),@OutWhsID VarChar(MAX),@FinanceID VarChar(MAX),@BillCode VarChar(50),
						@FullName VarChar(100),@UserCode VarChar(50),@LogistBillNo VarChar(20),@Summary VarChar(256),@Description VarChar(100),@UserID INT,@PageNo int,@PageSize INT',
						@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@inWhsID,@OutWhsID,@FinanceID,@BillCode,
						@FullName,@UserCode,@LogistBillNo,@Summary,@Description,@UserID,@PageNo,@PageSize

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：hanlin
	日期：2014-6-15
	描述：查询已过账单据（经营历程）
-------------------------------------------*/
CREATE PROCEDURE [UP_OT_QueryPostBill]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(max)='',
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@OperatorID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@InWhsID VARCHAR(max)='',
	@OutWhsID VARCHAR(max)='',
	@FinanceID VARCHAR(max)='',
	@BillCode VARCHAR(50)='',
	@BillCodeMatch INT=1,
	@FullName VARCHAR(100)='',
	@FullNameMatch INT=1,
	@UserCode VARCHAR(100)='',
	@UserCodeMatch INT=1,
	@LogistBillNo VARCHAR(20)='',
	@LogistBillNoMatch INT=1,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=1,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=1,
	@ShowRed INT=2,
	@WeiXin INT=0,
	@UserID INT=0,
	@IsHistory INT=0,
	@OrderField VARCHAR(50)=''
)

AS
SET NOCOUNT ON

DECLARE @sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlWhs nvarchar(max),@SqlWhs1 nvarchar(max),
		@SqlWhs2 nvarchar(max),@SqlDept nvarchar(max),@SqlEly nvarchar(max),@SqlBtype nvarchar(max),@SqlCreator nvarchar(max),@SqlPostor nvarchar(max),
		@BillCodeStr VARCHAR(max)='',@UserCodeStr VARCHAR(max)='',@FullNameStr VARCHAR(max)='',@LogistBillNoStr VARCHAR(max)='',@WhsStr VARCHAR(max)='',
		@SummaryStr VARCHAR(max)='',@DescriptionStr VARCHAR(max)='',@Ret INT=0,@IsInAndOut INT=0

EXEC @ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN
	
IF @DateType<>0 --过账和录单有时间，所以结束天数加1
	SET @EndDate = DATEADD(day,1,@EndDate) 

IF @BillTypeID<>'' AND NOT EXISTS(SELECT 1 FROM dbo.UF_OT_Split_Int(@BillTypeID,',') A WHERE a.typeid NOT IN(301,309,310))
	SET @IsInAndOut=1
		
if object_id('tempdb..#BillType','U') is not null drop table #BillType
CREATE TABLE #BillType(billtype int)
IF @BillTypeID<>''		
	INSERT INTO #BillType SELECT A.typeid FROM  dbo.UF_OT_Split_Int(@BillTypeID,',') A Inner Join dbo.UF_OT_BillTypeLimit(@UserID) B on A.typeid = B.Typeid
ELSE
	INSERT INTO #BillType SELECT A.BillTypeID  FROM PD_BillType A Inner Join dbo.UF_OT_BillTypeLimit(@UserID) B on A.BillTypeID = B.Typeid  WHERE CanPost=1 
--------------------根据条件筛选单据类型---------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM #BillType WHERE billtype=0)
BEGIN
	IF @BTypeID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504,600)
	IF dbo.UF_BD_IsAllBtypeLimit(@UserID)=0
		DELETE FROM #BillType WHERE billtype IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504,600)
		
	IF @FinanceID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,201,102,202,401,402,403,404,405,406,602)   
	IF @UserCode<>'' OR @FullName<>'' OR @WhsID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,301,302,303,304,305,306,309,310,600)   
	IF @LogistBillNo<>''
		DELETE FROM #BillType WHERE billtype<>201
END  

IF @BTypeID<>'' OR dbo.UF_BD_IsAllBtypeLimit(@UserID)=1
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType Table(TypeID INT) insert into @BType '
	IF @BTypeID<>'' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)=2
		SET @SqlCreateTable+='	Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	ELSE IF @BTypeID='' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)=1
		SET @SqlCreateTable+='	Select Btypeid from dbo.UF_BD_BtypeLimit(@UserID) '
	ELSE
		SET @SqlCreateTable+='	Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') a inner join dbo.UF_BD_BtypeLimit(@UserID) b ON b.BtypeID =a.typeid '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON I.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON I.ElyID=E.TypeID ' 
END	
IF @OperatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @Operator Table(TypeID INT) insert into @Operator Select typeid from dbo.UF_OT_Split_Int(@OperatorID,'','') '
	SET @SqlTable+=' INNER JOIN @Operator O ON I.Creator=O.TypeID ' 
END	

IF dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2
	SET @WhsStr=' AND (EXISTS(Select 1 FROM UF_BD_KtypeLimit(@UserID) where WhsID=I.OutWhsID) OR Exists(Select 1 FROM UF_BD_KtypeLimit(@UserID) where WhsID=I.InWhsID)) '	

IF @IsInAndOut=0 AND (@WhsID<>'' OR dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2)
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType Table(TypeID INT) insert into @KType '
	IF @WhsID<>'' AND dbo.UF_BD_IsAllKtypeLimit(@UserID)=2
		SET @SqlCreateTable+=' Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	ELSE IF @WhsID='' AND dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2
		SET @SqlCreateTable+=' Select WhsID from UF_BD_KtypeLimit(@UserID) '
	ELSE
		SET @SqlCreateTable+=' Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') a inner join UF_BD_KtypeLimit(@UserID) kl ON kl.WhsID =a.typeid '
END


IF @IsInAndOut=1
BEGIN
	IF @InWhsID<>''
		SET @SqlTable+=' INNER JOIN dbo.UF_OT_Split_Int(@InWhsID,'','') Wi ON I.InWhsID=Wi.TypeID ' 
	IF @OutWhsID<>''
		SET @SqlTable+=' INNER JOIN dbo.UF_OT_Split_Int(@OutWhsID,'','') Wo ON I.OutWhsID=Wo.TypeID ' 
END

IF @FinanceID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @AType Table(TypeID INT) insert into @AType '	
	SET @SqlCreateTable+='Select f2.FinanceID from BD_Finance f INNER JOIN BD_Finance f2 On f2.path Like f.Path+''%'' INNER JOIN dbo.UF_OT_Split_Int(@FinanceID,'','')f1 ON f1.TypeID=f.FinanceID  '
END	



IF @billcode <>'' 
	SET @BillCodeStr = ' AND BillCode'+CASE @BillCodeMatch WHEN 0 THEN ' Like''%''+@BillCode+''%''' ELSE ' =@BillCode' END
IF @LogistBillNo <>'' 
	SET @LogistBillNoStr = ' AND LogistBillNo'+CASE @LogistBillNoMatch WHEN 0 THEN ' Like''%''+@LogistBillNo+''%''' ELSE ' =@LogistBillNo' END
IF @Summary <>'' 
	SET @SummaryStr = ' AND Summary'+CASE @SummaryMatch WHEN 0 THEN ' Like''%''+@Summary+''%''' ELSE ' =@Summary' END
IF @Description <>'' 
	SET @DescriptionStr = ' AND Description'+CASE @DescriptionMatch WHEN 0 THEN ' Like''%''+@Description+''%''' ELSE ' =@Description' END
IF @FullName <>'' 
	SET @FullNameStr = ' AND GoodsName'+CASE @FullNameMatch WHEN 0 THEN ' Like''%''+@FullName+''%''' ELSE ' =@FullName' END
IF @UserCode <>'' 
	SET @UserCodeStr = ' AND g.GoodsNo'+CASE @UserCodeMatch WHEN 0THEN ' Like''%''+@UserCode+''%''' ELSE ' =@UserCode' END

SELECT @sql+='
UNION ALL 
SELECT  BillNo,
		BillDate,
		BillCode,
		'+Cast(BillTypeID AS varchar)+' AS BillTypeID,
		'''+billname+''' AS BillName,
		DeptID,
		ElyID,'
		+CASE WHEN billtypeid IN(201,202,305,404,405) THEN 'IsOS' ELSE '0' END+' as IsOS,'
		+CASE WHEN billtypeid IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504,600) THEN 'BtypeID' ELSE '0' END+' as BtypeID,'
		+CASE WHEN billtypeid IN(101,102,201,202,302,303,304,305,306,600) THEN 'WhsID' WHEN billtypeid IN(301,309,310) THEN 'OutWhsID'  ELSE '0' END+' as WhsID,'
		+CASE WHEN @IsInAndOut=1 THEN 'OutWhsID,' ELSE '' END				--单独选择调拨单的时候需要显示出入库两个仓库
		+CASE WHEN @IsInAndOut=1 THEN 'InWhsID,' ELSE '' END
		+CASE WHEN billtypeid=310 THEN 'InTotal As Total,' ELSE 'Total,' END
		+CASE WHEN billtypeid IN(101,102,201,202,401,402,602) THEN 'Privilege' ELSE '0' END+' as Privilege,'	--优惠金额
		+CASE WHEN billtypeid IN(101,201,102,202,403,404,405,406,602) THEN 'PayRecTotal' ELSE '0' END+' as PayRecTotal,'
		+CASE WHEN billtypeid IN(101,201,102,202,403,404,405,501,502,503,504,602) THEN 'PaidTotal' ELSE '0' END+' as PaidTotal,'
		+CASE WHEN billtypeid =201 THEN 'LogistBillNo' ELSE '''''' END+' as LogistBillNo,
		Creator As CreatorID,
		CreateTime,
		PosElyID,
		Red,
		Summary,
		Description,
		PosTime
FROM '+BillTable+' I '
+CASE WHEN @IsInAndOut=0 AND(dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2 OR @WhsID<>'') AND billtypeid IN(101,102,201,202,302,303,304,305,306,600) THEN ' INNER JOIN @KType W ON I.WhsID=W.TypeID ' ELSE '' END
+CASE WHEN @IsInAndOut=0 AND (dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2 OR @WhsID<>'') AND billtypeid IN(301,309,310) THEN ' INNER JOIN @KType W ON I.OutWhsID=W.TypeID ' ELSE '' END
+CASE WHEN @BTypeID='' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)=2 OR billtypeid NOT IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504,600) THEN '' ELSE ' INNER JOIN @BType B ON I.BTypeID=B.TypeID '  END
+@SqlTable
+'WHERE	'+CASE @DateType WHEN 0 THEN ' BillDate' WHEN 1 THEN 'CreateTime' ELSE 'PosTime' END +' BETWEEN @BeginDate AND @EndDate' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+ case when billtypeid in (301,309,310) then @WhsStr ELSE '' end
		+@BillCodeStr 
		+@LogistBillNoStr
		+@SummaryStr
		+@DescriptionStr
		+CASE WHEN @FullName='' AND @UserCode=''THEN '' ELSE ' AND EXISTS(SELECT 1 FROM '+BillDetail+' d INNER JOIN BD_Goods g ON d.GoodsID=g.GoodsID WHERE I.BillNo=D.BillNo '+@FullNameStr+@UserCodeStr+')' END 
		+' AND IsDraft=0 '
		+CASE WHEN @FinanceID='' OR billtypeid NOT IN(101,201,102,202,403,404,405,406,602) THEN '' ELSE ' AND EXISTS(SELECT 1 FROM @AType A WHERE I.FinanceID=A.TypeID '+case when billtypeid in (101,201) THEN 'OR I.FreightFinanceID=A.TypeID ' ELSE '' END+'
			OR EXISTS(SELECT 1 FROM PD_MulAccounts M INNER JOIN @AType A ON M.FinanceID=A.TypeID WHERE M.BillTypeID='+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo))' END
		+CASE WHEN @FinanceID<>'' AND BillTypeID IN(401,402) THEN ' AND EXISTS(SELECT 1 FROM MF_PayRecDetail M INNER JOIN @AType A ON M.FinanceID=A.TypeID AND M.BillNo=I.BillNo) ' ELSE '' END	
		+CASE WHEN @ShowRed=0 THEN '' WHEN @ShowRed=1 THEN ' AND Red<>0 ' ELSE ' And Red=0' END 
		+CASE WHEN @Weixin=0 THEN '' ELSE ' AND '+ CASE @Weixin WHEN 1 THEN 'NOT' ELSE '' END +' EXISTS(SELECT 1 FROM PD_WeiXinAccounts WHERE BillTypeID='+Cast(BillTypeID AS varchar)+' AND BillNo=I.BillNo '+CASE @Weixin WHEN 3 THEN 'AND PayStatus=1' WHEN 4 THEN 'AND PayStatus=0' ELSE '' END+')' END
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0
WHERE CanPost=1 

IF @IsHistory=1
	SELECT @sql+='
	UNION ALL 
	SELECT  BillNo,
			BillDate,
			BillCode,
			'+Cast(BillTypeID AS varchar)+' AS BillTypeID,
			'''+billname+''' AS BillName,
			DeptID,
			ElyID,'
			+CASE WHEN billtypeid IN(201,202,305,404,405) THEN 'IsOS' ELSE '0' END+' as IsOS,'
			+CASE WHEN billtypeid IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504,600) THEN 'BtypeID' ELSE '0' END+' as BtypeID,'
			+CASE WHEN billtypeid IN(101,102,201,202,302,303,304,305,306,600) THEN 'WhsID' WHEN billtypeid in(301,309,310) THEN 'OutWhsID'  ELSE '0' END+' as WhsID,'
			+CASE WHEN @IsInAndOut=1 THEN 'OutWhsID,' ELSE '' END				--单独选择调拨单的时候需要显示出入库两个仓库
			+CASE WHEN @IsInAndOut=1 THEN 'InWhsID,' ELSE '' END
			+CASE WHEN billtypeid=310 THEN 'InTotal As Total,' ELSE 'Total,' END
			+CASE WHEN billtypeid IN(101,102,201,202,401,402,602) THEN 'Privilege' ELSE '0' END+' as Privilege,'	--优惠金额
			+CASE WHEN billtypeid IN(101,201,102,202,403,404,405,406,602) THEN 'PayRecTotal' ELSE '0' END+' as PayRecTotal,'
			+CASE WHEN billtypeid IN(101,201,102,202,403,404,405,501,502,503,504,602) THEN 'PaidTotal' ELSE '0' END+' as PaidTotal,'
			+CASE WHEN billtypeid =201 THEN 'LogistBillNo' ELSE '''''' END+' as LogistBillNo,
			Creator As CreatorID,
			CreateTime,
			PosElyID,
			Red,
			Summary,
			Description,
			PosTime
	FROM '+BillTable+'_His I '
	+CASE WHEN @IsInAndOut=0 AND(dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2 OR @WhsID<>'') AND billtypeid IN(101,102,201,202,302,303,304,305,306,600) THEN ' INNER JOIN @KType W ON I.WhsID=W.TypeID ' ELSE '' END
	+CASE WHEN @IsInAndOut=0 AND (dbo.UF_BD_IsAllKtypeLimit(@UserID)<>2 OR @WhsID<>'') AND billtypeid IN(301,309,310) THEN ' INNER JOIN @KType W ON I.OutWhsID=W.TypeID ' ELSE '' END
	+CASE WHEN @BTypeID='' AND dbo.UF_BD_IsAllBtypeLimit(@UserID)=2 OR billtypeid NOT IN(101,102,201,202,303,304,401,402,404,405,501,502,503,504,600) THEN '' ELSE ' INNER JOIN @BType B ON I.BTypeID=B.TypeID '  END
	+@SqlTable
	+'WHERE	'+CASE @DateType WHEN 0 THEN ' BillDate' WHEN 1 THEN 'CreateTime' ELSE 'PosTime' END +' BETWEEN @BeginDate AND @EndDate' 
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
			+ case when billtypeid in(301,309,310) then @WhsStr ELSE '' end
			+@BillCodeStr 
			+@LogistBillNoStr
			+@SummaryStr
			+@DescriptionStr
			+CASE WHEN @FullName='' AND @UserCode='' THEN '' ELSE ' AND EXISTS(SELECT 1 FROM '+BillDetail+' d INNER JOIN BD_Goods g ON d.GoodsID=g.GoodsID WHERE I.BillNo=D.BillNo '+@FullNameStr+@UserCodeStr+')' END 
			+' AND IsDraft=0 '
			+CASE WHEN @FinanceID='' OR billtypeid NOT IN(101,201,102,202,403,404,405,406,602) THEN '' ELSE ' AND EXISTS(SELECT 1 FROM @AType A WHERE I.FinanceID=A.TypeID '+case when billtypeid in (101,201) THEN 'OR I.FreightFinanceID=A.TypeID ' ELSE '' END+'
			OR EXISTS(SELECT 1 FROM PD_MulAccounts M INNER JOIN @AType A ON M.FinanceID=A.TypeID WHERE M.BillTypeID='+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo))' END
			+CASE WHEN @FinanceID<>'' AND BillTypeID IN(401,402) THEN ' AND EXISTS(SELECT 1 FROM MF_PayRecDetail M INNER JOIN @AType A ON M.FinanceID=A.TypeID AND M.BillNo=I.BillNo) ' ELSE '' END	
			+CASE WHEN @ShowRed=0 THEN '' WHEN @ShowRed=1 THEN ' AND Red<>0 ' ELSE ' And Red=0' END 
			+CASE WHEN @Weixin=0 THEN '' ELSE ' AND '+ CASE @Weixin WHEN 1 THEN 'NOT' ELSE '' END +' EXISTS(SELECT 1 FROM PD_WeiXinAccounts WHERE BillTypeID='+Cast(BillTypeID AS varchar)+' AND BillNo=I.BillNo '+CASE @Weixin WHEN 3 THEN 'AND PayStatus=1' WHEN 4 THEN 'AND PayStatus=0' ELSE '' END+')' END
	FROM PD_BillType b
	INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0
	WHERE CanPost=1

drop table #BillType

SELECT @sql=@SqlCreateTable+'
;WITH PagingData AS 
('	+STUFF(@sql,1,12,'')+'
)'

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END
--print @sql
SET @sql+='	
	 ,DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderField+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	) 
	SELECT * INTO #PostBillData FROM DATA
	SELECT Data.*,
		   CASE wx.PayStatus WHEN 0 THEN ''支付失败'' WHEN 1  THEN ''支付成功'' ELSE '''' END WeiXinStatus, '

if @IsInAndOut=0
	set @sql+= 'w.WhsName,w.WhsNo,d.DeptName,D.DeptCode,e.ElyName,e.ElyCode,e1.ElyName as Creator,e1.ElyCode as CreatorCode,e2.ElyName as Postor,e2.ElyCode as PostorCode,b.BTypeName,b.BTypeCode
	FROM #PostBillData Data
	LEFT JOIN BD_Whs w ON Data.WhsID = w.WhsID '
ELSE
	SET @sql+='wi.WhsName AS InWhsName,wi.WhsNO as InWhsNo,wo.WhsName AS OutWhsName,wo.WhsNO as OutWhsNo,d.DeptName,D.DeptCode,e.ElyName,e.ElyCode,e1.ElyName as Creator,e1.ElyCode as CreatorCode,e2.ElyName as Postor,e2.ElyCode as PostorCode,b.BTypeName,b.BTypeCode
	FROM #PostBillData Data
	LEFT JOIN BD_Whs wi ON Data.InWhsID = wi.WhsID
	LEFT JOIN BD_Whs wo ON Data.OutWhsID = wo.WhsID'
SET @sql+='
	LEFT JOIN dbo.PD_WeiXinAccounts wx ON data.BillNo = wx.BillNo AND data.BillTypeID = wx.BillTypeID
	LEFT JOIN BD_Dept d ON Data.DeptID = d.DeptID 
	LEFT JOIN BD_Employee e ON Data.ElyID = e.ElyID 
	LEFT JOIN BD_Employee e1 ON Data.CreatorID = e1.ElyID 
	LEFT JOIN BD_Employee e2 ON Data.PosElyID = e2.ElyID 
	LEFT JOIN BD_Btype b ON Data.BtypeID = b.BtypeID 
	ORDER BY '+@OrderField+'
	DROP Table #PostBillData
	'
DECLARE @curPos INT = 1,@count int=1
 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
EXEC sp_executesql @sql,N'@DateType INT,@BeginDate Date,@EndDate Date,@BTypeID VarChar(MAX),@DeptID VarChar(MAX),@ElyID VarChar(MAX),@OperatorID VarChar(max),@WhsID VarChar(MAX),@inWhsID VarChar(MAX),@OutWhsID VarChar(MAX),@FinanceID VarChar(MAX),@BillCode VarChar(50),
						@FullName VarChar(100),@UserCode VarChar(50),@LogistBillNo VarChar(20),@Summary VarChar(256),@Description VarChar(100),@UserID INT,@PageNo int,@PageSize INT',
						@DateType,@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID,@OperatorID,@WhsID,@inWhsID,@OutWhsID,@FinanceID,@BillCode,
						@FullName,@UserCode,@LogistBillNo,@Summary,@Description,@UserID,@PageNo,@PageSize


GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_OT_WeiXinPayCheckQuery]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_OT_WeiXinPayCheckQuery]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：hlin
	日期：2016-3-11
	描述：微信支付对账单
-------------------------------------------*/
CREATE PROCEDURE [UP_OT_WeiXinPayCheckQuery]
(			   
	@pageNo INT=1,					--页码
	@pageSize INT=10,				--分页数
	@BillStartDate DATETIME,		--单据开始日期
	@BillEndDate DATETIME,			--单据结束日期
	@BillType INT=0,			    --账单类型
	@Type INT=0						--查询类型 0=明细 1=合计
)
AS
SET NOCOUNT ON
BEGIN


DECLARE @Sql NVARCHAR(MAX)='',@SqlJoin VARCHAR(max)='',@VipTableStr NVARCHAR(max)=''
--INNER JOIN BEGIN

  
SET @Sql ='
WITH BillData AS(
SELECT	TradeTime ,
		BillCode ,
		MchBillCode ,
		TradeStatus,
		CASE TradeType WHEN ''JSAPI'' THEN ''公众号支付''
			WHEN ''NATIVE'' THEN ''扫码支付''
			WHEN ''MICROPAY'' THEN ''刷卡支付''
			WHEN ''APP'' THEN ''APP支付''
		END  TradeType ,
		Total ,
		Privilege ,
		GoodsName ,
		Poundage ,
		Rate ,
		RetBillCode ,
		MchRetBillCode ,
		RetTotal ,
		RetPrivilege ,
		CASE RetType WHEN ''ORIGINAL'' THEN ''原路退款''
			WHEN ''BALANCE'' THEN ''退回到余额''
		END RetType,
		CASE RetStatus  WHEN ''PROCESSING'' THEN ''退款处理中''
			WHEN ''SUCCESS'' THEN ''退款成功''
			WHEN ''FAIL'' THEN ''退款失败 ''
			WHEN ''CHANGE'' THEN ''转入代发''
			WHEN ''NOTSURE'' THEN ''未确定，需要商户原退款单号重新发起''
		END RetStatus,
		RetCreateTime ,
		RetSuccessTime
FROM dbo.OT_WXStateBill 
WHERE TradeTime BETWEEN @BillStartDate AND @BillEndDate '

IF @BillType<>0
	SET @sql+='AND TradeStatus='+CASE @BillType WHEN 1 THEN '''SUCCESS''' WHEN 2 THEN '''REFUND''' END

IF @Type=0
	SET @sql+='
), 
PageData AS(
SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM BillData) A
CROSS JOIN
(
SELECT	ROW_NUMBER() OVER( ORDER BY TradeTime DESC ) AS ROWID,
*
FROM BillData
) B
WHERE B.ROWID>(@PageNo-1)*@PageSize
AND B.ROWID<=@PageNo*@PageSize
)
SELECT p.*,
		R.BillTypeID,
		R.BillNo,
		R.BillCode SysBillCode,
		BillName
FROM PageData p  
LEFT JOIN  PD_WeiXinRecord R ON R.out_trade_no=p.MchBillCode AND R.out_refund_no=p.MchRetBillCode
LEFT JOIN PD_BillType t ON R.BillTypeID=t.BillTypeID'
ELSE
	SET @sql+=')
	SELECT SUM(Total)Total,SUM(Privilege)Privilege,SUM(Poundage)Poundage,SUM(RetTotal)RetTotal,SUM(RetPrivilege)RetPrivilege from BillData'

EXEC SP_EXECUTESQL @Sql,N'@pageNo INT,@pageSize INT,@BillStartDate DATETIME,@BillEndDate DATETIME'
,@pageNo,@pageSize,@BillStartDate,@BillEndDate 


END


GO






if exists (select * from sysobjects where id = object_id(N'[UP_PD_AdjustPriceBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_PD_AdjustPriceBill]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		雷洋
-- Create date:  2014/6/17
-- Description:	 调价单
-- =============================================
CREATE PROCEDURE [UP_PD_AdjustPriceBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	if exists( select 1 from PD_AdjPriceBill where BillNo = @BillNo)
	begin	
		select  BillNo,
			BillDate,
			BillCode,
			Bill.DeptID,
			Bill.ElyID,
			bill.WhsID,
			BillQty,
			Total,
			Creator,
			PosElyID,
			Summary,
			Description,
			IsDraft,
			Red,
			d.DeptName,
			e.ElyName,
			w.WhsName,
			ec.ElyName as CreatorName,
			ep.ElyName as PosName,
			bill.AuditStatus
			from PD_AdjPriceBill bill
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN  BD_Whs w ON bill.WhsID=w.WhsID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 where BillNo = @BillNo
	     
		  SELECT	  detail.[DID]
			  ,detail.[BillNo]
			  ,detail.BarCode
			  ,detail.GoodsID
			  ,detail.UnitID
			  ,detail.Convfactor
			  ,detail.Qty
			  ,detail.BSQty
			  ,round(detail.CostPrice*detail.Convfactor,8) as CostPrice
			  ,detail.CostPrice as GoodsCostPrice
			  ,detail.AdjPrice
			  ,detail.GoodsCostTotal as CostTotal
			  ,detail.GoodsCostTotal
			  ,detail.AdjTotal
			  ,detail.[Remark]
			  ,detail.WhsID
			  ,detail.Ppt1ID
			  ,detail.WhsPtID
			  ,wp.WhsPtName
			  ,p1.Value AS Ppt1Name
			  ,detail.Ppt2ID
			  ,p2.Value AS Ppt2Name
			  ,g.GoodsNo
			  ,g.GoodsName
			  ,g.Model
			  ,g.Spec
			  ,gp.Unit
			  ,gpr1.Convfactor as Convfactor1
			  ,ISNULL(gpr2.Convfactor,1) as Convfactor2
			  ,ISNULL(gpr3.Convfactor,1) as Convfactor3
			  ,gpr1.BarCode[BarCode1],gpr2.BarCode[BarCode2],gpr3.BarCode[BarCode3]
			  ,gpr1.Unit as Unit1
			  ,gpr2.Unit as Unit2
			  ,gpr3.Unit as Unit3,
			  g.IsSerial,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.InPutPrice,g.CostMethod,detail.IsSelectBatch
		 FROM PD_AdjPriceDetail detail
			  INNER JOIN BD_Goods g ON detail.GoodsID=g.GoodsID	
			  LEFT JOIN BD_Whs_Position wp ON detail.WhsPtID = wp.WhsPtID
			  LEFT JOIN BD_Goods_Price gp ON detail.UnitID = gp.UnitID and detail.GoodsID = gp.GoodsID
			  LEFT JOIN BD_Goods_Ppt1 p1 ON detail.Ppt1ID = p1.Ppt1ID
			  LEFT JOIN BD_Goods_Ppt2 p2 ON detail.Ppt2ID=p2.Ppt2ID
			  LEFT JOIN BD_Goods_Price gpr1 ON g.GoodsID = gpr1.GoodsID and gpr1.UnitID = 1
			  LEFT JOIN BD_Goods_Price gpr2 ON g.GoodsID = gpr2.GoodsID and gpr2.UnitID = 2
			  LEFT JOIN BD_Goods_Price gpr3 ON g.GoodsID = gpr3.GoodsID and gpr3.UnitID = 3
		 WHERE detail.BillNo = @BillNo;  --查询明细    
		 -- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_AdjPriceSerial ps Inner Join PD_AdjPriceDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
	ELSE
	BEGIN
	select  BillNo,
			BillDate,
			BillCode,
			Bill.DeptID,
			Bill.ElyID,
			bill.WhsID,
			BillQty,
			Total,
			Creator,
			PosElyID,
			Summary,
			Description,
			IsDraft,
			Red,
			d.DeptName,
			e.ElyName,
			w.WhsName,
			ec.ElyName as CreatorName,
			ep.ElyName as PosName,
			bill.AuditStatus
			from PD_AdjPriceBill_His bill
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN  BD_Whs w ON bill.WhsID=w.WhsID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 where BillNo = @BillNo
	     
		  SELECT	  detail.[DID]
			  ,detail.[BillNo]
			  ,detail.BarCode
			  ,detail.GoodsID
			  ,detail.UnitID
			  ,detail.Convfactor
			  ,detail.Qty
			  ,detail.BSQty
			  ,round(detail.GoodsCostTotal/detail.Qty,8) as CostPrice
			  ,detail.CostPrice as GoodsCostPrice
			  ,detail.AdjPrice
			  ,detail.GoodsCostTotal as CostTotal
			  ,detail.GoodsCostTotal
			  ,detail.AdjTotal
			  ,detail.[Remark]
			  ,detail.WhsID
			  ,detail.Ppt1ID
			  ,detail.WhsPtID
			  ,wp.WhsPtName
			  ,p1.Value AS Ppt1Name
			  ,detail.Ppt2ID
			  ,p2.Value AS Ppt2Name
			  ,g.GoodsNo
			  ,g.GoodsName
			  ,g.Model
			  ,g.Spec
			  ,gp.Unit
			  ,gpr1.Convfactor as Convfactor1
			  ,ISNULL(gpr2.Convfactor,1) as Convfactor2
			  ,ISNULL(gpr3.Convfactor,1) as Convfactor3
			  ,gpr1.BarCode[BarCode1],gpr2.BarCode[BarCode2],gpr3.BarCode[BarCode3]
			  ,gpr1.Unit as Unit1
			  ,gpr2.Unit as Unit2
			  ,gpr3.Unit as Unit3,
			  g.IsSerial,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.InPutPrice,g.CostMethod
		 FROM PD_AdjPriceDetail_His detail
			  INNER JOIN BD_Goods g ON detail.GoodsID=g.GoodsID	
			  LEFT JOIN BD_Whs_Position wp ON detail.WhsPtID = wp.WhsPtID
			  LEFT JOIN BD_Goods_Price gp ON detail.UnitID = gp.UnitID and detail.GoodsID = gp.GoodsID
			  LEFT JOIN BD_Goods_Ppt1 p1 ON detail.Ppt1ID = p1.Ppt1ID
			  LEFT JOIN BD_Goods_Ppt2 p2 ON detail.Ppt2ID=p2.Ppt2ID
			  LEFT JOIN BD_Goods_Price gpr1 ON g.GoodsID = gpr1.GoodsID and gpr1.UnitID = 1
			  LEFT JOIN BD_Goods_Price gpr2 ON g.GoodsID = gpr2.GoodsID and gpr2.UnitID = 2
			  LEFT JOIN BD_Goods_Price gpr3 ON g.GoodsID = gpr3.GoodsID and gpr3.UnitID = 3
		 WHERE detail.BillNo = @BillNo;  --查询明细    
		 -- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_AdjPriceSerial_His ps Inner Join PD_AdjPriceDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END                                            
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AdjustWhsPt]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_AdjustWhsPt
GO
/****** Object:  StoredProcedure [UP_PD_AdjustWhsPt]    Script Date: 05/27/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		lY
-- Create date:  2014/6/03
-- Description:	 货位调整
-- =============================================
CREATE PROCEDURE [UP_PD_AdjustWhsPt](
     @PageNo INT = 0,
     @PageSize INT = 0,
	 @WhsID INT = 0, --仓库
	 @WshPtID  VARCHAR(50) = '',  --货位
	 @GoodsTypeID INT = 0,  --商品分类
	 @GoodsNO VARCHAR(50) = '',  --商品编号
	 @GoodsNOMatch INT=0,
	 @GoodsName VARCHAR(100) = '',  --商品名称
	 @GoodsNameMatch INT=0,
	 @Spec VARCHAR(50) = '',  --规格
	 @SpecMatch INT=0,
	 @Model VARCHAR(50) = '',  --型号
	 @ModelMatch INT=0,
	 @Place VARCHAR(50) = '',  --产地
	 @PlaceMatch INT=0,
	 @AbbName VARCHAR(50) = '',      --简名
	 @AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',        --品牌
	 @BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',      --条码
	 @BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	 @Ppt1 VARCHAR(50) = '',  --属性1
	 @Ppt1Match INT=0,
	 @Ppt2 VARCHAR(50)= '',  --属性2
	 @Ppt2Match INT=0,
	 @NegativeFlag int = 0,  --只显示负库存商品 
	 @ZeroFlag int = 0,  --显示0库存货位 
	 @Stt INT = 0,  --显示停用商品
	 @OrderType1 Int=0,
	 @OrderSeq1 Int=1,
	 @ClickFlag Int=0 --判断是否跳转页面，特殊处理规格和型号条件
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	IF (@WhsID<=0) 
	BEGIN
		 RAISERROR ('请选择"仓库"进行查询！' , 16, 1) WITH NOWAIT
		  RETURN 1
	END
	DECLARE @Sql NVARCHAR(MAX),@SqlCreateTable varchar(max)='',@SqlGoodsType varchar(max)='',@ordStr varchar(100)=''
	,@WhsPt varchar(max)= '',@WhsPtStr varchar(max)='',@StrWhsPt varchar(max)=''
	DECLARE @TVP AS [TVP_Paging_Param]
	if @GoodsTypeID <> 0
	Begin
		Set @SqlCreateTable += ' DECLARE @GoodsType  as Table(typeid int) INSERT INTO @GoodsType(typeid) ' + dbo.UF_BD_GetGoodsID_Str('')
		Set @SqlGoodsType +=' Inner Join @GoodsType GT on G.GoodsID = GT.TypeID '
	End
if @WshPtID<>''
	Set @StrWhsPt += ' INNER Join dbo.UF_OT_Split_Int(@WshPtID,'','') WPID on WP.WhsPtID = WPID.typeid '
if @ZeroFlag = 1
Begin
	Select @WhsPt += ',WhsPt as
		(
			select WhsPtID,WhsPtNO,WhsPtName,0 as GoodsID,'''' as Ppt1Name,'''' as Ppt2Name,0 as Ppt1ID,0 as Ppt2ID,'''' as Model,'''' as Place,'''' as Spec,'''' as GoodsNO,'''' as GoodsName,'''' as Unit,1 as Stt,0 as Qty 
			 from BD_Whs_Position Wp '+@StrWhsPt+' where WhsPtID not in (select distinct WhsPtID from PD_GoodsStock_Detail ) And WhsID = @WhsID
		) '
	Select @WhsPtStr += ' Union All
			select WhsPtID,WhsPtNO,WhsPtName,GoodsID,Ppt1Name,Ppt2Name,Ppt1ID,Ppt2ID,Model,Place,Spec,GoodsNO,GoodsName,Unit,Stt,Qty,'''' AS Brand,'''' AS GoodsAbbName,'''' AS BarCode, 0 AS IsSerial
			from WhsPt '
End

-- 新增了批次信息，需按组合计
SET @Sql = @SqlCreateTable + ' ;WITH GOODSSTOCK AS
		(
			SELECT GD.GoodsID,WhsPtID,Ppt1ID,Ppt2ID,SUM(GD.Qty) AS Qty,WhsID 
			FROM PD_GoodsStock_Detail GD INNER JOIN PD_GoodsStock GS ON GS.StockID = GD.StockID where GS.WhsID = @WhsID 
			GROUP BY GD.GoodsID,WhsPtID,Ppt1ID,Ppt2ID,WhsID '
	if @NegativeFlag <> 0
		Set @Sql += ' HAVING SUM(GD.Qty) < 0 '--' AND GD.Qty<0 '
	Set @Sql += '	),goods AS
		(
			SELECT WhsID,WhsPtID,Qty,G.GoodsID,G.GoodsNO,G.GoodsName,GS.Ppt1ID Ppt1ID,P1.Value Ppt1Name,GS.Ppt2ID as Ppt2ID,P2.Value Ppt2Name,G.Model,G.Place,G.Spec,Unit,G.Stt,G.Brand,G.GoodsAbbName,GPI.BarCode
					,g.IsSerial 
			FROM GOODSSTOCK GS LEFT JOIN BD_Goods G on GS.GoodsID = g.GoodsID
			LEFT JOIN BD_Goods_Ppt1 P1 ON GS.Ppt1ID = P1.Ppt1ID
			LEFT JOIN BD_Goods_Ppt2 P2 ON GS.Ppt2ID = P2.Ppt2ID
			LEFT JOIN BD_Goods_Price GPI ON G.GoodsID = GPI.GoodsID AND GPI.UnitID=1
			'+@SqlGoodsType+'
			where 1=1 '
	if @GoodsNO <> ''
		Set @Sql = @Sql + ' AND G.GoodsNo ' + Case @GoodsNOMatch when 0 then ' like ''%'' + @GoodsNO +''%''' Else '=@GoodsNO ' End
	if @GoodsName <> ''
		Set @Sql = @Sql + ' AND G.GoodsName ' + Case @GoodsNameMatch when 0 then ' Like ''%'' + @GoodsName +''%''' Else '=@GoodsName ' End
	if @Ppt1 <> ''
		Set @Sql = @Sql + ' AND P1.Value '+ Case @Ppt1Match when 0 then ' like ''%'' + @Ppt1 +''%''' Else ' =@Ppt1' End
	if @Ppt2 <> ''
		Set @Sql = @Sql + ' AND P2.Value '+ Case @Ppt2Match when 0 then ' like ''%'' + @Ppt2 +''%''' Else ' =@Ppt2' End
	if @Stt = 0
		Set @Sql = @Sql + ' AND G.Stt = 1 '
	if (@ClickFlag= 1 and @Spec = '' and @GoodsTypeID = 0) or @Model <> ''
		Set @Sql = @Sql + ' AND G.Model '+ Case @ModelMatch when 0 then ' Like ''%'' + @Model +''%''' Else ' =@Model' End
	if @Place <> ''
		Set @Sql = @Sql + ' AND G.Place '+ Case @PlaceMatch when 0 then ' Like ''%'' + @Place +''%''' Else ' =@Place' End
	if (@ClickFlag= 1 and @Model = '' and @GoodsTypeID = 0) or @Spec <> ''
		Set @Sql = @Sql + ' AND G.Spec '+ Case @SpecMatch when 0 then ' Like ''%'' + @Spec +''%''' Else ' =@Spec' End
	/*新增商品查询条件 start 150901*/
	if @AbbName <> ''
		Set @Sql = @Sql + ' AND G.GoodsAbbName ' + Case @AbbNameMatch when 0 then ' like ''%'' + @AbbName +''%''' Else '=@AbbName ' End
	if @Brand <> ''
		Set @Sql = @Sql + ' AND G.Brand ' + Case @BrandMatch when 0 then ' Like ''%'' + @Brand +''%''' Else '=@Brand ' End
	if @BarCode <> ''
		Set @Sql = @Sql + ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = GS.GoodsID AND barcode.BarCode ' + Case @BarCodeMatch when 0 then ' LIKE ''%'' + @BarCode +''%''' Else '=@BarCode' End + ' ) '
	/*end*/
	Set @Sql = @Sql +'			) '
	Set @Sql += @WhsPt + '
				,PagingData AS
				(
					SELECT G.WhsPtID,WhsPtNO,WhsPtName,GoodsID,Ppt1Name,Ppt2Name,Ppt1ID,Ppt2ID,Model,Place,Spec,GoodsNO,GoodsName,Unit,G.Stt,Qty,G.Brand,G.GoodsAbbName,G.BarCode
					,g.IsSerial 
			FROM goods G left join BD_Whs_Position WP '+@StrWhsPt+' on g.WhsPtID = WP.WhsPtID  
			
			where wp.WhsID = @WhsID '			
	SET @sql += + @WhsPtStr
	SET @sql += + ' )'

if @OrderType1 = 0
Begin
	Select @ordStr += ' WhsPtNO '
	if @OrderSeq1 = 2
		Select @ordStr += ' desc '
	Select @ordStr += ',GoodsNO'
End
else 
Begin
	Select @ordStr += ' GoodsNO '
	if @OrderSeq1 = 2
		Select @ordStr += ' desc '
	Select @ordStr += ',WhsPtNO'
ENd

	
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@WhsID', 'VARCHAR(20)', @WhsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@WshPtID', 'VARCHAR(50)', @WshPtID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsTypeID', 'INT', @GoodsTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsNO', 'VARCHAR(50)', @GoodsNO)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsName', 'VARCHAR(100)', @GoodsName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Spec', 'VARCHAR(50)', @Spec)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Model', 'VARCHAR(50)', @Model)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Place', 'VARCHAR(50)', @Place)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Ppt1', 'VARCHAR(50)', @Ppt1)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Ppt2', 'VARCHAR(50)', @Ppt2)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@AbbName', 'VARCHAR(50)', @AbbName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Brand', 'VARCHAR(50)', @Brand)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BarCode', 'VARCHAR(100)', @BarCode)

EXEC [UP_OT_Paging] @sql,@TVP,@PageNo,@PageSize,@ordStr,'',@ordStr,1,0

	
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AdjustWhsPtSum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_AdjustWhsPtSum
GO
/****** Object:  StoredProcedure [UP_PD_AdjustWhsPt]    Script Date: 05/27/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		lY
-- Create date:  2015/10/26
-- Description:	 货位调整
-- =============================================
CREATE PROCEDURE [UP_PD_AdjustWhsPtSum](
	 @WhsID INT = 0, --仓库
	 @WshPtID  VARCHAR(50) = '',  --货位
	 @GoodsTypeID INT = 0,  --商品分类
	 @GoodsNO VARCHAR(50) = '',  --商品编号
	 @GoodsNOMatch INT=0,
	 @GoodsName VARCHAR(100) = '',  --商品名称
	 @GoodsNameMatch INT=0,
	 @Spec VARCHAR(50) = '',  --规格
	 @SpecMatch INT=0,
	 @Model VARCHAR(50) = '',  --型号
	 @ModelMatch INT=0,
	 @Place VARCHAR(50) = '',  --产地
	 @PlaceMatch INT=0,
	 @AbbName VARCHAR(50) = '',      --简名
	 @AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',        --品牌
	 @BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',      --条码
	 @BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	 @Ppt1 VARCHAR(50) = '',  --属性1
	 @Ppt1Match INT=0,
	 @Ppt2 VARCHAR(50)= '',  --属性2
	 @Ppt2Match INT=0,
	 @NegativeFlag int = 0,  --只显示负库存商品 
	 @ZeroFlag int = 0,  --显示0库存货位 
	 @Stt INT = 0,  --显示停用商品
	 @ClickFlag Int=0 --判断是否跳转页面，特殊处理规格和型号条件
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	IF (@WhsID<=0) 
	BEGIN
		 RAISERROR ('请选择"仓库"进行查询！' , 16, 1) WITH NOWAIT
		  RETURN 1
	END
	DECLARE @Sql NVARCHAR(MAX),@SqlCreateTable varchar(max)='',@SqlGoodsType varchar(max)='',@ordStr varchar(100)=''
	,@WhsPt varchar(max)= '',@WhsPtStr varchar(max)='',@StrWhsPt varchar(max)='',@sqlParam varchar(max)=''
	DECLARE @TVP AS [TVP_Paging_Param]
	if @GoodsTypeID <> 0
	Begin
		Set @SqlCreateTable += ' DECLARE @GoodsType  as Table(typeid int) INSERT INTO @GoodsType(typeid) ' + dbo.UF_BD_GetGoodsID_Str('')
		Set @SqlGoodsType +=' Inner Join @GoodsType GT on G.GoodsID = GT.TypeID '
	End
if @WshPtID<>''
	Set @StrWhsPt += ' INNER Join dbo.UF_OT_Split_Int(@WshPtID,'','') WPID on WP.WhsPtID = WPID.typeid '
if @ZeroFlag = 1
Begin
	Select @WhsPt += ',WhsPt as
		(
			select 0 as Qty 
			 from BD_Whs_Position Wp '+@StrWhsPt+' where WhsPtID not in (select distinct WhsPtID from PD_GoodsStock_Detail ) And WhsID = @WhsID
		) '
	Select @WhsPtStr += ' Union All
			select Qty 
			from WhsPt '
End

if @GoodsNO <> ''
		Set @sqlParam += ' AND G.GoodsNo ' + Case @GoodsNOMatch when 0 then ' like ''%'' + @GoodsNO +''%''' Else '=@GoodsNO ' End
	if @GoodsName <> ''
		Set @sqlParam +=  ' AND G.GoodsName ' + Case @GoodsNameMatch when 0 then ' Like ''%'' + @GoodsName +''%''' Else '=@GoodsName ' End
	if @Ppt1 <> ''
	Begin
		Set @SqlGoodsType += ' LEFT JOIN BD_Goods_Ppt1 P1 ON GS.Ppt1ID = P1.Ppt1ID '
		Set @sqlParam +=  ' AND P1.Value '+ Case @Ppt1Match when 0 then ' like ''%'' + @Ppt1 +''%''' Else ' =@Ppt1' End
	End
	if @Ppt2 <> ''
	BEGIN
		Set @SqlGoodsType += ' LEFT JOIN BD_Goods_Ppt2 P2 ON GS.Ppt2ID = P2.Ppt2ID '
		Set @sqlParam += ' AND P2.Value '+ Case @Ppt2Match when 0 then ' like ''%'' + @Ppt2 +''%''' Else ' =@Ppt2' End
	END
	if @Stt = 0
		Set @sqlParam +=  ' AND G.Stt = 1 '
	if (@ClickFlag= 1 and @Spec = '' and @GoodsTypeID = 0) or @Model <> ''
		Set @sqlParam +=  ' AND G.Model '+ Case @ModelMatch when 0 then ' Like ''%'' + @Model +''%''' Else ' =@Model' End
	if @Place <> ''
		Set @sqlParam +=  ' AND G.Place '+ Case @PlaceMatch when 0 then ' Like ''%'' + @Place +''%''' Else ' =@Place' End
	if (@ClickFlag= 1 and @Model = '' and @GoodsTypeID = 0) or @Spec <> ''
		Set @sqlParam +=  ' AND G.Spec '+ Case @SpecMatch when 0 then ' Like ''%'' + @Spec +''%''' Else ' =@Spec' End
	/*新增商品查询条件 start 150901*/
	if @AbbName <> ''
		Set @sqlParam +=  ' AND G.GoodsAbbName ' + Case @AbbNameMatch when 0 then ' like ''%'' + @AbbName +''%''' Else '=@AbbName ' End
	if @Brand <> ''
		Set @sqlParam +=  ' AND G.Brand ' + Case @BrandMatch when 0 then ' Like ''%'' + @Brand +''%''' Else '=@Brand ' End
	if @BarCode <> ''
		Set @sqlParam +=  ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = GS.GoodsID AND barcode.BarCode ' + Case @BarCodeMatch when 0 then ' LIKE ''%'' + @BarCode +''%''' Else '=@BarCode' End + ' ) '

SET @Sql = @SqlCreateTable + ' ;WITH GOODSSTOCK AS
		(
			SELECT GD.GoodsID,WhsPtID,Ppt1ID,Ppt2ID,GD.Qty,WhsID 
			FROM PD_GoodsStock_Detail GD INNER JOIN PD_GoodsStock GS ON GS.StockID = GD.StockID where GS.WhsID = @WhsID '
	if @NegativeFlag <> 0
		Set @Sql += ' AND GD.Qty<0 '
	Set @Sql += '	),goods AS
		(
			SELECT WhsPtID,Qty
			FROM GOODSSTOCK GS LEFT JOIN BD_Goods G on GS.GoodsID = g.GoodsID
			'+@SqlGoodsType+'
			where 1=1 ' + @sqlParam + '  ) '
	
	/*end*/
	Set @Sql += @WhsPt + '
				,PagingData AS
				(
					SELECT Qty
			FROM goods G left join BD_Whs_Position WP '+@StrWhsPt+' on g.WhsPtID = WP.WhsPtID  
			
			where wp.WhsID = @WhsID '			
	SET @sql += + @WhsPtStr
	SET @sql += + ' )
	
	select Sum(Qty) As Qty from PagingData '
print @sql
EXEC sp_executesql @sql,
N'@WhsID VARCHAR(20), @WshPtID VARCHAR(50),@GoodsTypeID INT,@GoodsNO VARCHAR(50),@GoodsName VARCHAR(100),@Spec VARCHAR(50),@Model VARCHAR(50),@Place VARCHAR(50)
,@Ppt1 VARCHAR(50),@Ppt2 VARCHAR(50),@AbbName VARCHAR(50),@Brand VARCHAR(50),@BarCode VARCHAR(100)',
@WhsID, @WshPtID,@GoodsTypeID,@GoodsNO,@GoodsName,@Spec,@Model, @Place, @Ppt1,@Ppt2,@AbbName,@Brand,@BarCode


	
END
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-12-23
	描述：调拨申请单明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_AllotDetailsSum]
(
	@DID Int = 0,
	@OperatorID INT 
)

AS
SET NOCOUNT ON

Declare @Sql Nvarchar(max)='',@BillSql Nvarchar(max)='',@SqlCreateTable VARCHAR(max)='',@sqlOut Nvarchar(Max)='',@LimitSqlIN NVARCHAR(max)='',@LimitSqlOut NVARCHAR(max)='',@KtypeLimit int
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSqlIN += ' Inner Join @LimitKType LW On LW.TypeID =i.InWhsID ' 	
	Set @LimitSqlOut += ' Inner Join @LimitKType LW On LW.TypeID =i.OutWhsID ' 	
End	

Select @BillSql += ' SELECT 0 as InQty, Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @LimitSqlOut +' where 
		 IsDraft=0 AND BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @LimitSqlIN +' where 
		 IsDraft=0 AND BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  0 as InQty,	Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @LimitSqlOut +' where 
		 IsDraft=0 AND BillTypeID = 309  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @LimitSqlIN +' where 
		 IsDraft=0 AND BillTypeID = 309  And Red = 0 And ReqDID = @DID
	 '
select @BillSql+= '
	UNION ALL
		SELECT  0 as InQty,Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @LimitSqlOut +' where 
		 IsDraft=0 AND BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @LimitSqlIN +' where 
		 IsDraft=0 AND BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  0 as InQty,	Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @LimitSqlOut +' where 
		 IsDraft=0 AND BillTypeID = 309  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @LimitSqlIN +' where 
		 IsDraft=0 AND BillTypeID = 309  And Red = 0 And ReqDID = @DID
		'
SELECT @sql= @SqlCreateTable + '
;WITH Bill AS 
('	+@BillSql+'
)
select SUM(InQty) as InQty,SUM(OutQty) as OutQty,SUM(Qty) as Qty,SUM(Total) as Total,SUM(DiscTotal) as DiscTotal,SUM(GoodsCostTotal) as GoodsCostTotal  from Bill
 '
--IF @sql IS NULL OR @sql=''
--BEGIN
--	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
--	RETURN 
--END
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
Exec sp_executesql @Sql,N'@DID Int,@OperatorID Int',@DID,@OperatorID 

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AllotReqDetailList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_AllotReqDetailList]
GO
/****** Object:  StoredProcedure [UP_PD_AllotReqDetailList] Script Date: 12/08/2014 15:32:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/12/8
-- Description:	 调拔申请单选择明细
-- =============================================
CREATE PROCEDURE [UP_PD_AllotReqDetailList](
     @BillNo INT = 0, --单据ID
	 @GoodsNo VARCHAR(50) = '', --商品编号
	 @GoodsName VARCHAR(100) = ''  --商品名称
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @feildsql VARCHAR(max)='',@joinsql VARCHAR(max)=''
	
	SET @joinsql=' LEFT JOIN BD_Goods_CustomVal C ON C.BaseID=detail.GoodsID '
	SELECT @joinsql+= CASE WHEN SourceType=1 THEN ' ' 
		WHEN SourceType=2 AND SOURCE=1 THEN ' LEFT JOIN BD_Goods G'+CAST(CustItemID AS VARCHAR)+' ON G'+CAST(CustItemID AS VARCHAR)+'.GoodsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=2 THEN ' LEFT JOIN BD_BType B'+CAST(CustItemID AS VARCHAR)+' ON B'+CAST(CustItemID AS VARCHAR)+'.BTypeID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=2 AND SOURCE=3 THEN ' LEFT JOIN BD_Whs W'+CAST(CustItemID AS VARCHAR)+' ON W'+CAST(CustItemID AS VARCHAR)+'.WhsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=4 THEN ' LEFT JOIN BD_Dept D'+CAST(CustItemID AS VARCHAR)+' ON D'+CAST(CustItemID AS VARCHAR)+'.DeptID=C.CustVal'+CAST(CustItemID AS VARCHAR)  
		WHEN SourceType=2 AND SOURCE=5 THEN ' LEFT JOIN BD_Employee E'+CAST(CustItemID AS VARCHAR)+' ON E'+CAST(CustItemID AS VARCHAR)+'.ElyID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=3 THEN ' LEFT JOIN BD_Custom C'+CAST(CustItemID AS VARCHAR) +' ON C'+CAST(CustItemID AS VARCHAR) +'.CustID=C.CustVal'+CAST(CustItemID AS VARCHAR)     
		END,
		@feildsql += CASE WHEN SourceType=1 THEN ' ,C.CustVal'+CAST(CustItemID AS VARCHAR)     
		WHEN SourceType=2 AND SOURCE=1 THEN ' ,G'+CAST(CustItemID AS VARCHAR)+'.GoodsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=2 THEN ' ,B'+CAST(CustItemID AS VARCHAR)+'.BTypeName AS CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=2 AND SOURCE=3 THEN ' ,W'+CAST(CustItemID AS VARCHAR)+'.WhsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=4 THEN ' ,D'+CAST(CustItemID AS VARCHAR)+'.DeptName AS CustVal'+CAST(CustItemID AS VARCHAR)  
		WHEN SourceType=2 AND SOURCE=5 THEN ' ,E'+CAST(CustItemID AS VARCHAR)+'.ElyName AS CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=3 THEN ',C'+CAST(CustItemID AS VARCHAR) +'.CustName AS CustVal'+CAST(CustItemID AS VARCHAR)     
		END
	FROM dbo.BD_Goods_CustomItem
	
	DECLARE @Sql NVARCHAR(MAX)
	SET @Sql = 'SELECT detail.DID AS ReqDID, detail.BillNo, detail.BarCode, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, 
					   detail.InWhsID, detail.InWhsPtID, detail.UnitID, detail.Convfactor, detail.Qty, detail.BSQty, 
					   detail.ComQty, inWhspt.WhsPtName AS InWhsPtName, detail.OutWhsID, detail.OutWhsPtID, 
					   detail.StopTag, detail.Remark, goods.GoodsNo, goods.GoodsName, stock.Price AS GoodsCostPrice,
					   goods.Spec, goods.Model, price.Unit, ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name, outWhspt.WhsPtName AS OutWhsPtName,
					   price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1, price1.Convfactor AS Convfactor1,
					   price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, price2.Convfactor AS Convfactor2,
					   price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3, price3.Convfactor AS Convfactor3,
					   goods.IsSerial,goods.CostMethod '
					   +@feildsql+'
                 FROM PD_AllotReqDetail detail
                 LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
                 LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID AND price.UnitID = detail.UnitID 
                 LEFT JOIN BD_Goods_Price price1 ON price1.GoodsID = detail.GoodsID AND price1.UnitID = 1
                 LEFT JOIN BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID AND price2.UnitID = 2
                 LEFT JOIN BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID AND price3.UnitID = 3
                 LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
                 LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
                 LEFT JOIN BD_Whs_Position inWhspt ON inWhspt.WhsPtID = detail.InWhsPtID 
                 LEFT JOIN BD_Whs_Position outWhspt ON outWhspt.WhsPtID = detail.OutWhsPtID 
                 LEFT JOIN PD_GoodsStock stock ON stock.WhsID = detail.OutWhsID AND stock.GoodsID = detail.GoodsID'
                 +@joinsql+'
                 WHERE detail.BillNo = @BillNo AND detaiL.BSQty > detaiL.ComQty 
                 AND detail.StopTag = 0 '  --完成数量(基本单位), 引用数量(基本数量)
	IF @GoodsNo <> ''
		SET @Sql += 'AND goods.GoodsNo LIKE ''%' + @GoodsNo + '%'' '  
	IF @GoodsName <> ''
		SET @Sql += 'AND goods.GoodsName LIKE ''%' + @GoodsName + '%'' '
	SET @Sql += 'ORDER BY detail.DID'
    --PRINT @Sql
    EXEC sp_executesql @Sql, N'@BillNo INT, @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100)', @BillNo, @GoodsNo, @GoodsName                 
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AllotReqList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_AllotReqList]
GO
/****** Object:  StoredProcedure [UP_PD_AllotReqList] Script Date: 12/08/2014 15:32:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/12/8
-- Description:	 调拔申请单选择
-- Update: sunzhiyuan 增加查询采购订单的时候排除未生效的单据
-- =============================================
CREATE PROCEDURE [UP_PD_AllotReqList](
     @PageNo INT = 0,
     @PageSize INT = 0,
     @BillCode VARCHAR(50) = '', --单据编号
	 @InWhsID INT = 0,  --要货仓库
	 @OutWhsID VARCHAR(1000) = '',  --发货仓库
	 @ElyID VARCHAR(1000) = '',  --经手人
	 @DeptID VARCHAR(1000) = '',  --部门
	 @GoodsNo VARCHAR(50)= '',  --商品编号
	 @GoodsName VARCHAR(100)= '',  --商品编号
     @Summary VARCHAR(50)= '',  --摘要
	 @Description VARCHAR(50)= '',  --说明
	 @BillStartDate DATETIME, --录单日期查询开始时间
	 @BillEndDate  DATETIME,  --录单日期查询结束时间
	 @DlvStartDate DATETIME = NULL, --交货日期查询开始时间
	 @DlvEndDate  DATETIME = NULL,  --交货日期查询结束时间
	 @OperatorID INT = 0 --操作员ID
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @TVP_Dept AS [TVP_Type], @KtypeLimit INT = 0,
			-- 过滤掉未生效的单据
	        @SqlParam NVARCHAR(MAX) = ' WHERE a.StopTag = 0 AND a.IsDraft = 0 AND a.BillDate BETWEEN @BillStartDate AND @BillEndDate '

	SET @Sql = ' ;WITH PagingData AS 
				 (SELECT a.BillNo, a.BillCode, a.BillDate, a.DlvDate, a.ElyID, a.DeptID, a.InWhsID,
						 a.OutWhsID, a.Summary, a.[Description] FROM PD_AllotReqBill a '
                         
	--仓库权限   
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)       
	        
	IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON a.OutWhsID = rWhs.WhsID '
	   
	IF @DlvStartDate IS NOT NULL AND @DlvEndDate IS NOT NULL
	   SET @SqlParam +=' AND a.DlvDate BETWEEN @DlvStartDate AND @DlvEndDate '
            
	IF @BillCode <> ''   
	   SET @SqlParam +=' AND a.BillCode LIKE ''%'' + @BillCode + ''%'''
       
	IF @DeptID <> ''
	   BEGIN
		 SET @Sql +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = a.DeptID '
		 INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
		 SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
			 INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
			 WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	   END
              
	IF @ElyID <> ''
	   SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = a.ElyID'
       
	IF @InWhsID <> 0
	   SET @SqlParam +='  AND a.InWhsID = @InWhsID '
       
	IF @OutWhsID <> ''
	   SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@OutWhsID, '','') _WhsOut ON _WhsOut.typeid = a.OutWhsID'
       
	IF @GoodsNo <> '' OR @GoodsName <> ''
	   BEGIN
		 SET @SqlParam +=' AND EXISTS (SELECT detail.DID FROM PD_AllotReqDetail detail
						   INNER JOIN BD_Goods goods on goods.GoodsID = detail.GoodsID
						   WHERE detaiL.BillNo = a.BillNo AND detaiL.StopTag = 0 
						   AND detaiL.BSQty > detaiL.ComQty '  		             
		 IF @GoodsNo <> ''
		  SET @SqlParam +=' AND goods.GoodsNo  LIKE ''%''+@GoodsNo+''%'''  
		             
		 IF @GoodsName <> ''
		  SET @SqlParam +=' AND goods.GoodsName  LIKE ''%''+@GoodsName+''%''' 
          
		  SET @SqlParam +=')'
	   END
	ELSE
	   SET @SqlParam +=' AND EXISTS (SELECT detail.DID FROM PD_AllotReqDetail detail
						 WHERE detaiL.BillNo = a.BillNo AND detaiL.StopTag = 0 
						 AND detaiL.BSQty > detaiL.ComQty )'  
                  
	IF @Summary <> ''
	   SET @SqlParam +=' AND a.Summary LIKE ''%''+@Summary+''%'''
                  
	IF @Description <> ''
	   SET @SqlParam +=' AND a.Description LIKE ''%''+@Description+''%'''

	SET @Sql= N'SET NOCOUNT ON;'
			 + @Sql + @SqlParam + ' )' +
			 N', _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName from BD_Employee)
			   , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName from BD_Dept)
			   , _DATA_InWhs AS (SELECT WhsID AS InWID, WhsNO AS InWhsNO, WhsName AS InWhsName from BD_Whs)
			   , _DATA_OutWhs AS (SELECT WhsID AS OutWID, WhsNO AS OutWhsNO, WhsName AS OutWhsName from BD_Whs)
			   , DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
						  CROSS JOIN
						 (SELECT ROW_NUMBER() OVER(ORDER BY BillNo) AS ROWID,* FROM PagingData) B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
			   SELECT * FROM DATA LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID
								  LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID
								  LEFT JOIN _DATA_InWhs ON Data.InWhsID = _DATA_InWhs.InWID
								  LEFT JOIN _DATA_OutWhs ON Data.OutWhsID = _DATA_OutWhs.OutWID
			    ORDER BY ROWID'
			    
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT * FROM PD_AllotReqBill WHERE 1 <> 1'
	--print @sql

	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillCode VARCHAR(50), @DeptID VARCHAR(1000), @ElyID VARCHAR(1000), 
							   @InWhsID INT, @OutWhsID VARCHAR(1000), @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100),
							   @Summary VARCHAR(50), @Description VARCHAR(50), @BillStartDate DATETIME, @BillEndDate DATETIME,
							   @OperatorID INT, @TVP_Dept TVP_Type READONLY, @DlvStartDate DATETIME, @DlvEndDate DATETIME', 
							   @PageNo, @PageSize, @BillCode, @DeptID, @ElyID, @InWhsID, @OutWhsID, @GoodsNo, @GoodsName,
							   @Summary, @Description, @BillStartDate, @BillEndDate, @OperatorID, @TVP_Dept, @DlvStartDate, @DlvEndDate
	 
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AuditBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_AuditBill
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-06-03
	描述：审核单据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_AuditBill]
(
	@BillStepID		INT=0,
	@AuditResult	INT=0,
	@Explain		VARCHAR(MAX) = '',
	@OperatorID		INT = 1,
	@IsAudit		BIT =0	/*0-反审核、1-审核*/
) 
AS

/************************/
--返回值
-- 0   审核/反审核成功。
-- -1  当前审核步骤不存在
-- -2  当前步骤状态为已审核，无法进行普通审核操作
-- -3  当前单据状态不为待审核，无法进行审核操作
-- -4  顺序审批流程下，前面存在待审核的步骤，无法进行审核操作
-- -5  已过账单据不能反审核
-- -6  已确认生效的订单不能反审核
/************************/

DECLARE @AuditingID INT = 0, @Level INT = 0, @BillNo INT = 0, @BillTypeID INT =0, @AuditStatus INT = 0, @Status INT = 0 
DECLARE @SpecElyID INT = 0,  @LevelCount INT = 0, @Type INT = 0, @StepID INT = 0, @IsDraft INT = 0

SELECT @AuditingID = AuditingID, @Level = [Level], @Type = [Type], @StepID = StepID FROM PD_BillAuditStep WHERE ID = @BillStepID
	
SELECT @BillNo = BillNo, @BillTypeID = BillTypeID, @LevelCount = LEN(AuditingLevels) FROM PD_AuditingBill WHERE ID = @AuditingID

IF @IsAudit = 0 --反审核
BEGIN
	IF @BillTypeID = 100
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_PchOrdBill WHERE BillNo = @BillNo
		IF @IsDraft = 0 RETURN -6
		UPDATE PD_PchOrdBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 101
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_PchBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_PchBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 102
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_PchRetBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_PchRetBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 200
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_SellOrdBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -6
		UPDATE PD_SellOrdBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 201
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_SellBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_SellBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 202
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_SellRetBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_SellRetBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 308
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_AllotReqBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -6
		UPDATE PD_AllotReqBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 301 OR @BillTypeID = 309
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_AllotBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_AllotBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 302
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_AdjPriceBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_AdjPriceBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 303 OR @BillTypeID = 304 OR @BillTypeID = 600
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_InOutWhsBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_InOutWhsBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 310
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_AssemblyBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -6
		UPDATE PD_AssemblyBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 305 OR @BillTypeID = 306
	BEGIN
		SELECT @IsDraft = IsDraft FROM PD_LossSpillBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE PD_LossSpillBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 401 OR @BillTypeID = 402
	BEGIN
		SELECT @IsDraft = IsDraft FROM MF_PayRecBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE MF_PayRecBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 403 OR @BillTypeID = 404 OR @BillTypeID = 405
	BEGIN
		SELECT @IsDraft = IsDraft FROM MF_FeeRecBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE MF_FeeRecBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 406
	BEGIN
		SELECT @IsDraft = IsDraft FROM MF_TransferBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE MF_TransferBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE 
	IF @BillTypeID = 501 OR @BillTypeID = 502 OR @BillTypeID = 503 OR @BillTypeID = 504
	BEGIN
		SELECT @IsDraft = IsDraft FROM MF_ARAPBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE MF_ARAPBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END ELSE
	IF @BillTypeID = 602
	BEGIN
		SELECT @IsDraft = IsDraft FROM VS_VipChargeBill WHERE BillNo = @BillNo;
		IF @IsDraft = 0 RETURN -5
		UPDATE VS_VipChargeBill SET AuditStatus = 5 WHERE BillNo = @BillNo
	END
			
	UPDATE PD_BillAuditStep 
		SET		AuditElyID = @OperatorID,
				AuditDate = GETDATE(),
				[Status] = 0,
				Explain = @Explain
		WHERE ID = @BillStepID	 
	
END ELSE
BEGIN  --单据审核
	
	
		
	SELECT @SpecElyID = SpecElyID FROM PD_AuditingBill WHERE ID = @AuditingID
	
	IF @SpecElyID = @OperatorID /*特定审核人审核所有未审核的步骤*/
	BEGIN
	
		IF @BillTypeID = 100
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_PchOrdBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 101
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_PchBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 102
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_PchRetBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 200
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_SellOrdBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 201
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_SellBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 202
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_SellRetBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 308
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_AllotReqBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 301 OR @BillTypeID = 309
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_AllotBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 302
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_AdjPriceBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE 
		IF @BillTypeID = 303 OR @BillTypeID = 304 OR @BillTypeID = 600
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_InOutWhsBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE 
		IF @BillTypeID = 310
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_AssemblyBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE 
		IF @BillTypeID = 305 OR @BillTypeID = 306
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PD_LossSpillBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE 
		IF @BillTypeID = 401 OR @BillTypeID = 402
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM MF_PayRecBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE 
		IF @BillTypeID = 403 OR @BillTypeID = 404 OR @BillTypeID = 405
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM MF_FeeRecBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE 
		IF @BillTypeID = 406
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM MF_TransferBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE 
		IF @BillTypeID = 501 OR @BillTypeID = 502 OR @BillTypeID = 503 OR @BillTypeID = 504
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM MF_ARAPBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END ELSE
		IF @BillTypeID = 602
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM VS_VipChargeBill WHERE BillNo = @BillNo AND AuditStatus = 3)  RETURN -3
		END
		
		
		
		UPDATE PD_BillAuditStep 
		SET		AuditElyID = @OperatorID,
				AuditDate = GETDATE(),
				[Status] = @AuditResult,
				Explain = @Explain
		WHERE AuditingID = @AuditingID AND [Status] = 0
		
	END ELSE
	BEGIN  /*普通审核人，审核当前步骤*/
	
		IF NOT EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE ID = @BillStepID) RETURN -1 --审核步骤不存在
		
		IF EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE ID = @BillStepID AND [Status] <> 0) RETURN -2 --状态为已审核,无需进行审核操作
		
		IF (@Type = 1)  /*当前为步骤属于顺序审批流程，需要判断该步骤之前的所有步骤*/
		BEGIN
			IF EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE AuditingID = @AuditingID AND StepID < @StepID AND [Status] = 0) RETURN -4 
		END ELSE
		BEGIN /*当前步骤为会签审批流程，只需判断该级别之前的所有步骤*/
			IF EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE AuditingID = @AuditingID AND [Level] < @Level AND [Status] = 0) RETURN -4
		END

		UPDATE PD_BillAuditStep 
		SET		AuditElyID = @OperatorID,
				AuditDate = GETDATE(),
				[Status] = @AuditResult,
				Explain = @Explain
		WHERE ID = @BillStepID	
	END
	
	DECLARE @nCount INT = @Level
	WHILE( @nCount <= @LevelCount)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE [Level] = @nCount AND [Status] = 0)
		BEGIN
			IF EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE [Level] = @nCount AND [Status] = 2)
				SET @Status = 2
			ELSE
				SET @Status = 1

			UPDATE PD_AuditingBill SET AuditingLevels = STUFF(AuditingLevels,@nCount,@nCount,@Status) WHERE ID = @AuditingID
		END
		SET @nCount = @nCount + 1
	END
	
	
	
	
	/*全部审核完成，修改审核主表状态和单据审核状态*/
	IF (NOT EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE AuditingID = @AuditingID AND [Status] = 0)) 
		OR (EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE AuditingID = @AuditingID AND [Status] = 2))
	BEGIN
		IF EXISTS(SELECT 1 FROM PD_BillAuditStep WHERE AuditingID = @AuditingID AND [Status] = 2) 
		BEGIN
			SET @AuditStatus = 5  /*审核不通过*/
			SET @Status = 2
		END	ELSE
		BEGIN
			SET @AuditStatus = 4  /*审核通过*/
			SET @Status = 1
		END
		
		UPDATE PD_AuditingBill SET IfAudit = @Status WHERE ID = @AuditingID
		
		IF @BillTypeID = 100
		BEGIN
			UPDATE PD_PchOrdBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 101
		BEGIN
			UPDATE PD_PchBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 102
		BEGIN
			UPDATE PD_PchRetBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 200
		BEGIN
			UPDATE PD_SellOrdBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 201
		BEGIN
			UPDATE PD_SellBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 202
		BEGIN
			UPDATE PD_SellRetBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 308
		BEGIN
			UPDATE PD_AllotReqBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 301 OR @BillTypeID = 309
		BEGIN
			UPDATE PD_AllotBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 302
		BEGIN
			UPDATE PD_AdjPriceBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 303 OR @BillTypeID = 304 OR @BillTypeID = 600
		BEGIN
			UPDATE PD_InOutWhsBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 310
		BEGIN
			UPDATE PD_AssemblyBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 305 OR @BillTypeID = 306
		BEGIN
			UPDATE PD_LossSpillBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 401 OR @BillTypeID = 402
		BEGIN
			UPDATE MF_PayRecBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 403 OR @BillTypeID = 404 OR @BillTypeID = 405
		BEGIN
			UPDATE MF_FeeRecBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 406
		BEGIN
			UPDATE MF_TransferBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE 
		IF @BillTypeID = 501 OR @BillTypeID = 502 OR @BillTypeID = 503 OR @BillTypeID = 504
		BEGIN
			UPDATE MF_ARAPBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END ELSE
		IF @BillTypeID = 602
		BEGIN
			UPDATE VS_VipChargeBill SET AuditStatus = @AuditStatus WHERE BillNo = @BillNo
		END
			
	END
END

RETURN 0

GO





IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AuditBillDetail]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_AuditBillDetail
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-05-29
	描述：审核单据明细信息
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_AuditBillDetail]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BillNo INT = 0,
	@BillTypeID INT = 0,
	@OperatorID INT = 0,
	@IsAudited INT = 0, --0待审核，1-已审核，2-全部查询
	@IsMy BIT = 0
) 
AS

DECLARE @Sql NVARCHAR(MAX)='', @TableSql NVARCHAR(MAX)='', @WhereSql NVARCHAR(MAX) = '', @SpecElyID INT = 0

SELECT @SpecElyID = SpecElyID FROM PD_AuditingBill WHERE BillNo = @BillNo AND BillTypeID = @BillTypeID

IF (@IsMy = 1) AND (@SpecElyID <> @OperatorID)
BEGIN
	SET @TableSql = ' INNER JOIN PD_BillAuditEly BAE ON BAE.AuditStepID = BAS.ID '
	SET @WhereSql = ' AND BAE.ElyID = @OperatorID'
END

IF (@IsAudited = 0) AND (@SpecElyID <> @OperatorID)
BEGIN
	SET @WhereSql += ' AND (
		BAS.[Type] = 1 AND BAS.AuditingID NOT IN(SELECT AuditingID FROM PD_BillAuditStep WHERE AuditingID = BAS.AuditingID AND StepID< BAS.StepID AND Status = 0)
		OR 
		BAS.[Type] = 2 AND BAS.AuditingID NOT IN(SELECT AuditingID FROM PD_BillAuditStep WHERE AuditingID = BAS.AuditingID AND [Level]< BAS.[Level] AND Status = 0)
		) '
END 


IF @IsAudited = 1
BEGIN
	SET @WhereSql += ' AND BAS.AuditElyID <> 0 '
END ELSE
IF @IsAudited = 0
BEGIN
	SET @WhereSql += ' AND BAS.Status = 0 '
END

SET @Sql = '
;WITH PagingData AS 
(
SELECT	BAS.ID AS BillStepID,			
		BAS.AuditDate,				
		SAS.ProjectCode,			
		SAS.ProjectName,			
		CASE BAS.Level WHEN 1 THEN ''一级'' WHEN 2 THEN ''二级'' WHEN 3 THEN ''三级'' WHEN 4 THEN ''四级'' WHEN 1 THEN ''五级'' END AS Level,
		CASE BAS.Type WHEN 1 THEN ''顺序审批'' ELSE ''会签审批'' END AS Type,				
		BAS.Status,			
		BAS.StepReason,					
		ISNULL(BAS.Explain,'''') AS Explain,				
		BAS.StepID,					
		BAS.AuditElyID,		
		ISNULL(E.ElyName, '''') AS AuditElyName,
		CASE BAS.AuditType WHEN 1 THEN ''一人审核即通过'' WHEN 2 THEN ''所有人审核才通过'' END AS AuditType,
		AB.SpecElyID,
		ISNULL(BE.ElyName, '''') AS SpecElyName
	FROM PD_BillAuditStep BAS
	INNER JOIN PD_AuditingBill AB ON AB.ID = BAS.AuditingID
	INNER JOIN SS_AuditSet SAS ON AB.AuditSetID = SAS.ID
	'+ @TableSql +'
	LEFT JOIN BD_Employee E ON BAS.AuditElyID = E.ElyID
	LEFT JOIN BD_Employee BE ON AB.SpecElyID = BE.ElyID
WHERE AB.BillNo = @BillNo AND AB.BillTypeID = @BillTypeID '+ @WhereSql +'
)
'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillNo','INT', @BillNo)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillTypeID','INT', @BillTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT', @OperatorID)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, 'Level','BillStepID','ROWID ASC',1,1

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AuditBillList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_AuditBillList
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-05-29
	描述：审核单据列表(待审核/已审核)
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_AuditBillList]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(MAX)='',
	@DeptID VARCHAR(MAX)='',
	@ElyID VARCHAR(MAX)='',
	@CreatorID VARCHAR(MAX)='',
	@BillCode VARCHAR(50) = '',
	@BillCodeMatch BIT = 0,
	@Summary VARCHAR(256)='',
	@SummaryMatch BIT = 0,
	@Description VARCHAR(100)='',
	@DescriptionMatch BIT = 0,
	@IsAudited BIT = 0,
	@OperatorID INT = 1
) 
AS

DECLARE @Sql NVARCHAR(MAX) = '', @IndexSql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = '', @KBIndexSql NVARCHAR(MAX)= ''
DECLARE @BillTypeSql NVARCHAR(MAX) = '',@TableSql NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = '', @NoLimitSql NVARCHAR(MAX) = ''
DECLARE @BtypeLimitSql NVARCHAR(MAX) = '', @KtypeLimitSql NVARCHAR(MAX) = '', @MulKtypeLimitSql NVARCHAR(MAX) = ''
DECLARE @KIndexSql NVARCHAR(MAX) = '', @BIndexSql NVARCHAR(MAX) = ''

DECLARE @PchBill NVARCHAR(MAX) = '', @PchOrderBill NVARCHAR(MAX) = '', @PchRetBill NVARCHAR(MAX) = ''
DECLARE @SellBill NVARCHAR(MAX) = '', @SellOrderBill NVARCHAR(MAX) = '', @SellRetBill NVARCHAR(MAX) = ''
DECLARE @AllotReqBill NVARCHAR(MAX) = '', @AllotBill NVARCHAR(MAX) = '', @AdjPriceBill NVARCHAR(MAX) = ''
DECLARE @InOutWhsBill NVARCHAR(MAX) = '', @AssemblyBill NVARCHAR(MAX) = '', @LossSpillBill NVARCHAR(MAX) = ''
DECLARE @PayRecBill NVARCHAR(MAX) = '', @FeeRecBill NVARCHAR(MAX) = '', @TransferBill NVARCHAR(MAX) = '' 
DECLARE @VipChargeBill NVARCHAR(MAX) = ''


SET @IndexSql = ' WHERE I.BillDate BETWEEN @BeginDate AND @EndDate '

IF (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0) OR (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0)  
BEGIN
	SET @KBIndexSql = ' AND 1=2'
END

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0
BEGIN
	SET @BIndexSql = ' AND 1=2'
END

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0
BEGIN
	SET @KIndexSql = ' AND 1=2'
END

IF @IsAudited = 0
BEGIN
	SET @CreateTableSql += ' DECLARE @AuditStep Table (BillNo INT, BillTypeID INT)
	INSERT  INTO @AuditStep 
	SELECT BillNo, BillTypeID FROM PD_BillAuditStep BAS 
		INNER JOIN PD_AuditingBill AB ON BAS.AuditingID = AB.ID 
		INNER JOIN PD_BillAuditEly BAE ON BAS.ID = BAE.AuditStepID
		WHERE BAE.ElyID = @OperatorID AND BAS.Status = 0 AND
		( 
		BAS.[Type] = 1 AND BAS.AuditingID NOT IN(SELECT AuditingID FROM PD_BillAuditStep WHERE AuditingID = BAS.AuditingID AND StepID< BAS.StepID AND Status = 0)
		OR 
		BAS.[Type] = 2 AND BAS.AuditingID NOT IN(SELECT AuditingID FROM PD_BillAuditStep WHERE AuditingID = BAS.AuditingID AND [Level]< BAS.[Level] AND Status = 0)
		)
	UNION ALL
	SELECT BillNo, BillTypeID FROM PD_AuditingBill WHERE SpecElyID = @OperatorID
	'
	SET @TableSql += ' INNER JOIN @AuditStep S ON I.BillNo = S.BillNo'
	SET @IndexSql += ' AND AuditStatus = 3'
END ELSE
BEGIN
SET @CreateTableSql += ' DECLARE @AuditStep Table (BillNo INT, BillTypeID INT)
	INSERT  INTO @AuditStep SELECT DISTINCT BillNo, BillTypeID FROM PD_BillAuditStep BAS 
						INNER JOIN PD_AuditingBill AB ON BAS.AuditingID = AB.ID
						WHERE BAS.AuditElyID = @OperatorID AND BAS.Status <> 0'
	SET @TableSql += ' INNER JOIN @AuditStep S ON I.BillNo = S.BillNo'
	SET @IndexSql += ' AND AuditStatus IN (3, 4, 5)'
END

IF @BillTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BillType Table(BillTypeID INT)   
     INSERT  INTO @BillType SELECT typeid AS BillTypeID  FROM dbo.UF_OT_Split_Int(@BillTypeID,'','')   
     '  
	SET @BillTypeSql+=' INNER JOIN @BillType BT ON PR.BillTypeID=BT.BillTypeID '   
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
	SET @TableSql+=' INNER JOIN @DType D ON I.DeptID=D.DeptID '  
END

IF @ElyID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '      
END

IF @CreatorID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @Creator Table(CreatorID INT)   
     INSERT  INTO @Creator SELECT typeid AS CreatorID  FROM dbo.UF_OT_Split_Int(@CreatorID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @Creator C ON I.Creator = C.CreatorID '      
END

SET @NoLimitSql = @TableSql

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
BEGIN
	SET @MulKtypeLimitSql = ' 
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) inkl ON inkl.WhsID =I.InWhsID
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) outkl ON outkl.WhsID =I.OutWhsID
	'
	SET @KtypeLimitSql = ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =I.WhsID'
	
	SET @TableSql += @KtypeLimitSql
END
	
	
IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
BEGIN
	SET @BtypeLimitSql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID'
	
	SET @TableSql += @BtypeLimitSql
END
	



IF @BillCode <> ''
BEGIN
	IF @BillCodeMatch = 1 
		SET @IndexSql += ' AND BillCode = @BillCode '
	ELSE
		SET @IndexSql += ' AND BillCode Like ''%''+@BillCode+''%'' ' 
END

IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 1 
		SET @IndexSql += ' AND Summary = @Summary '
	ELSE
		SET @IndexSql += ' AND Summary Like ''%''+@Summary+''%'' ' 
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 1 
		SET @IndexSql += ' AND Description = @Description '
	ELSE
		SET @IndexSql += ' AND Description Like ''%''+@Description+''%'' ' 
END


SET @KIndexSql += @IndexSql;
SET @BIndexSql += @IndexSql;
SET @KBIndexSql += @IndexSql;

--采购订单
SET @PchOrderBill = '
SELECT	100 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime, 
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_PchOrdBill I '+ @TableSql +@KBIndexSql +' AND S.BillTypeID = 100'

--采购入库单
SET @PchBill = '
SELECT	101 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_PchBill I '+ @TableSql +@KBIndexSql +' AND S.BillTypeID = 101'

--采购退货单
SET @PchRetBill = '
SELECT	102 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_PchRetBill I '+ @TableSql +@KBIndexSql +' AND S.BillTypeID = 102'


--销售订单
SET @SellOrderBill = '
SELECT	200 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime, 
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_SellOrdBill I '+ @TableSql +@KBIndexSql +' AND S.BillTypeID = 200'

--销售出库单
SET @SellBill = '
SELECT	201 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_SellBill I '+ @TableSql +@KBIndexSql +' AND S.BillTypeID = 201'

--销售退货单
SET @SellRetBill = '
SELECT	202 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_SellRetBill I '+ @TableSql +@KBIndexSql +' AND S.BillTypeID = 202'

--调拨申请单
SET @AllotReqBill = '
SELECT	308 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_AllotReqBill I '+ @NoLimitSql + @MulKtypeLimitSql + @KIndexSql +' AND S.BillTypeID = 308'

--同价/变价调拨单
SET @AllotBill = '
SELECT	I.BillTypeID,		BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,	I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_AllotBill I '+ @NoLimitSql + @MulKtypeLimitSql +@KIndexSql +' AND S.BillTypeID = I.BillTypeID'

--调价单
SET @AdjPriceBill = '
SELECT	302 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_AdjPriceBill I '+ @NoLimitSql + @KtypeLimitSql + @KIndexSql +' AND S.BillTypeID = 302'

--其他出/入库单
SET @InOutWhsBill = '
SELECT	I.BillTypeID,		BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_InOutWhsBill I '+ @TableSql +@KBIndexSql +' AND S.BillTypeID = I.BillTypeID'


--生产拆装单
SET @AssemblyBill = '
SELECT	310 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_AssemblyBill I '+ @NoLimitSql + @MulKtypeLimitSql +@KIndexSql +' AND S.BillTypeID = 310'

--报损报溢单
SET @LossSpillBill = '
SELECT	I.BillTypeID,				BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM PD_LossSpillBill I '+ @NoLimitSql + @KtypeLimitSql +@KIndexSql +' AND S.BillTypeID = I.BillTypeID'

--收付款单
SET @PayRecBill = '
SELECT	I.BillTypeID,		BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM MF_PayRecBill I '+ @NoLimitSql + @BtypeLimitSql +@BIndexSql +' AND S.BillTypeID = I.BillTypeID'

--现金费用单,一般费用单,其他收入单
SET @FeeRecBill = '
SELECT	I.BillTypeID,		BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM MF_FeeRecBill I '+ @NoLimitSql + @BtypeLimitSql +@BIndexSql +' AND S.BillTypeID = I.BillTypeID'

--转款单
SET @TransferBill = '
SELECT	406 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM MF_TransferBill I '+ @NoLimitSql +@IndexSql +' AND S.BillTypeID = 406'

--应收应付
SET @ARAPBill = '
SELECT	I.BillTypeID,		BillCode,		BillDate,		Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,		I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM MF_ARAPBill I '+ @NoLimitSql + @BtypeLimitSql +@BIndexSql +' AND S.BillTypeID = I.BillTypeID'

--会员充值单
SET @VipChargeBill = '
SELECT 602 AS BillTypeID,	BillCode,		BillDate,		Summary,			Description,
		'''' AS BTypeID,	I.DeptID,		I.ElyID,		I.BillNo,		    CreateTime,
		CASE I.AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus
FROM VS_VipChargeBill I'+ @NoLimitSql + @IndexSql +' AND S.BillTypeID = 602'


SET @Sql = @CreateTableSql+'
;WITH PagingData AS 
(
SELECT	PR.BillTypeID,	PBT.BillName,	PR.BillCode,	BillDate,		Summary,		Description,	
		PR.BTypeID,		B.BTypeCode,	B.BTypeName,	PR.DeptID,		D.DeptCode,		D.DeptName,		
		PR.ElyID,		E.ElyCode,		E.ElyName,		BillNo,			CreateTime,		AuditStatus
	FROM(
	'+ @PchBill+'
	UNION ALL
	'+ @PchOrderBill+'
	UNION ALL
	'+@PchRetBill+'
	UNION ALL
	'+@SellBill+'
	UNION ALL
	'+@SellOrderBill+'
	UNION ALL
	'+@SellRetBill+'
	UNION ALL
	'+@AllotReqBill+'
	UNION ALL
	'+@AllotBill+'
	UNION ALL
	'+@AdjPriceBill+'
	UNION ALL
	'+@InOutWhsBill+'
	UNION ALL
	'+@AssemblyBill+'
	UNION ALL
	'+@LossSpillBill+'
	UNION ALL
	'+@PayRecBill+'
	UNION ALL
	'+@FeeRecBill+'
	UNION ALL
	'+@TransferBill+'
	UNION ALL
	'+@VipChargeBill+'
	UNION ALL
	'+@ARAPBill+'
	) PR
	LEFT JOIN BD_Btype B ON PR.BTypeID = B.BTypeID
	LEFT JOIN BD_Employee E ON PR.ElyID = E.ElyID
	LEFT JOIN BD_Dept D ON PR.DeptID = D.DeptID
	INNER JOIN PD_BillType PBT ON PR.BillTypeID = PBT.BillTypeID
	'+ @BillTypeSql + ')'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate','DATE', @BeginDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate','DATE', @EndDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillTypeID','VARCHAR(MAX)',@BillTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID','VARCHAR(MAX)',@DeptID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ElyID','VARCHAR(MAX)',@ElyID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@CreatorID','VARCHAR(MAX)',@CreatorID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillCode','VARCHAR(50)',@BillCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Summary','VARCHAR(256)',@Summary)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Description','VARCHAR(100)',@Description)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, 'CreateTime','','ROWID ASC',1,1



GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AuditBillQuery]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_AuditBillQuery
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-06-02
	描述：审核单据查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_AuditBillQuery]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(MAX)='',
	@BTypeID VARCHAR(MAX)='',
	@WhsID VARCHAR(MAX) = '',
	@DeptID VARCHAR(MAX)='',
	@ElyID VARCHAR(MAX)='',
	@CreatorID VARCHAR(MAX)='',
	@SignerID VARCHAR(MAX)= '',
	@SignStatus VARCHAR(20) = '',
	@BillCode VARCHAR(50) = '',
	@BillCodeMatch BIT = 0,
	@Summary VARCHAR(256)='',
	@SummaryMatch BIT = 0,
	@Description VARCHAR(100)='',
	@DescriptionMatch BIT = 0,
	@OperatorID INT = 1
) 
AS

DECLARE @Sql NVARCHAR(MAX) = '', @IndexSql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = ''
DECLARE @InnerTableSql NVARCHAR(MAX) = '',@TableSql NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = ''
DECLARE @BtypeSql NVARCHAR(MAX) = '', @KtypeSql NVARCHAR(MAX) = '', @MulKtypeSql NVARCHAR(MAX) = ''
DECLARE @NoKBSql NVARCHAR(MAX) = '', @NKtypeIndexSql NVARCHAR(MAX) = '', @NBtypeIndexSql NVARCHAR(MAX) = ''
DECLARE @KtypeIndexSql NVARCHAR(MAX) = '', @BtypeIndexSql NVARCHAR(MAX) = ''

DECLARE @PchBill NVARCHAR(MAX) = '', @PchOrderBill NVARCHAR(MAX) = '', @PchRetBill NVARCHAR(MAX) = ''
DECLARE @SellBill NVARCHAR(MAX) = '', @SellOrderBill NVARCHAR(MAX) = '', @SellRetBill NVARCHAR(MAX) = ''
DECLARE @AllotReqBill NVARCHAR(MAX) = '', @AllotBill NVARCHAR(MAX) = '', @AdjPriceBill NVARCHAR(MAX) = ''
DECLARE @InOutWhsBill NVARCHAR(MAX) = '', @AssemblyBill NVARCHAR(MAX) = '', @LossSpillBill NVARCHAR(MAX) = ''
DECLARE @PayRecBill NVARCHAR(MAX) = '', @FeeRecBill NVARCHAR(MAX) = '', @TransferBill NVARCHAR(MAX) = ''
DECLARE @VipChargeBill NVARCHAR(MAX) = ''

--单据日期条件
SET @IndexSql = ' WHERE I.BillDate BETWEEN @BeginDate AND @EndDate '

--审核状态条件（审核中，审核通过，审核未通过）
SET @IndexSql += ' AND AuditStatus IN (3, 4, 5) '

IF @BillTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BillType Table(BillTypeID INT)   
     INSERT  INTO @BillType SELECT typeid AS BillTypeID  FROM dbo.UF_OT_Split_Int(@BillTypeID,'','')   
     '  
	SET @InnerTableSql+=' INNER JOIN @BillType BT ON PR.BillTypeID=BT.BillTypeID '   
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
	SET @TableSql+=' INNER JOIN @DType D ON I.DeptID=D.DeptID '  
END

IF @ElyID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '      
END

IF @CreatorID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @Creator Table(CreatorID INT)   
     INSERT  INTO @Creator SELECT typeid AS CreatorID  FROM dbo.UF_OT_Split_Int(@CreatorID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @Creator C ON I.Creator = C.CreatorID '      
END


SET @NoKBSql = @TableSql

IF @BTypeID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     
     SET @BtypeSql += ' INNER JOIN @BType B ON I.BTypeID=B.BTypeID '
	 SET @NBtypeIndexSql = ' AND 1=2 '
END

IF @WhsID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @Whs Table(WhsID INT)   
     INSERT  INTO @Whs SELECT typeid AS WhsID  FROM dbo.UF_OT_Split_Int(@WhsID,'','')   
     '
     
     SET @KtypeSql += ' INNER JOIN @Whs K ON I.WhsID=K.WhsID '
     SET @MulKtypeSql += ' INNER JOIN @Whs K ON (I.InWhsID=K.WhsID OR I.OutWhsID = K.WhsID)'
     SET @NKtypeIndexSql = ' AND 1=2 '
END

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0
BEGIN
	SET @BtypeIndexSql = ' AND 1=2 '
END

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0
BEGIN
	SET @KtypeIndexSql = ' AND 1=2'
END

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
BEGIN
	SET @MulKtypeSql += ' 
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) inkl ON inkl.WhsID =I.InWhsID
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) outkl ON outkl.WhsID =I.OutWhsID
	'
	SET @KtypeSql += ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =I.WhsID'
END
	
	
IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
BEGIN
	SET @BtypeSql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID'
	
END

SET @TableSql += @BtypeSql + @KtypeSql

IF @SignerID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @Signer Table(SignElyID INT)   
     INSERT  INTO @Signer SELECT typeid AS SignElyID  FROM dbo.UF_OT_Split_Int(@SignerID,'','')   
     '  
	SET @InnerTableSql +=' INNER JOIN @Signer S ON PR.SignElyID = S.SignElyID '      
END

IF @BillCode <> ''
BEGIN
	IF @BillCodeMatch = 1 
		SET @IndexSql += ' AND BillCode = @BillCode '
	ELSE
		SET @IndexSql += ' AND BillCode Like ''%''+@BillCode+''%'' ' 
END

IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 1 
		SET @IndexSql += ' AND Summary = @Summary '
	ELSE
		SET @IndexSql += ' AND Summary Like ''%''+@Summary+''%'' ' 
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 1 
		SET @IndexSql += ' AND Description = @Description '
	ELSE
		SET @IndexSql += ' AND Description Like ''%''+@Description+''%'' ' 
END

IF @SignStatus <> ''
BEGIN
	SET @IndexSql += ' AND AB.SignStatus IN ( '+@SignStatus+' )'
END

--采购订单
SET @PchOrderBill = '
SELECT	100 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_PchOrdBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @TableSql +@IndexSql + @BtypeIndexSql + @KtypeIndexSql + ' AND AB.BillTypeID = 100 '  

--采购入库单
SET @PchBill = '
SELECT	101 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_PchBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo  
'+ @TableSql +@IndexSql  + @BtypeIndexSql + @KtypeIndexSql + ' AND AB.BillTypeID = 101 '

--采购退货单
SET @PchRetBill = '
SELECT	102 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_PchRetBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo  
'+ @TableSql +@IndexSql + @BtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = 102'


--销售订单
SET @SellOrderBill = '
SELECT	200 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_SellOrdBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @TableSql +@IndexSql + @BtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = 200'

--销售出库单
SET @SellBill = '
SELECT	201 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_SellBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo  
'+ @TableSql +@IndexSql  +  @BtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = 201 '

--销售退货单
SET @SellRetBill = '
SELECT	202 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_SellRetBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo  
'+ @TableSql +@IndexSql + @BtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = 202'

--调拨申请单
SET @AllotReqBill = '
SELECT	308 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_AllotReqBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @MulKtypeSql +@IndexSql + @NBtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = 308'

--同价/变价调拨单
SET @AllotBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_AllotBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @MulKtypeSql +@IndexSql + @NBtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = I.BillTypeID'

--调价单
SET @AdjPriceBill = '
SELECT	302 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_AdjPriceBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @KtypeSql +@IndexSql + @NBtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = 302'

--其他出/入库单
SET @InOutWhsBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_InOutWhsBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+@TableSql +@IndexSql + @BtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = I.BillTypeID'


--生产拆装单
SET @AssemblyBill = '
SELECT	310 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_AssemblyBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @MulKtypeSql  +@IndexSql + @NBtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = 310'

--报损报溢单
SET @LossSpillBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM PD_LossSpillBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @KtypeSql +@IndexSql + @NBtypeIndexSql + @KtypeIndexSql +' AND AB.BillTypeID = I.BillTypeID'

--收付款单
SET @PayRecBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM MF_PayRecBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @BtypeSql +@IndexSql + @NKtypeIndexSql + @BtypeIndexSql + ' AND AB.BillTypeID = I.BillTypeID'

--现金费用单,一般费用单,其他收入单
SET @FeeRecBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM MF_FeeRecBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @BtypeSql +@IndexSql + @NKtypeIndexSql + @BtypeIndexSql +' AND AB.BillTypeID = I.BillTypeID'

--转款单
SET @TransferBill = '
SELECT	406 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM MF_TransferBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql +@IndexSql + @NKtypeIndexSql + @NBtypeIndexSql + ' AND AB.BillTypeID = 406'

--应收应付
SET @ARAPBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM MF_ARAPBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql + @BtypeSql +@IndexSql + @NKtypeIndexSql + @BtypeIndexSql +' AND AB.BillTypeID = I.BillTypeID'

--会员充值单
SET @VipChargeBill = '
SELECT	602 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		CASE AuditStatus WHEN 3 THEN ''审核中'' WHEN 4 THEN ''审核通过'' WHEN 5 THEN ''审核不通过'' END AS AuditStatus,
		CASE AB.SignElyID WHEN 999999 THEN I.Creator ELSE AB.SignElyID END AS SignElyID,
		CASE AB.SignStatus WHEN 0 THEN ''未签收'' WHEN 1 THEN ''已签收'' WHEN 2 THEN ''无需签收'' END AS SignStatus
FROM VS_VipChargeBill I  INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo 
'+ @NoKBSql +@IndexSql + @NKtypeIndexSql + @NBtypeIndexSql + ' AND AB.BillTypeID = 602'


SET @Sql = @CreateTableSql+'
;WITH PagingData AS 
(
SELECT	PR.BillTypeID,	PBT.BillName,	PR.BillCode,	BillDate,		Summary,		Description,	
		PR.BTypeID,		B.BTypeCode,	B.BTypeName,	PR.DeptID,		D.DeptCode,		D.DeptName,		
		PR.ElyID,		E.ElyCode,		E.ElyName,		BillNo,			CreateTime,		AuditStatus,
		PR.SignElyID,		BE.ElyCode AS SignElyCode,		BE.ElyName AS SignElyName,		SignStatus
	FROM(
	'+ @PchBill+'
	UNION ALL
	'+ @PchOrderBill+'
	UNION ALL
	'+@PchRetBill+'
	UNION ALL
	'+@SellBill+'
	UNION ALL
	'+@SellOrderBill+'
	UNION ALL
	'+@SellRetBill+'
	UNION ALL
	'+@AllotReqBill+'
	UNION ALL
	'+@AllotBill+'
	UNION ALL
	'+@AdjPriceBill+'
	UNION ALL
	'+@InOutWhsBill+'
	UNION ALL
	'+@AssemblyBill+'
	UNION ALL
	'+@LossSpillBill+'
	UNION ALL
	'+@PayRecBill+'
	UNION ALL
	'+@FeeRecBill+'
	UNION ALL
	'+@TransferBill+'
	UNION ALL
	'+@VipChargeBill+'
	UNION ALL
	'+@ARAPBill+'
	) PR
	LEFT JOIN BD_Btype B ON PR.BTypeID = B.BTypeID
	LEFT JOIN BD_Employee E ON PR.ElyID = E.ElyID
	LEFT JOIN BD_Employee BE ON PR.SignElyID = BE.ElyID
	LEFT JOIN BD_Dept D ON PR.DeptID = D.DeptID
	INNER JOIN PD_BillType PBT ON PR.BillTypeID = PBT.BillTypeID
	'+ @InnerTableSql + ')'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate','DATE', @BeginDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate','DATE', @EndDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillTypeID','VARCHAR(MAX)',@BillTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BTypeID','VARCHAR(MAX)',@BTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID','VARCHAR(MAX)',@DeptID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ElyID','VARCHAR(MAX)',@ElyID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@WhsID','VARCHAR(MAX)',@WhsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@CreatorID','VARCHAR(MAX)',@CreatorID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SignerID','VARCHAR(MAX)',@SignerID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillCode','VARCHAR(50)',@BillCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Summary','VARCHAR(256)',@Summary)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Description','VARCHAR(100)',@Description)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@SignStatus','VARCHAR(20)',@SignStatus)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, 'CreateTime','','ROWID ASC',1,1



GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_AuditInvoice]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_AuditInvoice
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-02-28
	描述：【审核/反审核】发票
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_AuditInvoice]
(
	@BillNo DECIMAL(18,0) = 0,
	@BillTypeID INT, --(507-采购发票,508-销售发票)
	@Mode INT --操作类型(1-审核,0-反审核)
) 
AS

DECLARE @Sql NVARCHAR(MAX) = '',@DetailTable NVARCHAR(MAX) = '', @BillTable NVARCHAR(MAX) = '', @RetBillTable NVARCHAR(MAX) = ''
DECLARE @InvoiceMode INT, @BillType NVARCHAR(50), @RetBillType NVARCHAR(50), @NoCol NVARCHAR(100) = '',@IndexTable NVARCHAR(MAX) = ''

IF @BillTypeID = 507--采购发票
BEGIN
	SELECT @BillTable = ' PD_PchBill ',@RetBillTable = ' PD_PchRetBill'
	SELECT @BillType = ' 101 ', @RetBillType = ' 102 '
	SELECT @InvoiceMode = InvoiceMode FROM MF_PchInvoiceBill WHERE BillNo = @BillNo
	SELECT @DetailTable = ' MF_PchInvoiceDetail ',@NoCol = 'PchBillNo', @IndexTable = ' MF_PchInvoiceBill '
END ELSE
IF @BillTypeID = 508 --销售发票
BEGIN
	SELECT @BillTable = ' PD_SellBill ', @RetBillTable = ' PD_SellRetBill '
	SELECT @BillType = ' 201 ', @RetBillType = ' 202 '
	SELECT @InvoiceMode = InvoiceMode FROM MF_SellInvoiceBill WHERE BillNo = @BillNo
	SELECT @DetailTable = ' MF_SellInvoiceDetail ',@NoCol = 'SellBillNo', @IndexTable = ' MF_SellInvoiceBill '
END

IF @Mode = 0 --反审核发票
BEGIN
	SET @Sql = '
		UPDATE '+@BillTable +'
		SET InvoiceMode = CASE InvoiceTotal - YInvoiceTotal WHEN 0 THEN 0 ELSE InvoiceMode END,
			InvoiceTotal = InvoiceTotal - YInvoiceTotal 
		FROM
		(
			SELECT '+@NoCol+' , SUM(InvoiceTotal) AS YInvoiceTotal FROM '+@DetailTable+' WHERE BillNo = @BillNo AND BillType ='+@BillType+'
			GROUP BY '+@NoCol+' 
		) Invoice
		INNER JOIN '+@BillTable +' SB ON SB.BillNo = Invoice.'+@NoCol+'
		
		UPDATE '+@RetBillTable+'
		SET InvoiceMode = CASE InvoiceTotal - YInvoiceTotal WHEN 0 THEN 0 ELSE InvoiceMode END,
			InvoiceTotal = InvoiceTotal - YInvoiceTotal 
		FROM
		(
			SELECT '+@NoCol+' , SUM(InvoiceTotal) AS YInvoiceTotal FROM '+@DetailTable+' WHERE BillNo = @BillNo AND BillType ='+@RetBillType+'
			GROUP BY '+@NoCol+' 
		) Invoice
		INNER JOIN '+@RetBillTable +' SB ON SB.BillNo = Invoice.'+@NoCol+'
		
		UPDATE ' + @IndexTable +' SET IsDraft = 1 WHERE BillNo = @BillNo
	'
	
END ELSE
BEGIN --审核发票
	
	SET @Sql = '
		UPDATE '+@BillTable +'
		SET InvoiceMode = '+ CONVERT(NVARCHAR(50),@InvoiceMode) +',
			InvoiceTotal = InvoiceTotal + YInvoiceTotal
		FROM
		(
			SELECT '+@NoCol+' , SUM(InvoiceTotal) AS YInvoiceTotal FROM '+@DetailTable+' WHERE BillNo = @BillNo AND BillType ='+@BillType+'
			GROUP BY '+@NoCol+' 
		) Invoice
		INNER JOIN '+@BillTable +' SB ON SB.BillNo = Invoice.'+@NoCol+' 
		
		UPDATE '+@RetBillTable+'
		SET InvoiceMode = '+ CONVERT(NVARCHAR(50),@InvoiceMode) +',
			InvoiceTotal = InvoiceTotal + YInvoiceTotal
		FROM
		(
			SELECT '+@NoCol+' , SUM(InvoiceTotal) AS YInvoiceTotal FROM '+@DetailTable+' WHERE BillNo = @BillNo AND BillType ='+@RetBillType+'
			GROUP BY '+@NoCol+' 
		) Invoice
		INNER JOIN '+@RetBillTable +' SB ON SB.BillNo = Invoice.'+@NoCol+' 
		
		UPDATE ' + @IndexTable +' SET IsDraft = 0 WHERE BillNo = @BillNo
	'
END

--PRINT(@sql)
exec sp_executesql @Sql , N'@BillNo INT', @BillNo




GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_BarCodeVerifyDetailQuery]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_BarCodeVerifyDetailQuery
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：Hlin
	日期：2015-09-24
	描述：条码验证明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_BarCodeVerifyDetailQuery]
(
	@BillNo INT,
	@BillTypeID INT
) 
AS

DECLARE @Sql NVARCHAR(MAX) = ''


SELECT @Sql = '
	SELECT	DID,
			G.GoodsName,
			G.GoodsNo,
			P.Unit,
			D.BarCode,
			Qty,
			VerifyQty,
			Qty-VerifyQty 
			DiffQty,
			Case WHEN Qty-VerifyQty=0 THEN ''√'' ELSE ''×'' END VerifyStatus
	FROM	'+BillDetail+' D
	INNER JOIN BD_Goods G On D.GoodsID=G.GoodsID
	INNER JOIN BD_Goods_Price P ON P.GoodsID=D.GoodsID AND P.UnitID=D.UnitID
	WHERE D.BillNo=@BillNo '
FROM dbo.PD_BillType
WHERE BillTypeID=@BillTypeID

EXEC sp_executesql @sql,N'@BillNo INT ',@BillNO

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_BarCodeVerifyListQuery]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_BarCodeVerifyListQuery
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：Hlin
	日期：2015-09-24
	描述：条码验证主表
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_BarCodeVerifyListQuery]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BillStartDate DATETIME,
	@BillEndDate DATETIME,
	@BillCode VARCHAR(50),--单据编号
	@BTypeID INT,
	@WhsID INT,
	@BillTypeID INT,
	@InWhsID INT,
	@OutWhsID INT,
	@VerifyStatus INT,
	@OperatorID INT
) 
AS

DECLARE @Sql NVARCHAR(MAX) = '',@JoinStr VARCHAR(max)=''

IF @BillTypeID NOT IN(301,309)
BEGIN
SET @JoinStr='	INNER JOIN dbo.BD_Btype b ON b.BTypeID=i.BTypeID '
IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID)<>2
	SET @JoinStr+=' inner join dbo.UF_BD_BtypeLimit(@OperatorID) b2 ON b2.BTypeID=i.BTypeID'	
IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID)<>2
	SET @JoinStr += ' inner join UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =I.WhsID '
END
ELSE IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID)<>2
BEGIN
	SET @JoinStr += ' inner join UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =I.InWhsID
					     inner join UF_BD_KtypeLimit(@OperatorID) k2 ON k2.WhsID =I.OutWhsID'
END

SELECT @Sql = '
WITH PagingData AS 
(
	SELECT '''+BillName+''' BillName,'+CAST(BillTypeID AS VARCHAR)+' BillTypeID,BillNo,BillCode,BillDate,'+CASE WHEN @BillTypeID NOT IN(301,309) THEN 'b.BTypeName' ELSE '''''' END+' BTypeName,
	e.ElyName,E2.ElyName AS VerifyElyName,E2.ElyID VerifyElyID,VerifyDate, 
	CASE WHEN NOT EXISTS(SELECT 1 FROM  '+BillDetail+' d WHERE Qty-VerifyQty<>0 AND d.BillNo=I.BillNO) THEN 3
		WHEN EXISTS(SELECT 1 FROM  '+BillDetail+' d WHERE VerifyQty>0 AND d.BillNo=I.BillNO) THEN 2
		ELSE 1 END VerifyStatus 
	FROM '+BillTable+' I
	'+@JoinStr+'
	INNER JOIN dbo.BD_Employee e ON I.ElyID = e.ElyID	
	LEFT JOIN BD_Employee E2 ON I.VerifyElyID = e2.ElyID
	WHERE I.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft=1 '
+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
+CASE WHEN @VerifyStatus=0 THEN ''
	  WHEN @VerifyStatus=2 THEN ' AND EXISTS(SELECT 1 FROM  '+BillDetail+' d WHERE Qty-VerifyQty<>0 AND d.BillNo=I.BillNO) AND EXISTS(SELECT 1 FROM  '+BillDetail+' d WHERE VerifyQty<>0 AND d.BillNo=I.BillNO) '
	  WHEN @VerifyStatus=3 THEN ' AND NOT EXISTS(SELECT 1 FROM  '+BillDetail+' d WHERE Qty-VerifyQty<>0 AND d.BillNo=I.BillNO) '
	  WHEN @VerifyStatus=1 THEN ' AND NOT EXISTS(SELECT 1 FROM  '+BillDetail+' d WHERE VerifyQty<>0 AND d.BillNo=I.BillNO) ' END
		
FROM dbo.PD_BillType
WHERE BillTypeID=@BillTypeID

IF @BillCode <> ''
BEGIN
	SET @Sql += ' AND I.BillCode LIKE ''%''+@BillCode+''%''  '
END

IF @BTypeID <> 0 AND @BillTypeID NOT IN(301,309)
BEGIN
	SET @Sql += ' AND I.BTypeID=@BTypeID '
END

IF @BillTypeID NOT IN(301,309)
BEGIN
	IF @WhsID<>0
		SET @Sql += ' AND I.WhsID=@WhsID '
END
ELSE
BEGIN
	IF @InWhsID<>0
		SET @Sql += ' AND I.InWhsID=@InWhsID '
	IF @OutWhsID<>0
		SET @Sql += ' AND I.OutWhsID=@OutWhsID '
END
	
SET @Sql += ' ) '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillStartDate','DATE', @BillStartDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillEndDate','DATE', @BillEndDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillCode','VARCHAR(50)',@BillCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BTypeID','INT',@BTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@WhsID','INT',@WhsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@InWhsID','INT',@InWhsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OutWhsID','INT',@OutWhsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, 'BillDate DESC','','BillDate DESC',1,1

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
	作者：谢吉康
	日期：2020-2-9
	描述：批量过账
*/


CREATE PROCEDURE UP_PD_BatchPassBill
(
	@OperatorId			VARCHAR(50),		-- 当前操作员ID
	@BillNo				NUMERIC(18,0),		-- 单据ID
	@BillType			INT					-- 单据类型
	
)
--@encode$--
AS
SET NOCOUNT ON


--数据检查,过账前
DECLARE @nRet INT,@GoodsID VARCHAR(20)
EXEC @nRet=Gp_PD_CheckBatchPassBillData @OperatorId,@BillType,@BillNo,@GoodsID OUTPUT
IF @nRet<>0 
	RETURN @nRet

--获取基础数据
DECLARE @VipCardID			INT,
		@VipChangeTotal		NUMERIC(24,10),	--变动金额
		@VipChangeCent		NUMERIC(24,10),	--变动积分
		@FreightTotal		NUMERIC(24,10),		
		@Freight			NUMERIC(24,10),
		@SQL				VARCHAR(MAX),
		@nSQL				NVARCHAR(MAX),
		@IndexTable			VARCHAR(100),	--单据主表
		@detailTable		VARCHAR(100),	--单据明细表
		@serialTable		VARCHAR(100),	--序列号表
		@FreightFinanceID	INT 

SET @VipCardID = 0
SET @VipChangeTotal = 0
SET @VipChangeCent = 0
SET @FreightFinanceID = 0

--应收应付科目
DECLARE @AR_ID INT = 0;				--应收ID
DECLARE @AP_ID INT = 0;				--应付ID
DECLARE @BR_ID INT = 0;				--预收ID
DECLARE @BP_ID INT = 0;				--预付ID
DECLARE @Goods_ID INT = 0;			--库存项目
DECLARE @BuyBackDiff_ID INT = 0;	--进货退货差价

SELECT @AR_ID = FinanceID FROM dbo.BD_Finance WHERE FinanceNO IN('1131')
SELECT @AP_ID = FinanceID FROM dbo.BD_Finance WHERE FinanceNO IN('2121')
SELECT @BR_ID = FinanceID FROM dbo.BD_Finance WHERE FinanceNO IN('2131')
SELECT @BP_ID = FinanceID FROM dbo.BD_Finance WHERE FinanceNO IN('1151')
SELECT @Goods_ID = FinanceID FROM dbo.BD_Finance WHERE FinanceNO IN('1243')
SELECT @BuyBackDiff_ID = FinanceID FROM dbo.BD_Finance WHERE FinanceNO IN('510204')

DECLARE @TotalDit INT = 2
DECLARE @PriceDit INT = 8

--查询主表明细表名称
SELECT @IndexTable = BillTable,@detailTable = BillDetail,@serialTable=BillSerial FROM dbo.PD_BillType WHERE BillTypeID = @BillType

--201.销售出库单 202.销售退货单
IF @BillType IN (201,202)
BEGIN
	IF @BillType = 201
	BEGIN
		SELECT	@VipCardId = VipCardID,
				@VipChangeTotal = Total - Privilege,
				@VipChangeCent = ExchangeCent - DeductionCent,
				@FreightTotal = FreightTotal,
				@Freight = Freight
		FROM	PD_SellBill
		WHERE	BillNo = @BillNo
	END
	ELSE		
	BEGIN
		SELECT	@VipCardId = VipCardID,
				@VipChangeTotal = -Total + Privilege,
				@VipChangeCent = -ExchangeCent + DeductionCent
		FROM	PD_SellRetBill
		WHERE	BillNo = @BillNo
	END
END

--101.采购入库单
IF @BillType = 101
BEGIN
	SELECT	@FreightTotal = FreightTotal,
			@Freight = Freight,
			@FreightFinanceID = FreightFinanceID
	FROM	PD_PchBill
	WHERE	BillNo = @BillNo
END


------------------------------------------往来过账 BEGIN-----------------------------------------

DECLARE @FieldName VARCHAR(50),@sqlWhere VARCHAR(max)

--处理微信支付账户
IF @BillType IN(201,202, 602, 405, 402)
BEGIN
	IF @BillType=402
	BEGIN
		SET @SQL=' IF EXISTS(SELECT 1 FROM MF_PayRecDetail WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND FinanceID=42)
					BEGIN
						INSERT INTO dbo.PD_WeiXinAccounts( BillTypeID ,BillNo ,FinanceID ,Total ,PayStatus)
						SELECT 402,'+CAST(@BillNo AS VARCHAR(10))+',42,Sum(Total),0 FROM MF_PayRecDetail WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND FinanceID=42 
					END'
	END
	ELSE
	BEGIN
		SET @SQL=' IF EXISTS(SELECT 1 FROM '+@IndexTable+' WHERE FinanceID=42 AND PayRecTotal>0 AND BillNo='+CAST(@BillNo AS VARCHAR(10))+')
					BEGIN	
	                    INSERT INTO dbo.PD_WeiXinAccounts( BillTypeID ,BillNo ,FinanceID ,Total ,PayStatus)
	                    SELECT '+CAST(@BillType AS VARCHAR(10))+',BillNo,FinanceID,PayRecTotal,0 FROM '+@IndexTable+' WHERE PayRecTotal>0 AND BillNo='+CAST(@BillNo AS VARCHAR(10))+'
	                END
                    ELSE IF EXISTS(SELECT 1 FROM dbo.PD_MulAccounts WHERE BillTypeID='+CAST(@BillType AS VARCHAR)+' AND BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND FinanceID=42)
                    BEGIN
	                    INSERT INTO dbo.PD_WeiXinAccounts( BillTypeID ,BillNo ,FinanceID ,Total ,PayStatus)
	                    SELECT BillTypeID,BillNo,FinanceID,Total,0 FROM PD_MulAccounts WHERE BillTypeID='+CAST(@BillType AS VARCHAR(10))+' AND BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND FinanceID=42
	                END'   
	END
	EXEC(@SQL)
END

--获取往来科目基础数据
DECLARE @BanlanceTotal DECIMAL(20,8)
		,@Total DECIMAL(20,8) = 0
		,@Privilege DECIMAL(20,8) = 0
		,@PayRecTotal DECIMAL(20,8) = 0
		,@BPTotal DECIMAL(20,8) = 0
		,@BTDTotal DECIMAL(20,8) = 0	--新增折前金额@BTDTotal 2020-3-4 20:16:08
		,@FeeTotal DECIMAL(20,8) = 0
		,@JTotal DECIMAL(20,8)
		,@DTotal DECIMAL(20,8)
		,@ATypeId	INT

--404,405 表MF_FeeRecDetail无Privilege、BPTotal字段导致过账失败 2020年3月4日
SET @nSQL='SELECT @Total=Total,@FeeTotal=0 FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR)+''
IF @BillType IN(101,102,201,202,403,404,405)
	SET @nSQL+=' SELECT @PayRecTotal=PayRecTotal FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR)+''
IF @BillType IN(101,102,201,202,401,402)
	SET @nSQL+=' SELECT @Privilege=Privilege FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR)+''
IF @BillType IN(401,402)
	SET @nSQL+=' SELECT @BPTotal=BPTotal FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR)+''
--后加数据
--IF @BillType IN(101,102,201,202)
	--SET @nSQL+=' SELECT @BTDTotal=BTDTotal FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR)+''


--采购入库单、采购退货单、销售出库单、销售退货单的折前金额
--处理销售单为计入现金银行 2020年3月4日20:40:19
EXECUTE sp_executesql @nSQL,N'@Total NUMERIC(24,10) OUTPUT
							,@Privilege NUMERIC(24,10) OUTPUT
							,@PayRecTotal NUMERIC(24,10) OUTPUT
							,@BPTotal NUMERIC(24,10) OUTPUT
							,@BTDTotal NUMERIC(24,10) OUTPUT
							,@FeeTotal NUMERIC(24,10) OUTPUT' ,@Total OUTPUT,@Privilege OUTPUT,@PayRecTotal OUTPUT,@BPTotal OUTPUT,@BTDTotal OUTPUT,@FeeTotal OUTPUT		
SET @BanlanceTotal=@Total - @Privilege - @PayRecTotal - @BPTotal - @BTDTotal + @FeeTotal
IF @BillType IN(401,402)
	SET @BanlanceTotal+=@Privilege

--处理应收应付	
IF @BillType IN(101, 102, 201, 202, 401, 402, 404, 405, 501, 502, 503, 504) AND ISNULL(@BanlanceTotal,0)<>0
BEGIN
	IF @BillType IN(101,404,503)
	BEGIN
		SET @ATypeId=@AP_ID
		SET @JTotal=0
		SET @DTotal=@BanlanceTotal
	END
	ELSE IF @BillType IN(102,401,504)
	BEGIN
		SET @ATypeId=@AP_ID
		SET @JTotal=@BanlanceTotal
		SET @DTotal=0
	END
	ELSE IF @BillType IN(201,405,501)
	BEGIN
		SET @ATypeId=@AR_ID
		SET @JTotal=@BanlanceTotal
		SET @DTotal=0
	END
	ELSE IF @BillType IN(202,402,502)
	BEGIN
		SET @ATypeId=@AR_ID
		SET @JTotal=0
		SET @DTotal=@BanlanceTotal
	END
			
	SET @SQL=' INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order])
				SELECT BillNo,'+CAST(@BillType AS varchar)+',BillDate,'+CAST(@ATypeId AS VARCHAR)+',BTypeID,ElyID,DeptID,'+CAST(@JTotal AS VARCHAR)+','+CAST(@DTotal AS varchar)+',10
				FROM '+@IndexTable+' where BillNo='+CAST(@BillNo AS VARCHAR(10))+''
	EXEC(@SQL)
END

	
-- 处理收付款单转的预收预付
IF @BillType IN(401,402) AND ISNULL(@BPTotal,0)<>0
BEGIN
	IF @BillType =401
	BEGIN
		SET @ATypeId=@BP_ID
		SET @JTotal=@BPTotal
		SET @DTotal=0
	END
	ELSE IF @BillType=402
	BEGIN
		SET @AtypeID = @BR_ID
		SET @JTotal = 0
		SET @DTotal = @BPTotal
	END
	SET @SQL=' INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order])
			SELECT BillNo,'+CAST(@BillType AS VARCHAR)+',BillDate,'+CAST(@ATypeId AS VARCHAR)+',BTypeID,ElyID,DeptID,'+CAST(@JTotal AS VARCHAR)+','+CAST(@DTotal AS VARCHAR)+',12
			FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS varchar)+' '
	EXEC(@SQL)
END

--弃用IsAccounts(是否多账户)判断,原因:单据401, 402, 403, 404, 405, 406, 602无此字段导致过账时不能影响现金银行数据
--2020年3月6日17:52:01
--处理收付款
--IF COL_LENGTH(@IndexTable,'IsAccounts') IS NOT NULL
--BEGIN
	--DECLARE @IsAccounts INT
	--SET @nSQL='SELECT @IsAccounts=IsAccounts FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS varchar)+'  '
	--EXECUTE sp_executesql @nSQL,N'@IsAccounts INT OUTPUT',@IsAccounts OUTPUT

	--处理收付款账户
	--IF @IsAccounts=0
IF NOT EXISTS(SELECT TOP 1 1 FROM PD_MulAccounts WHERE BillNo=@BillNo AND BillTypeID=@BillType)
BEGIN

	IF @BillType IN(101, 102, 201, 202, 401, 402, 403, 404, 405, 406, 602) AND ISNULL(@PayRecTotal,0)<>0 
	BEGIN

		IF @BillType IN(101, 202, 401, 403, 404, 406)
		BEGIN
			SET @JTotal=0
			SET @DTotal=@PayRecTotal
		END
		ELSE
		BEGIN
			SET @JTotal=@PayRecTotal
			SET @DTotal=0
		END

		SET @SQL=' INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order])
		SELECT BillNo,'+CAST(@BillType AS VARCHAR)+',BillDate,FinanceID,BTypeID,ElyID,DeptID,'+CAST(@JTotal AS VARCHAR)+','+CAST(@DTotal AS VARCHAR)+',11
		FROM '+@IndexTable+'  WHERE BillNo='+CAST(@BillNo AS varchar)+' '
		
		EXEC(@SQL)
	END 
END
--处理多账户收付款
ELSE
BEGIN

	IF @BillType IN(101, 102, 201, 202, 403, 404, 405, 602)
	BEGIN

		IF @BillType IN(101, 202, 403, 404)
			SET @FieldName='DTotal,JTotal'
		ELSE
			SET @FieldName='JTotal,DTotal'

		SET @SQL='INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,'+@FieldName+',[Order])
					SELECT MA.BillNo,MA.BillTypeID,B.BillDate,MA.FinanceID,B.BTypeID,B.ElyID,B.DeptID,MA.Total,0,11
					FROM PD_MulAccounts MA INNER JOIN '+@IndexTable+' B ON MA.BillNo=B.BillNo AND MA.BillTypeID=B.BillTypeID
					Where BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND BillTypeID='+CAST(@BillType AS VARCHAR(10))+''
		EXEC(@SQL)
	END
END
--END


--处理优惠金额
IF @BillType IN(101, 102, 201, 202, 401, 402, 602) AND ISNULL(@Privilege,0)<>0
BEGIN
	DECLARE @PER_ID INT
	SET @nSQL='SELECT @PER_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO=''550102''' 
	EXECUTE sp_executesql @nSQL,N'@PER_ID INT OUTPUT',@PER_ID OUTPUT
	IF @BillType IN(101,202,401)
	BEGIN
		SET @JTotal = 0
        SET @DTotal =@Privilege
	END
	ELSE
	BEGIN
		SET @JTotal = @Privilege
        SET @DTotal = 0
	END
	SET @SQL='INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order])
			SELECT BillNo,'+CAST(@BillType AS VARCHAR)+',BillDate,'+CAST(@PER_ID AS VARCHAR)+',BTypeID,ElyID,DeptID,'+CAST(@JTotal AS VARCHAR)+','+CAST(@DTotal AS VARCHAR)+',11
			FROM '+@IndexTable+'  WHERE BillNo='+CAST(@BillNo AS varchar)+' '
	EXEC(@SQL)
END

--增加分组字段A.BillNo,A.BillDate,B.FinanceID,A.BTypeID,A.ElyID,A.DeptID 2020年3月2日
--处理单据明细收付款项目
IF @BillType IN(401, 402, 403, 404, 405, 406, 501, 502, 503, 504)
BEGIN
	IF @BillType IN(401, 405, 501, 504)
		SET @FieldName='DTotal,JTotal'
	ELSE
		SET @FieldName='JTotal,DTotal'
	SET @SQL='INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,'+@FieldName+',[Order])
	          SELECT A.BillNo,'+CAST(@BillType AS VARCHAR)+',A.BillDate,B.FinanceID,A.BTypeID,A.ElyID,A.DeptID,Sum(B.Total),0,8 
	          FROM '+@IndexTable+' A INNER JOIN '+@detailTable+' B ON A.BillNo=B.BillNo WHERE B.BillNo='+CAST(@BillNo AS VARCHAR(10))+' Group By A.BillNo,A.BillDate,B.FinanceID,A.BTypeID,A.ElyID,A.DeptID,B.FinanceID'
	EXEC(@SQL)	          
END
ELSE IF @BillType = 602
BEGIN
	SET @SQL='INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,DTotal,JTotal,[Order])
            SELECT 	A.BillNo,'+CAST(@BillType AS VARCHAR)+',A.BillDate,T.FinanceID,0,A.ElyID,A.DeptID,Sum(D.Total),0,8 
            FROM VS_VipChargeBill A INNER JOIN dbo.VS_VipChargeDetail  d ON A.BillNo=D.BillNo
			INNER JOIN dbo.VS_VipCard v ON v.VipCardID=d.VipCardID 
			INNER JOIN dbo.VS_VipCardType T ON T.VipCardTypeID=v.VipCardTypeID 
			WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' Group By T.FinanceID,V.BTypeID'
	EXEC(@SQL)		
END

------------------------------------------往来过账 END-----------------------------------------



-------------------------------------------库存含序列号过账 BEGIN------------------------------

--取不到成本但有最近进价的取最近进价为成本价
IF @BillType IN(102, 201, 202, 301, 304, 305, 306, 309, 310, 600)
BEGIN
	SELECT @FieldName=CASE WHEN @BillType IN(301,309) THEN 'OutWhsID' ELSE 'WhsID' END
	SELECT @sqlWhere=CASE WHEN @BillType =310 THEN ' AND DetailType= 2 ' ELSE '' END
	SET @SQL='IF EXISTS(SELECT 1 FROM '+@detailTable+' p LEFT JOIN PD_GoodsStock s ON p.'+@FieldName+'=s.WhsID AND p.GoodsID=s.GoodsID 
				INNER JOIN BD_Goods G On p.GoodsID=G.GoodsID
				WHERE  InPutPrice=1 AND (CostMethod =1 AND (s.Price IS NULL OR s.Price<0 ) OR CostMethod=2) AND BillNo='+CAST(@BillNo AS VARCHAR(10))+' '+@sqlWhere+')
				UPDATE '+@detailTable+' SET GoodsCostTotal= ROUND((BSQty*t.Price)/Convfactor,'+CAST(@TotalDit AS VARCHAR(10))+'),CostPrice=ROUND(t.Price/Convfactor,'+CAST(@PriceDit AS VARCHAR(10))+'),InPutPrice=0 FROM
				(SELECT  UnitID, GoodsID,ROUND(PchDis*PchPrice,'+CAST(@PriceDit AS VARCHAR(10))+') Price FROM dbo.PD_PriceTrail t WHERE PchPrice IS NOT NULL AND PchDate=(SELECT MAX(PchDate) FROM PD_PriceTrail WHERE GoodsID=t.GoodsID  AND UnitID=t.UnitID ))t
				WHERE '+@detailTable+'.BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND '+@detailTable+'.UnitID=t.UnitID  AND t.GoodsID='+@detailTable+'.GoodsID AND InPutPrice=1 '+@sqlWhere+' '
	
END

--同价调拨单、变价调拨单为双仓库 2020年3月2日
IF @BillType NOT IN(301,309)
BEGIN
	DECLARE @nBTypeId VARCHAR(100),@nPosTime DATETIME
	SET @nSQL='SELECT @nBTypeId=BTypeID,@nPosTime=PosTime FROM '+@IndexTable+' WHERE BillNo='+CAST(@BillNo AS varchar)+' '
	EXECUTE sp_executesql @nSQL,N'@nBTypeId INT OUTPUT,@nPosTime DATETIME OUTPUT',@nBTypeId OUTPUT,@nPosTime OUTPUT
END

--出库序列号过账
IF @BillType IN(102, 201, 304, 305, 310, 600)
BEGIN
	SELECT @sqlWhere=CASE WHEN @BillType =310 THEN ' AND DetailType= 2 ' ELSE '' END
	SET @SQL='UPDATE '+@serialTable+' SET CostPrice=g.CostPrice
                FROM dbo.PD_GoodsSerial g,'+@detailTable+' d
                WHERE g.Serial='+@serialTable+'.Serial AND g.Flag=1 AND d.DID='+@serialTable+'.BillDID AND d.BillNo='+CAST(@BillNo AS VARCHAR(10))+'                        
                UPDATE dbo.PD_GoodsSerial SET Flag=0,OutTime='''+CONVERT(varchar, @nPosTime, 120)+''',OutBTypeID='+CAST(@nBTypeId AS VARCHAR(10))+'
                FROM '+@serialTable+' s INNER JOIN '+@detailTable+' d ON s.BillDID=d.DID
                WHERE s.Serial=PD_GoodsSerial.Serial AND PD_GoodsSerial.Flag=1 AND BillNo='+CAST(@BillNo AS VARCHAR(10))+' '+@sqlWhere+''
	EXEC(@SQL)
END


DECLARE @QtyName VARCHAR(50),@nTotalName VARCHAR(50)
--单据不直接影响成本单据处理主表--单仓库
IF @BillType IN(102, 201, 202, 304, 305, 310, 600)
BEGIN
	SELECT @QtyName=CASE WHEN @BillType=202 THEN 'BsQty' ELSE '-BsQty' END,
			@nTotalName=CASE WHEN @BillType=202 THEN 'GoodsCostTotal' ELSE '-GoodsCostTotal' END
	SELECT @sqlWhere=CASE WHEN @BillType =310 THEN ' AND DetailType= 2 ' ELSE '' END
	SET @SQL='UPDATE '+@detailTable+' SET GoodsCostTotal=CASE WHEN s.Qty='+@detailTable+'.BSQty THEN s.Total ELSE ROUND(BSQty*s.Price,'+CAST(@TotalDit AS VARCHAR(10))+') END,CostPrice=s.Price FROM dbo.PD_GoodsStock s
				WHERE '+@detailTable+'.BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND s.GoodsID='+@detailTable+'.GoodsID AND s.WhsID='+@detailTable+'.WhsID   AND InPutPrice=1 '+@sqlWhere+' 
				;WITH PostData AS(SELECT GoodsID,WhsID,SUM('+@QtyName+') AS Qty,SUM('+@nTotalName+') AS Total FROM '+@detailTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' '+@sqlWhere+'  GROUP BY WhsID,GoodsID)
				MERGE PD_GoodsStock AS target USING(SELECT GoodsID,WhsID,Qty,Total FROM PostData) AS source
				ON target.GoodsID=source.GoodsID AND target.WhsID =source.WhsID
				WHEN MATCHED THEN UPDATE SET target.Qty += source.Qty,target.Total += source.Total,TARGET.Price=CASE WHEN TARGET.Qty + source.Qty=0 
				THEN TARGET.Price ELSE ROUND(CAST(TARGET.Total+source.Total AS DECIMAL(20,8))/CAST(TARGET.Qty+source.Qty as DECIMAL(20,8)),'+CAST(@PriceDit AS VARCHAR(10))+') END
				WHEN NOT MATCHED BY TARGET and source.Qty<>0 THEN INSERT (GoodsID,WhsID,Qty,Total,Price) 
				VALUES(source.GoodsID,source.WhsID,source.Qty,source.Total,ROUND(CAST(source.Total AS DECIMAL(20,8))/CAST(source.Qty AS DECIMAL(20,8)),'+CAST(@PriceDit AS VARCHAR(10))+'));'
	EXEC(@SQL)				
END

			
--单价影响成本类单据过账处理主表-单仓库
IF @BillType IN(101,303,306,310)
BEGIN
	SELECT @sqlWhere=CASE WHEN @BillType =310 THEN ' AND DetailType= 1' ELSE '' END
	SET @SQL=';WITH PostData AS(SELECT GoodsID,WhsID,SUM(BsQty) AS Qty,SUM(GoodsCostTotal) AS Total FROM '+@detailTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' '+@sqlWhere+' GROUP BY WhsID,GoodsID)
                MERGE PD_GoodsStock AS target USING(SELECT GoodsID,WhsID,Qty,Total FROM PostData) AS source
                ON target.GoodsID=source.GoodsID AND target.WhsID =source.WhsID
                WHEN MATCHED THEN UPDATE SET target.Qty += source.Qty,TARGET.Total += source.Total,TARGET.Price=CASE WHEN TARGET.Qty + source.Qty=0 
                THEN TARGET.Price ELSE ROUND(CAST(TARGET.Total+source.Total AS DECIMAL(20,8))/CAST(TARGET.Qty+source.Qty as DECIMAL(20,8)),'+CAST(@PriceDit AS VARCHAR(10))+') END
                WHEN NOT MATCHED BY TARGET and source.Qty<>0 THEN INSERT (GoodsID,WhsID,Qty,Total,Price) 
                VALUES(source.GoodsID,source.WhsID,source.Qty,source.Total,ROUND(CAST(source.Total AS DECIMAL(20,8))/CAST(source.Qty as DECIMAL(20,8)),'+CAST(@PriceDit AS VARCHAR(10))+'));
                '
    EXEC(@SQL)
END


--入库序列号过账
IF @BillType IN(101, 202, 303, 306, 310)
BEGIN
	SELECT @sqlWhere=CASE WHEN @BillType =310 THEN ' AND DetailType= 1' ELSE '' END
	SET @SQL='UPDATE '+@serialTable+' SET CostPrice=d.CostPrice FROM '+@detailTable+' d WHERE d.DID='+@serialTable+'.BillDID AND d.BillNo='+CAST(@BillNo AS VARCHAR(10))+' '+@sqlWhere+'
				INSERT INTO dbo.PD_GoodsSerial( Serial ,WhsID ,WhsPtID , GoodsID ,Ppt1ID ,Ppt2ID ,InBTypeID ,InTime ,Remark ,CostPrice ,BatchNumber,ProductDate,EndDate)
				SELECT Serial ,d.WhsID ,WhsPtID , GoodsID ,Ppt1ID ,Ppt2ID ,'+CAST(@nBTypeId AS VARCHAR(10))+' ,'''+CONVERT(varchar, @nPosTime, 120)+''' ,s.Remark ,s.CostPrice,d.BatchNumber,d.ProductDate,d.EndDate
				FROM '+@serialTable+' s INNER JOIN '+@detailTable+' d ON D.DID=s.BillDID WHERE d.BillNo='+CAST(@BillNo AS VARCHAR(10))+' '+@sqlWhere+''
	EXEC(@SQL)
END


--单独处理调价单
IF @BillType =302 
BEGIN
	IF EXISTS(SELECT 1 FROM SS_SysCfg WHERE CfgName='SerialNoMgt' AND CfgValue=1)
	BEGIN
		SET @SQL='UPDATE dbo.PD_AdjPriceSerial SET CostPrice=g.CostPrice,AdjPrice=ROUND(D.AdjTotal/BSQty,'+@PriceDit+')
					FROM dbo.PD_AdjPriceDetail D,dbo.PD_GoodsSerial g 
					WHERE D.DID=PD_AdjPriceSerial.BillDID AND g.Serial=PD_AdjPriceSerial.Serial AND g.Flag=1 AND BillNo='+CAST(@BillNo AS VARCHAR(10))+'
					UPDATE dbo.PD_GoodsSerial SET CostPrice=s.AdjPrice
					FROM  dbo.PD_AdjPriceDetail d
					INNER JOIN dbo.PD_AdjPriceSerial s ON s.BillDID=d.DID
					WHERE d.BillNo='+CAST(@nBTypeId AS VARCHAR(10))+' AND s.Serial=PD_GoodsSerial.Serial AND PD_GoodsSerial.Flag=1'
		EXEC(@SQL)
	END
	
	SET @SQL='UPDATE PD_AdjPriceDetail SET GoodsCostTotal=CASE WHEN s.Qty=PD_AdjPriceDetail.BSQty THEN s.Total ELSE ROUND(BSQty*s.Price,'+CAST(@TotalDit AS VARCHAR(10))+') END,CostPrice=s.Price FROM dbo.PD_GoodsStock s
                WHERE PD_AdjPriceDetail.BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND s.GoodsID=PD_AdjPriceDetail.GoodsID AND s.WhsID=PD_AdjPriceDetail.WhsID AND BSQty<>0 
                AND CASE WHEN BSQty=0 THEN 0 ELSE GoodsCostTotal/BSQty END > 0 AND InPutPrice=1
                ;WITH PostData AS(
                SELECT WhsID,GoodsID,SUM(BsQty) AS Qty,SUM(AdjTotal - GoodsCostTotal) as Total FROM PD_AdjPriceDetail 
                WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' GROUP BY WhsID,GoodsID Having SUm(GoodsCostTotal)<>SUM(AdjTotal))
                MERGE PD_GoodsStock AS target USING(SELECT GoodsID,WhsID,Qty,Total FROM PostData) AS source
                ON target.GoodsID=source.GoodsID AND target.WhsID =source.WhsID
                WHEN MATCHED AND target.Qty>=source.Qty
                THEN UPDATE SET target.Total+=source.Total,TARGET.Price=CASE WHEN TARGET.Qty=0
                THEN TARGET.Price ELSE ROUND(CAST(TARGET.Total+source.Total AS DECIMAL(20,8))/TARGET.Qty,'+CAST(@PriceDit AS VARCHAR(10))+') END;'
	EXEC(@SQL)
END

DECLARE @AllotWithInspect INT --调拨单是否启用验货流程
SELECT @AllotWithInspect=CfgValue FROM SS_SysCfg WHERE CfgName='AllotWithInspect'
DECLARE @sqlStr varchar(500)
--处理双仓库仓库库存主表 --目前仅仅有调拨单
--2020年3月11日 第468行拼接报错 原因未使用ROUND后面却拼接了@PriceDit
IF @BillType IN(301,309)
BEGIN
	IF EXISTS(SELECT 1 FROM SS_SysCfg WHERE CfgName='SerialNoMgt' AND CfgValue=1)
	BEGIN
		SELECT @sqlStr=CASE WHEN @AllotWithInspect=1 THEN '' ELSE 
							CASE WHEN @BillType=301 THEN ',AllotPrice=G.CostPrice' ELSE ',AllotPrice=ROUND(D.AllotTotal/BSQty,'+CAST(@PriceDit AS VARCHAR(10))+')' END 
						END
						
		SET @SQL='UPDATE PD_AllotSerial SET CostPrice=ROUND(g.CostPrice,'+CAST(@PriceDit AS VARCHAR(10))+') FROM dbo.PD_GoodsSerial g,PD_AllotDetail d
                  WHERE g.Serial=PD_AllotSerial.Serial AND g.Flag=1 AND d.DID=PD_AllotSerial.BillDID AND d.BillNo='+CAST(@BillNo AS VARCHAR(10))+' '
		IF @AllotWithInspect=1
		BEGIN
			SET @SQL+='
						UPDATE dbo.PD_GoodsSerial SET Flag=2
	                    FROM  dbo.PD_AllotDetail d
	                    INNER JOIN dbo.PD_AllotSerial s ON s.BillDID=d.DID
	                    WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND s.Serial=PD_GoodsSerial.Serial AND PD_GoodsSerial.Flag=1'
		END
		ELSE
		BEGIN
			SET @SQL+='
						UPDATE dbo.PD_GoodsSerial SET WhsID=d.InWhsID,WhsPtID=InWhsPtID,CostPrice=S.AllotPrice
	                    FROM  dbo.PD_AllotDetail d
	                    INNER JOIN dbo.PD_AllotSerial s ON s.BillDID=d.DID
	                    WHERE d.BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND s.Serial=PD_GoodsSerial.Serial AND PD_GoodsSerial.Flag=1'
		END

		EXEC(@SQL)
	END
	SELECT @nTotalName=CASE WHEN @BillType=301 THEN 'GoodsCostTotal' ELSE 'AllotTotal' END
	SELECT @sqlStr=CASE WHEN @AllotWithInspect=1 THEN '' 
						ELSE 'UNION ALL
							  SELECT InWhsID AS WhsID,GoodsID,SUM(BsQty) AS Qty,SUM('+@nTotalName+') AS Total 
							  FROM dbo.PD_AllotDetail WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' 
							  GROUP BY InWhsID,GoodsID' END
	SET @SQL=' UPDATE PD_AllotDetail SET GoodsCostTotal=CASE WHEN s.Qty=PD_AllotDetail.BSQty THEN s.Total ELSE ROUND(BSQty*s.Price,'+CAST(@TotalDit AS VARCHAR(10))+') END,CostPrice=s.Price FROM dbo.PD_GoodsStock s
                WHERE PD_AllotDetail.BillNo='+CAST(@BillNo AS VARCHAR)+' AND s.GoodsID=PD_AllotDetail.GoodsID AND s.WhsID=PD_AllotDetail.OutWhsID AND InPutPrice=1
                IF EXISTS(SELECT 1 FROM dbo.PD_GoodsStock g INNER JOIN (SELECT SUM(BSQty) Qty,SUM(GoodsCostTotal) Total,D.GoodsID,OutWhsID FROM  PD_AllotDetail D
                          INNER JOIN BD_Goods Gs ON D.GoodsID=Gs.GoodsID WHERE  BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND (InPutPrice<>0 OR gs.CostMethod=2) GROUP BY D.GoodsID,OutWhsID) p ON g.GoodsID = p.GoodsID AND g.WhsID = p.OutWhsID 
                          WHERE  g.Qty=p.Qty  AND g.Total<>p.Total AND g.Total>0)
                UPDATE dbo.PD_AllotDetail SET GoodsCostTotal+=g.Total,CostPrice= Case G.CostMethod WHEN 1 THEN ROUND((GoodsCostTotal+g.Total)/BSQty,'+CAST(@TotalDit AS VARCHAR(10))+') ELSE CostPrice END
                FROM( SELECT DID,g.Total-p.Total AS Total,CostMethod
                      FROM (SELECT MAX(DID) DID, SUM(BsQty) Qty,SUM(GoodsCostTotal) Total,D.GoodsID,OutWhsID,CostMethod FROM  PD_AllotDetail D
                      INNER JOIN BD_Goods Gs ON D.GoodsID=Gs.GoodsID WHERE  BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND (InPutPrice<>0 OR gs.CostMethod=2)  GROUP BY D.GoodsID,OutWhsID,CostMethod)p
                      INNER JOIN PD_GoodsStock g ON g.GoodsID = p.GoodsID AND g.WhsID = p.OutWhsID 
                      WHERE  g.Qty=p.Qty AND g.Total<>p.Total AND g.Total>=0
				)g WHERE g.DID=PD_AllotDetail.DID;
                WITH PostData AS
				(
					SELECT OutWhsID AS WhsID,GoodsID,SUM(-BsQty) AS Qty,SUM(-GoodsCostTotal) AS Total  FROM dbo.PD_AllotDetail 
					WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' GROUP BY OutWhsID,GoodsID
					'+@sqlStr+'
				)MERGE PD_GoodsStock AS target 
				USING(SELECT GoodsID,WhsID,Qty,Total FROM PostData) AS source ON target.GoodsID=source.GoodsID AND target.WhsID =source.WhsID
                WHEN MATCHED THEN UPDATE SET target.Qty = target.Qty + source.Qty,target.Total += source.Total,TARGET.Price=CASE WHEN TARGET.Qty + source.Qty=0 
                THEN TARGET.Price ELSE ROUND(CAST(TARGET.Total+source.Total AS DECIMAL(20,8))/CAST(TARGET.Qty+source.Qty as DECIMAL(20,8)),'+CAST(@PriceDit AS VARCHAR(10))+') END
                WHEN NOT MATCHED BY TARGET and source.Qty<>0 THEN INSERT (GoodsID,WhsID,Qty,Total,Price) 
                VALUES(source.GoodsID,source.WhsID,source.Qty,source.Total,ROUND(CAST(source.Total AS DECIMAL(20,8))/CAST(source.Qty as DECIMAL(20,8)),'+CAST(@PriceDit AS VARCHAR(10))+'));'
	EXEC(@SQL)
	IF @BillType=301
	BEGIN
		SET @SQL=' UPDATE PD_AllotDetail SET AllotTotal = GoodsCostTotal,AllotPrice=ROUND(CostPrice*Convfactor,'+CAST(@PriceDit AS VARCHAR(10))+')  WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+''
		EXEC(@SQL)
	END
END

--出库处理数量为0金额不为0的情况（数量拆分过后*单价之和！=金额）
IF @BillType IN(102, 201, 304, 305, 306, 310, 600)
BEGIN
	SET @SQL='IF EXISTS(SELECT 1 FROM dbo.PD_GoodsStock g INNER JOIN '+@detailTable+' p ON g.GoodsID = p.GoodsID AND g.WhsID = p.WhsID
						 INNER JOIN BD_Goods Gs ON G.GoodsID=Gs.GoodsID
						 WHERE g.Qty=0 AND g.Total<>0 AND BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND (InPutPrice<>0 OR  Gs.CostMethod=2))
				BEGIN  UPDATE '+@detailTable+' SET GoodsCostTotal+=g.Total,CostPrice=CASE CostMethod WHEN 1 THEN ROUND((GoodsCostTotal+g.Total)/BSQty,'+CAST(@PriceDit AS VARCHAR(10))+') ELSE CostPrice END
				FROM(SELECT DID,g.Total AS Total,CostMethod
				FROM (SELECT MAX(DID) DID,D.GoodsID,WhsID,CostMethod FROM  '+@detailTable+' D INNER JOIN BD_Goods Gs ON D.GoodsID=Gs.GoodsID
					   WHERE  BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND (InPutPrice<>0 OR CostMethod=2) GROUP BY D.GoodsID,WhsID,CostMethod)p
				INNER JOIN	PD_GoodsStock g ON g.GoodsID = p.GoodsID AND g.WhsID = p.WhsID
				WHERE  g.Qty=0 AND g.Total<>0 )g WHERE g.DID='+@detailTable+'.DID
				UPDATE PD_GoodsStock SET Total=0  FROM dbo.PD_GoodsStock g INNER JOIN '+@detailTable+' p ON g.GoodsID = p.GoodsID AND g.WhsID = p.WhsID
				INNER JOIN BD_Goods Gs ON G.GoodsID=Gs.GoodsID WHERE g.Qty=0 AND g.Total<>0 AND BillNo='+CAST(@BillNo AS VARCHAR(10))+' AND (InPutPrice<>0 OR CostMethod=2) END'
	EXEC(@SQL)
END

--处理单仓库库存明细数量
IF @BillType IN (101, 102, 201, 202, 303, 304, 305, 306, 310, 600)
BEGIN
	SELECT @QtyName=CASE WHEN @BillType IN(101, 202, 303, 306) THEN 'BsQty' 
						 WHEN @BillType=310 THEN ' CASE WHEN DetailType=1 THEN BsQty ELSE -BsQty END'
						 ELSE '-BsQty'  END 
	SET @SQL=';WITH PostData AS(
                            SELECT D.GoodsID,WhsID,WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate, 
                                    SUM('+@QtyName+') AS Qty,CASE CostMethod WHEN 1 THEN 0 ELSE CostPrice END CostPrice 
                            FROM '+@detailTable+' D 
                                    INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID 
                            WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' 
                            GROUP BY WhsID,WhsPtID,D.GoodsID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,CASE CostMethod WHEN 1 THEN 0 ELSE CostPrice END)
                MERGE PD_GoodsStock_Detail AS target USING(SELECT GoodsID,WhsID,WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,Qty,CostPrice FROM PostData) AS source
                ON target.GoodsID=source.GoodsID AND target.WhsPtID =source.WhsPtID AND target.Ppt1ID=source.Ppt1ID AND target.Ppt2ID=source.Ppt2ID
                AND target.BatchNumber=source.BatchNumber AND target.ProductDate =source.ProductDate AND target.EndDate=source.EndDate AND target.CostPrice=source.CostPrice
                WHEN MATCHED AND target.Qty + source.Qty = 0 THEN DELETE
                WHEN MATCHED THEN UPDATE SET target.Qty = target.Qty + source.Qty
                WHEN NOT MATCHED BY TARGET  and source.Qty<>0 THEN INSERT (StockID,GoodsID,WhsPtID,Ppt1ID,Ppt2ID,Qty,BatchNumber,ProductDate,EndDate,CostPrice) VALUES(
                (SELECT StockID FROM PD_GoodsStock WHERE GoodsID=source.GoodsID AND WhsID=source.WhsID),source.GoodsID,source.WhsPtID,source.Ppt1ID,source.Ppt2ID,source.Qty
                ,source.BatchNumber,source.ProductDate,source.EndDate,source.CostPrice);'
	EXEC(@SQL)
END

		
--处理调价单明细 只针对手工指定商品
IF @BillType=302
BEGIN
	;WITH PostData AS(SELECT D.GoodsID,WhsID,WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,CostPrice, SUM(-BSQty) AS Qty FROM PD_AdjPriceDetail D 
                INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE G.CostMethod=2 AND BillNo=CAST(@BillNo AS VARCHAR(10)) GROUP BY WhsID,WhsPtID,D.GoodsID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,CostPrice
                UNION ALL SELECT D.GoodsID,WhsID,WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,ROUND(AdjTotal/BSQty,@PriceDit), SUM(BSQty) AS Qty FROM PD_AdjPriceDetail D 
                INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE G.CostMethod=2 AND BillNo=CAST(@BillNo AS VARCHAR(10)) GROUP BY WhsID,WhsPtID,D.GoodsID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,ROUND(AdjTotal/BSQty,@PriceDit))
                MERGE PD_GoodsStock_Detail AS target USING(SELECT GoodsID,WhsID,WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,CostPrice,Qty FROM PostData) AS source
                ON target.GoodsID=source.GoodsID AND target.WhsPtID =source.WhsPtID AND target.Ppt1ID=source.Ppt1ID AND target.Ppt2ID=source.Ppt2ID
                AND target.BatchNumber=source.BatchNumber AND target.ProductDate =source.ProductDate AND target.EndDate=source.EndDate AND target.CostPrice=source.CostPrice
                WHEN MATCHED AND target.Qty + source.Qty = 0 THEN DELETE
                WHEN MATCHED THEN UPDATE SET target.Qty = target.Qty + source.Qty
                WHEN NOT MATCHED BY TARGET  and source.Qty<>0 THEN INSERT (StockID,GoodsID,WhsPtID,Ppt1ID,Ppt2ID,Qty,BatchNumber,ProductDate,EndDate,CostPrice) VALUES(
                (SELECT StockID FROM PD_GoodsStock WHERE GoodsID=source.GoodsID AND WhsID=source.WhsID),source.GoodsID,source.WhsPtID,source.Ppt1ID,source.Ppt2ID,source.Qty
                ,source.BatchNumber,source.ProductDate,source.EndDate,source.CostPrice);
	EXEC(@SQL)
END

--处理双仓库仓库库存明细数量 --目前仅仅有调拨单
--修复问题,@sqlStr限制(500)个字节导致显示不完整提示ProductD字段错误
--修复问题选择列表中的列 'BD_Goods.CostMethod' 无效，因为该列没有包含在聚合函数或 GROUP BY 子句中。,将GROUP BY中的CostMethod
IF @BillType IN(301,309)
BEGIN
	SELECT @sqlStr= CASE WHEN @AllotWithInspect=1 THEN '' 
		  ELSE 'UNION ALL
				SELECT InWhsID AS WhsID,D.GoodsID,InWhsPtID AS WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,SUM(BsQty) AS Qty,
				CASE CostMethod WHEN 1 THEN 0 ELSE ROUND(SUM(AllotTotal)/SUM(BsQty),'+CAST(@PriceDit AS VARCHAR(10))+') END CostPrice FROM dbo.PD_AllotDetail D
				INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' 
				GROUP BY InWhsID,InWhsPtID,D.GoodsID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,EndDate,CostMethod '
				--CASE CostMethod WHEN 1 THEN 0 ELSE ROUND(AllotTotal/BSQty,'+CAST(@PriceDit AS VARCHAR(10))+') END 
		  END
	SET @SQL=';WITH PostData AS(
                SELECT OutWhsID AS WhsID,D.GoodsID,OutWhsPtID AS WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,SUM(-BsQty) AS Qty,
				CASE CostMethod WHEN 1 THEN 0 ELSE CostPrice END CostPrice FROM dbo.PD_AllotDetail D
                INNER JOIN BD_Goods G ON D.GoodsID=G.GoodsID WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' 
                GROUP BY OutWhsID,OutWhsPtID,D.GoodsID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,CASE CostMethod WHEN 1 THEN 0 ELSE CostPrice END 
				'+@sqlStr+' 
				)MERGE PD_GoodsStock_Detail AS target 
				USING(SELECT GoodsID,WhsID,WhsPtID,Ppt1ID,Ppt2ID,BatchNumber,ProductDate,EndDate,Qty,CostPrice FROM PostData) AS source
                ON target.GoodsID=source.GoodsID AND target.WhsPtID =source.WhsPtID AND target.Ppt1ID=source.Ppt1ID AND target.Ppt2ID=source.Ppt2ID
                AND target.BatchNumber=source.BatchNumber AND target.ProductDate =source.ProductDate AND target.CostPrice=source.CostPrice
                WHEN MATCHED AND target.Qty + source.Qty = 0 THEN DELETE
                WHEN MATCHED THEN UPDATE SET target.Qty = target.Qty + source.Qty
                WHEN NOT MATCHED BY TARGET  and source.Qty<>0 THEN INSERT (StockID,GoodsID,WhsPtID,Ppt1ID,Ppt2ID,Qty,BatchNumber,ProductDate,EndDate,CostPrice) VALUES(
                (SELECT StockID FROM PD_GoodsStock WHERE GoodsID=source.GoodsID AND WhsID=source.WhsID),source.GoodsID,source.WhsPtID,source.Ppt1ID,source.Ppt2ID,source.Qty
                 ,source.BatchNumber,source.ProductDate,source.EndDate,source.CostPrice);' 
	EXEC(@SQL)                                           
END

--回写成本价过后要修改主表单据金额
IF @BillType IN (301, 304, 305, 306, 310, 600)
BEGIN
	IF @BillType=310
	BEGIN
		UPDATE PD_AssemblyBill SET OutTotal=d.OutTotal,InTotal=d.InTotal FROM (SELECT SUM(CASE WHEN DetailType=1 THEN goodscosttotal ELSE 0 END) InTotal, 
               SUM(CASE WHEN DetailType=2 THEN goodscosttotal ELSE 0 END) OutTotal FROM PD_AssemblyDetail WHERE BillNo=@BillNo)d WHERE BillNo =@BillNo
	END
	SET @SQL='UPDATE '+@IndexTable+' SET Total=d.total FROM (SELECT SUM(goodscosttotal)total 
              FROM '+@detailTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+')d WHERE BillNo ='+CAST(@BillNo AS VARCHAR(10))+''
	EXEC(@SQL)
END

-------------------------------------------库存含序列号过账 END--------------------------------

--单据自己的项目单独处理

IF @BillType IN (101, 102, 201, 202, 301, 302, 303, 304, 305, 306, 309, 310, 406, 600)
BEGIN
	IF @BillType = 101	--采购入库单
	BEGIN
		IF @Freight - @FreightTotal <> 0
		BEGIN
			INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order],ExPay)
			SELECT	BillNo,101 AS BillTypeID,BillDate,@AP_ID,LogistBtypeID,ElyID,DeptID,0 AS JTotal,Freight - FreightTotal,21,1 AS ExPay
			FROM	PD_PchBill
			WHERE	BillNo = @BillNo            
		END
		
		IF @FreightFinanceID <> 0 AND @FreightTotal <> 0
		BEGIN
			INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order],ExPay)
            SELECT	BillNo,101 AS BillTypeID,BillDate,FreightFinanceID,LogistBtypeID,ElyID,DeptID,0 AS JTotal,FreightTotal,22,1 AS ExPay
			FROM	PD_PchBill
			WHERE	BillNo = @BillNo
		END
	END
	
	IF @BillType = 102	--采购退货单
	BEGIN
		IF EXISTS(SELECT 1 FROM PD_PchRetDetail WHERE BillNo=@BillNo Having Sum(TaxTotal-GoodsCostTotal)<>0)
		BEGIN
			INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,DTotal,JTotal,[Order])
			SELECT	B.BillNo,102 AS BillTypeId,B.BillDate,@BuyBackDiff_ID,B.BTypeId,B.ElyID,B.DeptId,Sum(TaxTotal-GoodsCostTotal),0,1 AS [Order]
			FROM	dbo.PD_PchRetBill B
			INNER JOIN PD_PchRetDetail D ON B.BillNo = D.BillNo
			WHERE	B.BillNo = @BillNo
			GROUP BY B.BillNo,
					 B.BillDate,
					 B.BTypeId,
					 B.ElyID,
					 B.DeptId
		END
	END
	
	IF @BillType IN(201,202)  
	BEGIN
		DECLARE @Item_ID INT
		
		--处理销售成本
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='5401'	--销售成本
		SELECT @nTotalName=CASE WHEN @BillType = 201 THEN 'JTotal,DTotal' ELSE 'DTotal,JTotal' END
		SET @SQL='IF EXISTS(SELECT 1 FROM '+@detailTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' Having Sum(GoodsCostTotal)<>0)
				BEGIN
					INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,'+@nTotalName+',[Order])
					SELECT 	SB.BillNo,'+CAST(@BillType AS VARCHAR)+' AS BillTypeId,SB.BillDate,'+CAST(@Item_ID AS VARCHAR(10))+',SB.BTypeID,SB.ElyID,SB.DeptId,Sum(GoodsCostTotal),0,1 
					FROM '+@IndexTable+' SB 
					INNER JOIN '+@detailTable+' SD ON SB.BillNo=SD.BillNo
					WHERE SD.BillNo='+CAST(@BillNo AS VARCHAR)+'
					GROUP BY SB.BillNo,
							 SB.BillDate,
							 SB.BTypeId,
							 SB.ElyID,
							 SB.DeptId
				END'
		EXEC(@SQL)
		
		--处理销售销售收入
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='5101'	--销售收入
		SELECT @nTotalName=CASE WHEN @BillType = 201 THEN 'DTotal,JTotal' ELSE 'JTotal,DTotal' END
		SET @SQL='IF EXISTS(SELECT 1 FROM '+@detailTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR(10))+' Having Sum(DiscTotal)<>0)
				BEGIN
					INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,'+@nTotalName+',[Order])
					SELECT 	SB.BillNo,'+CAST(@BillType AS VARCHAR)+' AS BillTypeId,SB.BillDate,'+CAST(@Item_ID AS VARCHAR(10))+',SB.BTypeID,SB.ElyID,SB.DeptId,Sum(DiscTotal),0,2 
					FROM '+@IndexTable+' SB 
					INNER JOIN '+@detailTable+' SD ON SB.BillNo=SD.BillNo
					WHERE SD.BillNo='+CAST(@BillNo AS VARCHAR)+'
					GROUP BY SB.BillNo,
							 SB.BillDate,
							 SB.BTypeId,
							 SB.ElyID,
							 SB.DeptId
				END'
		EXEC(@SQL)
		
		IF @BillType=201	--销售出库单
		BEGIN
			IF EXISTS( SELECT 1 FROM PD_SellBill WHERE FreightType=1 AND Freight<>0 AND BillNo=@BillNo)
			BEGIN
				SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='510303'	--买家运费收入
				INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order])
                SELECT BillNo,201 AS BillTypeID,BillDate,@Item_ID,BTypeID,ElyID,DeptId,0,Freight,3 
                FROM PD_SellBill WHERE BillNo=@BillNo
			END
			
			--网店转过来的单据不处理运费科目
			IF EXISTS(SELECT 1 FROM PD_SellBill WHERE IsOS=0 AND BillNo=@BillNo)
			BEGIN
				--处理运费
				SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='550103'	
				IF @Freight<>0
				BEGIN
					INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order],ExPay)
					SELECT BillNo,201 AS BillTypeID,BillDate,@Item_ID,LogistBtypeID,ElyID,DeptId,Freight,0,20,1 
					FROM PD_SellBill WHERE BillNo=@BillNo
				END
				
				--处理运费应付款
				IF @Freight<>0 AND @FreightTotal<>0
				BEGIN
					INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order],ExPay)
					SELECT BillNo,201 AS BillTypeID,BillDate,@AP_ID,LogistBtypeID,ElyID,DeptID,0,(Freight - FreightTotal)AS DTotal,21,1
					FROM PD_SellBill WHERE BillNo=@BillNo
				END
				
				--处理运费付款账户
				IF @FreightTotal<>0 AND @FreightFinanceID<>0
				BEGIN
					INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order],ExPay)
                    SELECT BillNo,201 AS BillTypeID,BillDate,@FreightFinanceID,LogistBtypeID,ElyID,DeptID,0,FreightTotal,22,1
                    FROM PD_SellBill WHERE BillNo=@BillNo
				END
			END
		END
	END	
	
	IF @BillType IN(301,309)	--同价调拨单、变价调拨单
	BEGIN
		IF @AllotWithInspect=1
		BEGIN
			--在途物资
			SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='1202'	
			EXEC UP_BD_InsertListFromDetail @Item_ID,'JTotal,DTotal','GoodsCostTotal',0,'PD_AllotBill','PD_AllotDetail',@BillType,@BillNo
			
			--库存商品
			EXEC UP_BD_InsertListFromDetail @Goods_ID,'DTotal,JTotal','GoodsCostTotal',1,'PD_AllotBill','PD_AllotDetail',@BillType,@BillNo
			
		END
		ELSE
		BEGIN
			IF @BillType=309
			BEGIN
				--库存商品
				EXEC UP_BD_InsertListFromDetail @Goods_ID,'JTotal,DTotal','AllotTotal',0,'PD_AllotBill','PD_AllotDetail',309,@BillNo
				
				EXEC UP_BD_InsertListFromDetail @Goods_ID,'DTotal,JTotal','GoodsCostTotal',1,'PD_AllotBill','PD_AllotDetail',309,@BillNo
				
				--变价调拨差价
				SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='510205'	
				EXEC UP_BD_InsertListFromDetail @Item_ID,'DTotal,JTotal','AllotTotal-GoodsCostTotal',2,'PD_AllotBill','PD_AllotDetail',309,@BillNo
			END
		END
	END
	IF @BillType=302	--成本调价单
	BEGIN
		--成本调价收入
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='510203'	
		EXEC UP_BD_InsertListFromDetail @Item_ID,'DTotal,JTotal','AdjTotal-GoodsCostTotal',1,'PD_AdjPriceBill','PD_AdjPriceDetail',302,@BillNo
	END
	
	IF @BillType =303	--其他入库单
	BEGIN
		--其他入库收入
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='510202'	
		EXEC UP_BD_InsertListFromDetail @Item_ID,'DTotal,JTotal','GoodsCostTotal',1,'PD_InOutWhsBill','PD_InOutWhsDetail',303,@BillNo
	END
	
	IF @BillType =304	--其他出库单
	BEGIN
		--其他出库费用
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='540502'	
		EXEC UP_BD_InsertListFromDetail @Item_ID,'JTotal,DTotal','GoodsCostTotal',1,'PD_InOutWhsBill','PD_InOutWhsDetail',304,@BillNo
	END
	
	IF @BillType =305	--报损单
	BEGIN
		--商品报损
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='540501'	
		EXEC UP_BD_InsertListFromDetail @Item_ID,'JTotal,DTotal','GoodsCostTotal',1,'PD_LossSpillBill','PD_LossSpillDetail',305,@BillNo
	END
	
	IF @BillType =306	--报溢单
	BEGIN
		--商品报溢收入
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='510201'	
		EXEC UP_BD_InsertListFromDetail @Item_ID,'DTotal,JTotal','GoodsCostTotal',1,'PD_LossSpillBill','PD_LossSpillDetail',306,@BillNo
	END
	
	IF @BillType =310
	BEGIN
		IF EXISTS(SELECT 1 FROM PD_AssemblyDetail WHERE BillNo=@BillNo AND DetailType=1 Having Sum(GoodsCostTotal)<>0)
		BEGIN
			INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,JTotal,DTotal,[Order])
			SELECT A.BillNo,310,A.BillDate,@Goods_ID,0,A.ElyID,A.DeptID,Sum(GoodsCostTotal),0,0 
			FROM PD_AssemblyBill A INNER JOIN PD_AssemblyDetail B ON A.BillNo=B.BillNo
			WHERE B.BillNo=@BillNo AND DetailType=1
			GROUP BY A.BillNo,A.BillDate,A.ElyID,A.DeptId
		END	  
		
		IF EXISTS(SELECT 1 FROM PD_AssemblyDetail WHERE BillNo=@BillNo AND DetailType=2 Having Sum(GoodsCostTotal)<>0)
		BEGIN
			INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,DTotal,JTotal,[Order])
			SELECT A.BillNo,310,A.BillDate,@Goods_ID,0,A.ElyID,A.DeptID,Sum(GoodsCostTotal),0,1 
			FROM PD_AssemblyBill A INNER JOIN PD_AssemblyDetail B ON A.BillNo=B.BillNo
			WHERE B.BillNo=@BillNo AND DetailType=2
			GROUP BY A.BillNo,A.BillDate,A.ElyID,A.DeptId
		END	 
		
		--商品拆装差价
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='510206'
		IF EXISTS(SELECT 1 FROM PD_AssemblyDetail WHERE BillNo=@BillNo Having Sum(CASE WHEN DetailType=1 THEN GoodsCostTotal ELSE -GoodsCostTotal END)<>0) 
		BEGIN
			INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,DTotal,JTotal,[Order])
			SELECT 	A.BillNo,310,A.BillDate,@Item_ID,0,A.ElyID,A.DeptID,Sum(CASE WHEN DetailType=1 THEN GoodsCostTotal ELSE -GoodsCostTotal END),0,2 
			FROM PD_AssemblyBill A INNER JOIN PD_AssemblyDetail B ON A.BillNo=B.BillNo WHERE B.BillNo=@BillNo 	
			GROUP BY A.BillNo,A.BillDate,A.ElyID,A.DeptId                         
		END
	END
	
	IF @BillType=600	--积分兑换单
	BEGIN
		--优惠
		SELECT @Item_ID=FinanceID FROM dbo.BD_Finance WHERE FinanceNO='550102'
		EXEC UP_BD_InsertListFromDetail @Item_ID,'JTotal,DTotal','GoodsCostTotal',1,'PD_InOutWhsBill','PD_InOutWhsDetail',600,@BillNo
	END
	
	IF @BillType=406	--转款单
	BEGIN
		DECLARE @FeeFinanceID INT
		SELECT @FeeTotal=FeeTotal,@FeeFinanceID=FeeFinanceID FROM MF_TransferBill WHERE BillNo=@BillNo
		IF @FeeTotal<>0 AND @FeeFinanceID<>0
		BEGIN
			INSERT INTO dbo.PD_ListTable( BillNo,BillTypeID,BillDate,FinanceID,BTypeID,ElyID,DeptID,JTotal,DTotal,[Order])
            SELECT BillNo,406,BillDate,@FeeFinanceID,0,ElyID,DeptID,FeeTotal,0,9
            FROM MF_TransferBill WHERE BillNo=@BillNo
		END
	
	END
	
END


--处理库存商品项目
--修复其他入库单、其他出库单提示列名 'FinanceID' 无效。（FinanceID都是通过@Goods_ID拼接起来的，所以无需将FinanceID分组）
IF @BillType IN (101, 102, 201, 202, 302, 303, 304, 305, 306, 600)
BEGIN
	DECLARE @TotalName	VARCHAR(MAX),	
			@TotalValue VARCHAR(MAX)

	SET @TotalName = 'JTotal,DTotal'	
	IF @BillType NOT IN(101, 202, 302, 303, 306)
		SET @TotalName='DTotal,JTotal'
	
	SET @TotalValue = 'GoodsCostTotal'
	IF @BillType = 302 --调价单
		SET @TotalValue = 'AdjTotal-GoodsCostTotal'

	SET @SQL = 'IF EXISTS(SELECT 1 FROM dbo.'+@detailTable+' WHERE BillNo='+CAST(@BillNo AS VARCHAR)+' Having Sum('+@TotalValue+')<>0)
				BEGIN	
					INSERT INTO dbo.PD_ListTable( BillNo ,BillTypeID ,BillDate ,FinanceID ,BTypeID ,ElyID ,DeptID,'+@TotalName+',[Order])
	                SELECT A.BillNo,'+CAST(@BillType AS VARCHAR(10))+',A.BillDate,'+CAST(@Goods_ID AS VARCHAR(10))+',A.BTypeID,A.ElyID,A.DeptID,Sum('+@TotalValue+'),0,0 
	                FROM '+@indexTable+' A INNER JOIN dbo.'+@detailTable+' B ON A.BillNo=B.BillNo 
	                WHERE B.BillNo='+CAST(@BillNo AS VARCHAR)+'
	                GROUP BY A.BillNo,A.BillDate,A.BTypeID,A.ElyID,A.DeptID
				END '
	EXEC(@SQL)
END

--项目余额
MERGE dbo.BD_Funds AS Target 
USING(
		SELECT	f.FinanceID,
				Sum(JTotal-DTotal)*LoanStt AS Total 
		FROM	dbo.PD_ListTable l 
        INNER JOIN dbo.BD_Finance f ON f.FinanceID=l.FinanceID where billno=@billNo and BillTypeID=@BillType  GROUP BY f.FinanceID,LoanStt
) AS source ON Target.FinanceID=source.FinanceID 
WHEN MATCHED THEN UPDATE SET Target.QmBalances+=SOURCE.total
WHEN NOT MATCHED BY TARGET AND SOURCE.total<>0 THEN INSERT(FinanceID,QmBalances)VALUES(SOURCE.FinanceID,SOURCE.total);

--处理往来余额
SET @SQL = ';WITH PostData AS(
				SELECT	BTypeID,
						Isnull(['+CAST(@AR_ID AS VARCHAR)+'],0) AS AR,
						Isnull(['+CAST(@AP_ID AS VARCHAR)+'],0) AS AP,
						Isnull(['+CAST(@BR_ID AS VARCHAR)+'],0) AS Br,
						Isnull(['+CAST(@BP_ID AS VARCHAR)+'],0) AS BP
				FROM	(
							SELECT	BTypeID,
									f.FinanceID,
									(JTotal-DTotal)*LoanStt AS Total 
							FROM	dbo.PD_ListTable l 
							INNER JOIN dbo.BD_Finance f ON f.FinanceID=l.FinanceID 
							WHERE	BillNo='+CAST(@BillNo AS VARCHAR)+' 
									AND BillTypeID='+CAST(@BillType AS VARCHAR)+' 
						)a PIVOT(SUM(Total) For FinanceID IN(['+CAST(@AR_ID AS VARCHAR)+'],['+CAST(@AP_ID AS VARCHAR)+'],['+CAST(@BR_ID AS VARCHAR)+'],['+CAST(@BP_ID AS VARCHAR)+']))AS  t)
				MERGE dbo.BD_ARAP AS Target USING(select BTypeID,Ar,Ap,Br,Bp from PostData Where AR<>0 OR BR<>0 OR AP<>0 OR BP<>0 ) AS source ON Target.BTypeID=source.BTypeID
				WHEN MATCHED THEN UPDATE SET Target.QmAR+=SOURCE.Ar,TARGET.QmAp+=SOURCE.ap,Target.QmBR+=SOURCE.Br,TARGET.QmBp+=SOURCE.Bp
				WHEN NOT MATCHED BY TARGET THEN INSERT(BTypeID,QmAR,QmAp,QmBr,QmBp)VALUES(SOURCE.BTypeID,SOURCE.Ar,SOURCE.Ap,SOURCE.Br,SOURCE.Bp); '

EXEC(@SQL)				

--PR_MdD9_DlyAccount过账调用判断捕捉错误修改：将RETURN的错误码-1依次修改为未占用错误码
--数据检查,过账后
--库存金额不允许为负；0=不启用 1=启用
IF EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'NotAllowNegativeTotal' AND CfgValue = '1')
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM PD_GoodsStock WHERE ISNULL(Total,0)<0)
	BEGIN
		RAISERROR('库存金额不能为负',16,1)
		RETURN -1
	END
END

--允许负库存；0=不允许 1=允许
IF EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'IsNegative' AND CfgValue = '0')
BEGIN
	IF EXISTS(SELECT TOP 1 1 FROM PD_GoodsStock WHERE ISNULL(Qty,0)<0)
	BEGIN
		RAISERROR('库存数量不能为负',16,1)
		RETURN -13
	END
END

--检测是否有金额为0的项目
IF EXISTS(SELECT 1 FROM PD_ListTable WHERE BillNo = @BillNo And BillTypeID=@BillType AND JTotal = 0 AND DTotal=0)
BEGIN
	RAISERROR('存在金额为0的项目',16,1)
	RETURN -14
END

--检测借贷是否相等
IF EXISTS(SELECT 1 FROM PD_ListTable WHERE  BillNo=@BillNo AND BillTypeID=@BillType HAVING SUM(JTotal)<>SUM(DTotal))
BEGIN
	RAISERROR('借贷不相等',16,1)
	RETURN -15
END

--处理价格跟跟踪
IF @VipCardID = 0 AND @BillType IN (101,201)
BEGIN
	DECLARE @BTypeID	VARCHAR(100),
			@PosTime	DATETIME
	IF @BillType = 101
	BEGIN
		SELECT @BTypeId = BTypeId,@PosTime = PosTime FROM PD_PchBill WHERE BillNo = @BillNo
		
		;WITH TrailData AS(
                            SELECT RANK() OVER (PARTITION BY GoodsID,UnitID,WhsID ORDER BY DID DESC)sort, GoodsID,UnitID,DID,Price,Discount FROM PD_PchDetail WHERE BillNo=@BillNo AND Gift=0)
                            MERGE dbo.PD_PriceTrail AS target USING ( SELECT GoodsID,UnitID,Price,Discount FROM TrailData WHERE sort=1) AS source
                            ON target.BtypeID=@BTypeID AND target.GoodsID=source.GoodsID AND target.UnitID=source.UnitID
                            WHEN MATCHED THEN UPDATE SET target.PchDate=@PosTime,target.PchDis=SOURCE.Discount, target.PchPrice=SOURCE.Price
                            WHEN NOT MATCHED BY TARGET THEN INSERT(BtypeID,GoodsID,UnitID,PchPrice,PchDis,PchDate)VALUES(@BTypeID,source.GoodsID,source.UnitID,source.Price,source.Discount,@PosTime);
	END                            
	ELSE
	BEGIN	
		SELECT @BTypeId = BTypeId,@PosTime = PosTime FROM PD_SellBill WHERE BillNo = @BillNo
		
		;WITH TrailData AS(
								SELECT RANK() OVER (PARTITION BY GoodsID,UnitID,WhsID ORDER BY DID DESC)sort, GoodsID,UnitID,DID,Price,Discount FROM PD_SellDetail WHERE BillNo=@BillNo AND Gift=0)
								MERGE dbo.PD_PriceTrail AS target USING ( SELECT GoodsID,UnitID,Price,Discount FROM TrailData WHERE sort=1) AS source
								ON target.BtypeID=@BTypeID AND target.GoodsID=source.GoodsID AND target.UnitID=source.UnitID
								WHEN MATCHED THEN UPDATE SET target.SellDate=@PosTime,target.SellDis=SOURCE.Discount, target.SellPrice=SOURCE.Price
								WHEN NOT MATCHED BY TARGET THEN INSERT(BtypeID,GoodsID,UnitID,SellPrice,SellDis,SellDate)VALUES(@BTypeID,source.GoodsID,source.UnitID,source.Price,source.Discount,@PosTime);
	END
END

--PR_MdD9_DlyAccount过账调用判断捕捉错误修改：将RETURN的错误码-1依次修改为未占用错误码
--回写完成数量 包括订单和退货原单
/*
采购入库单
采购退货单
销售出库单
销售退货单
同价调拨单
变价调拨单
*/
IF @BillType IN (201,101,202,102,301,309)
BEGIN
	IF @BillType = 101
	BEGIN
		IF EXISTS(SELECT 1 FROM PD_PchOrdDetail D 
					INNER JOIN (SELECT OrdDID,SUM(BSQty) AS Qty FROM PD_PchDetail b WHERE BillNO=@BillNo  AND OrdDID>0 GROUP BY OrdDID) b
					ON d.DID=b.OrdDID WHERE d.ComQty+b.Qty>d.BsQty
				 )
			AND EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'BuyNotOverOrdQty' AND CfgValue = '1')
		BEGIN
			RAISERROR('单据数据超过订单数量',16,1)
			RETURN -16
		END
		
		;WITH BuySellQty AS (SELECT OrdDID,SUM(BSQty) AS Qty,SUM(TaxTotal) AS Total FROM PD_PchDetail WHERE BillNO=@BillNo  AND OrdDID>0 GROUP BY OrdDID)
                            UPDATE PD_PchOrdDetail SET ComQty+=q.Qty ,ComTotal+=q.Total FROM BuySellQty q WHERE q.OrdDID=PD_PchOrdDetail.DID                 
	END
	ELSE IF @BillType = 201
	BEGIN
		IF EXISTS(SELECT 1 FROM PD_SellOrdDetail D 
					INNER JOIN (SELECT OrdDID,SUM(BSQty) AS Qty FROM PD_SellDetail b WHERE BillNO=@BillNo  AND OrdDID>0 GROUP BY OrdDID) b
					ON d.DID=b.OrdDID WHERE d.ComQty+b.Qty>d.BsQty
				 )
			AND EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'SaleNotOverOrdQty' AND CfgValue = '1')
		BEGIN
			RAISERROR('单据数据超过订单数量',16,1)
			RETURN -16
		END 
		
		;WITH BuySellQty AS (SELECT OrdDID,SUM(BSQty) AS Qty,SUM(TaxTotal) AS Total FROM PD_SellDetail WHERE BillNO=@BillNo  AND OrdDID>0 GROUP BY OrdDID)
                            UPDATE PD_SellOrdDetail SET ComQty+=q.Qty ,ComTotal+=q.Total FROM BuySellQty q WHERE q.OrdDID=PD_SellOrdDetail.DID 	
	END
	ELSE IF @BillType = 102
	BEGIN
		IF EXISTS(SELECT 1 FROM PD_PchDetail D 
					INNER JOIN (SELECT PchDID,SUM(BSQty) AS Qty FROM PD_PchRetDetail b WHERE BillNO=@BillNo  AND PchDID>0 GROUP BY PchDID) b
					ON d.DID=b.PchDID WHERE d.ComQty+b.Qty>d.BsQty
				 )
		   AND EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'BuyBackNotOverBuyQty' AND CfgValue = '1')
		BEGIN
			RAISERROR('退货数据超过原单数量',16,1)
			RETURN -17
		END
		
		;WITH BuySellQty AS (SELECT PchDID,SUM(BSQty) AS Qty,SUM(TaxTotal) AS Total FROM PD_PchRetDetail WHERE BillNO=@BillNo  AND PchDID>0 GROUP BY PchDID)
                            UPDATE PD_PchDetail SET ComQty+=q.Qty ,ComTotal+=q.Total FROM BuySellQty q WHERE q.PchDID=PD_PchDetail.DID	
	END
	ELSE IF @BillType = 202
	BEGIN
		IF EXISTS(SELECT 1 FROM PD_SellDetail D 
					INNER JOIN (SELECT SellDID,SUM(BSQty) AS Qty FROM PD_SellRetDetail b WHERE BillNO=@BillNo  AND SellDID>0 GROUP BY SellDID) b
					ON d.DID=b.SellDID WHERE d.ComQty+b.Qty>d.BsQty
				 )
		   AND EXISTS(SELECT TOP 1 1 FROM dbo.SS_SysCfg WHERE CfgName = 'SaleBackNotOverSaleQty' AND CfgValue = '1')
		BEGIN
			RAISERROR('退货数据超过原单数量',16,1)
			RETURN -17
		END 	
		
		;WITH BuySellQty AS (SELECT SellDID,SUM(BSQty) AS Qty,SUM(TaxTotal) AS Total FROM PD_SellRetDetail WHERE BillNO=@BillNo  AND SellDID>0 GROUP BY SellDID)
                            UPDATE PD_SellDetail SET ComQty+=q.Qty ,ComTotal+=q.Total FROM BuySellQty q WHERE q.SellDID=PD_SellDetail.DID
	END
	ELSE IF @BillType IN (301,309)
	BEGIN
		;WITH AllotQty AS (SELECT ReqDID,SUM(InspectQty) AS Qty FROM PD_AllotDetail WHERE BillNO=@BillNo  AND ReqDID>0 GROUP BY ReqDID)
                            UPDATE PD_AllotReqDetail SET InspectQty+=q.Qty  FROM AllotQty q WHERE q.ReqDID=PD_AllotReqDetail.DID
	END
END

--处理结算状态
DECLARE @SettleState INT 

IF @BillType IN (101, 102, 201, 202, 401, 402, 403, 404, 405, 501, 502, 503, 504)
BEGIN
	SET @SettleState = 0
	
	SET @PayRecTotal = 0
	SET @BanlanceTotal = 0		
			
	IF @BillType = 101
		SELECT @PayRecTotal = PayRecTotal,@BanlanceTotal = Total - Privilege - PayRecTotal - 0 + 0 FROM PD_PchBill WHERE BillNo = @BillNo
	ELSE IF @BillType = 102	
		SELECT @PayRecTotal = PayRecTotal,@BanlanceTotal = Total - Privilege - PayRecTotal - 0 + 0 FROM PD_PchRetBill WHERE BillNo = @BillNo
	ELSE IF @BillType = 201	
		SELECT @PayRecTotal = PayRecTotal,@BanlanceTotal = Total - Privilege - PayRecTotal - 0 + 0 FROM PD_SellBill WHERE BillNo = @BillNo			
	ELSE IF @BillType = 202	
		SELECT @PayRecTotal = PayRecTotal,@BanlanceTotal = Total - Privilege - PayRecTotal - 0 + 0 FROM PD_SellRetBill WHERE BillNo = @BillNo			
	ELSE IF @BillType IN (401,402)
		SELECT @PayRecTotal = Total,@BanlanceTotal = Total - 0 - BPTotal + 0 FROM MF_PayRecBill WHERE BillNo = @BillNo	
	ELSE IF @BillType IN (403,404,405)
		SELECT @PayRecTotal = PayRecTotal,@BanlanceTotal = Total - 0 - PayRecTotal - 0 + 0 FROM MF_FeeRecBill WHERE BillNo = @BillNo		
	ELSE IF @BillType IN (501,502,503,504)
		SELECT @PayRecTotal = Total,@BanlanceTotal = Total - 0 - 0 - 0 + 0 FROM MF_ARAPBill WHERE BillNo = @BillNo		
	
	IF @PayRecTotal <> 0
		SET @SettleState = 1
	
	IF @BanlanceTotal = 0
		SET @SettleState = 2
		
	IF @BillType = 101
		UPDATE PD_PchBill SET StlTag=@SettleState WHERE BillNo=@BillNo
	ELSE IF @BillType = 102	
		UPDATE PD_PchRetBill SET StlTag=@SettleState WHERE BillNo=@BillNo
	ELSE IF @BillType = 201	
		UPDATE PD_SellBill SET StlTag=@SettleState WHERE BillNo=@BillNo
	ELSE IF @BillType = 202	
		UPDATE PD_SellRetBill SET StlTag=@SettleState WHERE BillNo=@BillNo
	ELSE IF @BillType IN (401,402)
		UPDATE MF_PayRecBill SET StlTag=@SettleState WHERE BillNo=@BillNo
	ELSE IF @BillType IN (403,404,405)
		UPDATE MF_FeeRecBill SET StlTag=@SettleState WHERE BillNo=@BillNo
	ELSE IF @BillType IN (501,502,503,504)
		UPDATE MF_ARAPBill SET StlTag=@SettleState WHERE BillNo=@BillNo
END

--销售出库单和采购入库单分为销售和运费两部分结算 101.采购入库单  201.销售出库单
IF @BillType IN (101,201) 
BEGIN		
	SET @SettleState = 0
	IF @FreightTotal <> 0
		SET @SettleState = 1
		
	IF @FreightTotal <> @Freight
		SET @SettleState = 2
		
	IF @BillType = 101
		UPDATE	PD_PchBill 
		SET		FreightStlTag=@SettleState 
		WHERE	BillNo=@BillNo
	ELSE		
		UPDATE	PD_SellBill 
		SET		FreightStlTag=@SettleState 
		WHERE	BillNo=@BillNo
END

--处理会员卡积分和储值金额 201.销售出库单，202.销售退货单
IF @VipCardID > 0 AND @BillType IN (201,202)
BEGIN	
	IF @VipChangeTotal <> 0
	BEGIN
		UPDATE	dbo.VS_VipCard 
		SET		TotalMoney = TotalMoney + @VipChangeTotal
		WHERE	VipCardID = @VipCardID
	END
	
	IF @VipChangeCent <>0
	BEGIN
		UPDATE	dbo.VS_VipCard 
		SET		CentBalance = CentBalance + @VipChangeCent,
				TotalCent = TotalCent + @VipChangeCent
		WHERE	VipCardID = @VipCardID
	END
END

--会员充值单处理会员储值
IF @BillType = 602
BEGIN
	UPDATE	VS_VipChargeDetail 
	SET		TotalBanlance=v.MoneyBalance
    FROM	VS_VipCard v 
    WHERE	v.VipCardID=VS_VipChargeDetail.VipCardID 
			AND BillNo=@BillNo
			
    UPDATE	dbo.VS_VipCard 
    SET		TotalStoreMoney+=a.total,
			Moneybalance+=a.total
    FROM	(
				SELECT	VipCardID,
						SUM(Total) total 
				FROM	dbo.VS_VipChargeDetail 
				WHERE	BillNo=@BillNo  
				GROUP BY VipCardID
			)a
    WHERE	a.VipCardID=VS_VipCard.VipCardID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_BatchStockQuery]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_PD_BatchStockQuery
GO

SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：sunzhiyuan
	日期：2016-03-04
	描述：批号库存查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_BatchStockQuery]
(
	@PageNo INT = 1,					-- 页码
	@PageSize INT = 10,					-- 页大小
	@WhsID VARCHAR(MAX) = '',         	-- 仓库
	@WhsTypeID INT = 0,					-- 仓库分类
	@SumLevel1 INT = 0,					-- 汇总级别
	@WhsPtNameMatch INT = 0,			-- 货位名称配置模式:0=包含,1=等于
	@WhsPtName VARCHAR(100) = '',		-- 货位名称
	@GoodsTypeID INT = 0,				-- 商品分类
	@GoodsNoMatch INT = 0,				-- 商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',			-- 商品编号
	@GoodsNameMatch INT = 0,			-- 商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',		-- 商品名称
	@OperatorID INT = 0,				-- 操作员ID
	--/*来自库存状况表的参数*/
	@GoodsID INT = 0,                   -- 商品ID
	@Spec VARCHAR(50) = '',             -- 规格
	@SpecMatch INT = 0,                 -- 规格匹配方式 0:包含 1:等于
	@SpecSum INT = 0,                   -- 规格
	@Model VARCHAR(50) = '',            -- 型号
	@ModelMatch INT = 0,                -- 型号匹配方式 0:包含 1:等于
	@ModelSum INT = 0,                  -- 型号
	@AbbName VARCHAR(50) = '',          -- 简名
	@AbbNameMatch INT = 0,              -- 简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',            -- 品牌
	@BrandMatch INT = 0,				-- 品牌匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',          -- 条码
	@BarCodeMatch INT = 0,              -- 条码匹配方式 0:包含 1:等于
	@BatchNumber VARCHAR(50) = '',      -- 批号
	@BatchNumberMatch INT = 0,          -- 批号匹配方式 0:包含 1:等于
	@ProductDateStart VARCHAR(25) = '', -- 生产日期范围起
	@ProductDateEnd VARCHAR(25) = '',   -- 生产日期范围始
	@EndDateStart VARCHAR(25) = '',     -- 到期日期范围起
	@EndDateEnd VARCHAR(25) = '',       -- 到期日期范围始
	@NearDateStart VARCHAR(25) = '',    -- 近效日期范围起
	@NearDateEnd VARCHAR(25) = '',      -- 近效日期范围始
	@SumOrNot INT = 1					-- 是否为合计
)
AS
BEGIN
SET NOCOUNT ON
	DECLARE @HeadSql NVARCHAR(MAX),@Sql NVARCHAR(MAX),@SqlParam NVARCHAR(MAX) = N'',
			@SqlInner NVARCHAR(MAX) = N'',@PageDataName NVARCHAR(MAX) = N'PagingData',@KtypeLimit INT = 0,
			@Sqlg NVARCHAR(MAX) = N''
	        
	----------------------------------查询条件----------------------------------
	SET @SqlParam='WHERE 1=1 '
	
	-- 仓库
	IF @WhsID <> ''
	BEGIN
		SET @SqlInner += ' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = GS.WhsID  '
	END
	
	-- 商品
	IF @GoodsID <> ''
	BEGIN
		SET @SqlInner += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _Goods ON _Goods.typeid = GS.GoodsID  '
	END
	ELSE
	BEGIN
		IF @Spec <> '' OR @SpecSum = 1  --商品规格(汇总时可能为空但是精确匹配)
		BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND Goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND Goods.Spec = @Spec '  
		END 
		IF @Model <> '' OR @ModelSum = 1      --商品型号(汇总时可能为空但是精确匹配)
		BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND Goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND Goods.Model = @Model ' 
		END 
		IF @AbbName <> ''    --商品简名
		BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND Goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND Goods.GoodsAbbName = @AbbName ' 
		END       
		IF @Brand <> ''      --商品品牌
		BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND Goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND Goods.Brand = @Brand ' 
		END
		IF @BarCode <> ''      --商品条码
		BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = Goods.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND barcode.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
		END
	END
	
	-- 货位
	IF @WhsPtName <> ''
	BEGIN
		-- 模糊查询
		IF @WhsPtNameMatch = 0
			SET @SqlParam += ' AND WHSPT.WhsPtName Like ''%'' + @WhsPtName + ''%'' '  
		-- 精确查询
		IF @WhsPtNameMatch = 1
			SET @SqlParam += ' AND WHSPT.WhsPtName = @WhsPtName '
	END
	
	-- 商品编号
	IF @GoodsNo <> ''
	BEGIN
		-- 模糊查询
		IF @GoodsNoMatch = 0
			SET @SqlParam += ' AND Goods.GoodsNo Like ''%''+@GoodsNo+''%'' '  
		-- 精确查询
		IF @GoodsNoMatch = 1
			SET @SqlParam += ' AND Goods.GoodsNo = @GoodsNo '  
	END
	
	-- 商品名称
	IF @GoodsName <> ''
	BEGIN
		-- 模糊查询
		IF @GoodsNameMatch = 0
			SET @SqlParam += ' AND Goods.GoodsName Like ''%''+@GoodsName+''%'' '  
		-- 精确查询
		IF @GoodsNameMatch = 1
			SET @SqlParam += ' AND Goods.GoodsName = @GoodsName '  
	END
	
	-- 批号
	IF @BatchNumber <> ''
	BEGIN
		-- 模糊查询
		IF @BatchNumberMatch = 0
			SET @SqlParam += ' AND detail.BatchNumber Like ''%''+@BatchNumber+''%'' '  
		-- 精确查询
		IF @BatchNumberMatch = 1
			SET @SqlParam += ' AND detail.BatchNumber = @BatchNumber '  
	END
	
	--生产日期范围
	IF @ProductDateStart <> '' AND @ProductDateEnd <> '' 
		SET @SqlParam += ' AND detail.ProductDate <> '''' AND detail.ProductDate BETWEEN CONVERT(DATE, @ProductDateStart) AND CONVERT(DATE, @ProductDateEnd) '
	
	--到期日期范围
	IF @EndDateStart <> '' AND @EndDateEnd <> '' 
		SET @SqlParam += ' AND detail.EndDate <> '''' AND detail.EndDate BETWEEN CONVERT(DATE, @EndDateStart) AND CONVERT(DATE, @EndDateEnd) '
	
	--近效日期范围
	IF @NearDateStart <> '' AND @NearDateEnd <> '' 
		SET @SqlParam += ' AND detail.EndDate <> '''' AND DATEADD(dd,-Goods.NearbyDays,CONVERT(DATE, detail.EndDate)) BETWEEN CONVERT(DATE, @NearDateStart) AND CONVERT(DATE, @NearDateEnd) '

	-- 商品类型
	IF @GoodsTypeID <> 0 AND @GoodsTypeID <> 1
	BEGIN
		SET @Sqlg += '
			_GoodsType AS(
				SELECT gt2.GoodsTypeID[typeid] 
				FROM BD_Goods_Type gt 
				INNER JOIN BD_Goods_Type gt2 ON gt2.[Path] LIKE gt.[Path]+''%'' 
				WHERE gt.GoodsTypeID = @GoodsTypeID AND gt2.Stt = 1 
				GROUP BY gt2.GoodsTypeID
			)
			,Goods AS(
				SELECT * FROM BD_Goods g 
				INNER JOIN _GoodsType ON _GoodsType.typeid = g.GoodsTypeID ) '
	END
	ELSE
	BEGIN
		SET @Sqlg += ' Goods AS(SELECT * FROM BD_Goods g  WHERE 1 = 1) '
	END

	-- 仓库类型
	IF @SumLevel1 <> 0 AND @SumLevel1 <> 1 AND @WhsTypeID <> 0
	BEGIN
		SET @Sqlg += '
			,_WHSType AS(
				SELECT wt2.WhsTypeID[typeid] 
				FROM BD_Whs_Type wt 
				INNER JOIN BD_Whs_Type wt2 ON wt2.[Path] LIKE wt.[Path]+''%'' 
				WHERE wt.WhsTypeID = @WhsTypeID AND wt2.Stt = 1 
				GROUP BY wt2.WhsTypeID
			)
			,WHS AS(
				SELECT * FROM BD_Whs w 
				INNER JOIN _WHSType ON _WHSType.typeid = w.WhsTypeID ) '
		SET @SqlInner += ' INNER JOIN WHS WHSType ON GS.WhsID = WHSType.WhsID '
	END

	/*权限使用公用方法*/
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF @KtypeLimit = 1 --部份权限
	   SET @SqlInner +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = WHS.WhsID '

	-- 仓库编号,仓库名称;
	-- 仓位编号,仓位名称;
	-- 商品编号,商品名称;
	-- 属性一,属性二;
	SET @HeadSql = N';With ' + @Sqlg +' ,PagingData AS (
						 SELECT WHS.WhsID, WHS.WhsNO,WHS.WhsName,
								WHSPT.WhsPtID,WHSPT.WhsPtNO,WHSPT.WhsPtName,
								Goods.GoodsID,Goods.GoodsNo,Goods.GoodsName,
								detail.Ppt1ID,GP1.Value AS Spec1,detail.Ppt2ID,GP2.Value AS Spec2,
								detail.BatchNumber,detail.ProductDate, detail.EndDate, CASE WHEN Goods.CostMethod = 1 THEN gs.Price
								ELSE detail.CostPrice END AS CostPrice,detail.Qty
								FROM PD_GoodsStock GS  
									INNER JOIN PD_GoodsStock_Detail detail ON GS.StockID = detail.StockID AND gs.GoodsID = detail.GoodsID
									INNER jOIN BD_Whs WHS ON GS.WhsID = WHS.WhsID
									LEFT JOIN BD_Whs_Position WHSPT ON detail.WhsPtID = WHSPT.WhsPtID
									INNER JOIN Goods Goods ON GS.GoodsID = Goods.GoodsID
									LEFT JOIN BD_Goods_Ppt1 GP1 ON detail.Ppt1ID = GP1.Ppt1ID
									LEFT JOIN BD_Goods_Ppt2 GP2 ON detail.Ppt2ID = GP2.Ppt2ID
					'
					
	-- 组合SQL代码块
    SET @Sql = @HeadSql + @SqlInner + @SqlParam 
    
    -- 合计处理
    IF @SumOrNot = 0
    BEGIN
		-- 分页
		SET @Sql+=' ) SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
					CROSS JOIN
					(SELECT	ROW_NUMBER() OVER( ORDER BY GoodsNo ) AS ROWID,* FROM PagingData) B
					WHERE B.ROWID > (@PageNo - 1) * @PageSize AND B.ROWID <= @PageNo * @PageSize '
	END
	IF @SumOrNot = 1
	BEGIN
		SET @Sql+=' ) SELECT SUM(A.Qty)[Qty] FROM PagingData A '
	END
	-- 没有权限
	IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
	
	print @Sql
	
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @WhsID VARCHAR(100), @WhsTypeID INT,@SumLevel1 INT,@WhsPtNameMatch INT, @WhsPtName VARCHAR(100),@GoodsID INT,
							   @Spec VARCHAR(50), @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100),
	                           @GoodsTypeID INT, @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),@OperatorID INT, 
	                           @BatchNumber VARCHAR(50), @BatchNumberMatch VARCHAR(50),@ProductDateStart VARCHAR(25), @ProductDateEnd VARCHAR(25),
	                           @EndDateStart VARCHAR(25), @EndDateEnd VARCHAR(25), @NearDateStart VARCHAR(25), @NearDateEnd VARCHAR(25)', 
							 @PageNo, @PageSize, @WhsID, @WhsTypeID, @SumLevel1,@WhsPtNameMatch, @WhsPtName,@GoodsID,
							 @Spec, @Model, @AbbName, @Brand, @BarCode,
							 @GoodsTypeID, @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName,@OperatorID,
	                         @BatchNumber,@BatchNumberMatch, @ProductDateStart, @ProductDateEnd,
	                         @EndDateStart, @EndDateEnd, @NearDateStart, @NearDateEnd
END

GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_BatchTrack]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_PD_BatchTrack
GO

SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：wubin
	日期：2016-03-03
	描述：批次跟踪查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_BatchTrack]
(
	@PageNo INT = 1,					-- 页码
	@PageSize INT = 10,					-- 页大小
	@BillStartDate DATETIME,			-- 起始时间
	@BillEndDate DATETIME,				-- 截止时间
	@WhsID VARCHAR(MAX) = '',			-- 仓库ID
	@GoodsTypeID INT = 0,				-- 商品分类
	@BtypeID VARCHAR(MAX) = '',			-- 往来单位ID
	@DeptID  VARCHAR(MAX) = '',			-- 部门ID
	@ElyID VARCHAR(MAX) = '',			-- 经手人ID
	@WhsPtNameMatch INT = 0,			-- 货位名称配置模式:0=包含,1=等于
	@WhsPtName VARCHAR(100) = '',		-- 货位名称
	@GoodsNoMatch INT = 0,				-- 商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',			-- 商品编号
	@GoodsNameMatch INT = 0,			-- 商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',		-- 商品名称
	@BillType INT = 1,					-- 单据类型
	@BatchNo VARCHAR(50) = '',          -- 批号
	@BatchNoMatch INT = 0,              -- 批号匹配方式 0:包含 1:等于
	@ProductDateStart VARCHAR(25) = '', -- 生产日期范围起
	@ProductDateEnd VARCHAR(25) = '',   -- 生产日期范围始
	@EndDateStart VARCHAR(25) = '',     -- 到期日期范围起
	@EndDateEnd VARCHAR(25) = '',       -- 到期日期范围始
	@NearDateStart VARCHAR(25) = '',    -- 近效日期范围起
	@NearDateEnd VARCHAR(25) = '',      -- 近效日期范围始
	-- 来自批次库存查询的参数 START
	@GoodsID INT = 0,                   -- 商品ID
	@Ppt1ID INT = 0,                    -- 属性1ID
	@Ppt2ID INT = 0,                    -- 属性2ID
	@ProductDate VARCHAR(25) = '',      -- 生产日期
	@EndDate VARCHAR(25) = '',          -- 到期日期
	@CostPrice DECIMAL(20,8) = 0,       -- 成本单价 
	-- END
	@OperatorID INT = 0,				-- 操作员
	@IsHistory INT = 0					-- 是否包含归档数据
)
AS
BEGIN
SET NOCOUNT ON

DECLARE @Re INT 
EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @BillStartDate, @isHistory = @IsHistory
IF @Re = 1 RETURN @Re;
DECLARE @JoinSql VARCHAR(MAX) = '', @WhereSql VARCHAR(MAX) = '', @Sql NVARCHAR(MAX) = '', @Cols VARCHAR(2000)= '',
        @BaseSql VARCHAR(MAX) = '', @BaseJoinSql VARCHAR(MAX) = '', @KtypeLimit INT,  @BtypeLimit INT,
        @InspectTagSql VARCHAR(100) = '', @JoinInSql VARCHAR(MAX) = '', @JoinOutSql VARCHAR(MAX) = '',
        @JoinExceptSql VARCHAR(MAX) = '', @WhereExceptSql VARCHAR(MAX) = '', @JoinInWptSql VARCHAR(MAX) = '', 
        @JoinOutWptSql VARCHAR(MAX) = '', @JoinOpenSql VARCHAR(MAX) = '', @WhereOpenSql VARCHAR(MAX) = '',
        @WhereInSql VARCHAR(MAX) = '', @WhereOutSql VARCHAR(MAX) = '', @CostPriceParam VARCHAR(2000) = ''
DECLARE @TVP_GoodsType AS [TVP_Type], @TVP_Dept AS [TVP_Type]

-- 判断是否启用调拨验证
IF EXISTS(SELECT 1 FROM SS_SysCfg WHERE CfgName='AllotWithInspect' AND CfgValue = 1) 
	SET @InspectTagSql += ' AND InspectTag = 1 '
	
SET @JoinSql += N' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = detail.GoodsID '
SET @Cols += ' ,goods.GoodsNo ,goods.GoodsName '

-- 商品分类	
IF @GoodsTypeID  <> 0     
   BEGIN
     SET @JoinSql +=' INNER JOIN @TVP_GoodsType goodsType ON goodsType.ChildTypeID = goods.GoodsTypeID '
     INSERT INTO @TVP_GoodsType([TypeID],[ChildTypeID]) 
     SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM  BD_Goods_Type gt
         INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
	     WHERE gt.GoodsTypeID = @GoodsTypeID AND cgt.SonNum = 0
   END

-- 商品ID
IF @GoodsID <> 0
BEGIN
	SET @WhereSql += N' AND detail.GoodsID = @GoodsID AND detail.Ppt1ID = @Ppt1ID AND detail.Ppt2ID = @Ppt2ID 
	                    AND detail.ProductDate = @ProductDate AND detail.EndDate = @EndDate AND detail.BatchNumber = @BatchNo '
	SET @CostPriceParam += N' AND detail.CostPrice = CASE WHEN goods.CostMethod = 1 THEN detail.CostPrice ELSE @CostPrice END ' 
END

-- 商品编号 	     							
IF @GoodsNo <> ''   
BEGIN 
   IF @GoodsNoMatch = 0
	   SET @WhereSql += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
   ELSE IF @GoodsNoMatch = 1
	   SET @WhereSql += N' AND goods.GoodsNo = @GoodsNo ' 
END

-- 商品名称   
IF @GoodsName <> ''  
BEGIN 
   IF @GoodsNameMatch = 0
	   SET @WhereSql += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
   ELSE IF @GoodsNameMatch = 1
	   SET @WhereSql += N' AND goods.GoodsName = @GoodsName ' 
END
	
-- 批号
IF @BatchNo <> '' AND @GoodsID = 0
BEGIN
	-- 模糊查询
	IF @BatchNoMatch = 0
		SET @WhereSql += ' AND detail.BatchNumber Like ''%''+@BatchNo+''%'' '  
	-- 精确查询
	IF @BatchNoMatch = 1
		SET @WhereSql += ' AND detail.BatchNumber = @BatchNo '  
END

-- 生产日期范围
IF @ProductDateStart <> '' AND @ProductDateEnd <> '' 
	SET @WhereSql += ' AND detail.ProductDate <> '''' AND detail.ProductDate BETWEEN CONVERT(DATE, @ProductDateStart) AND CONVERT(DATE, @ProductDateEnd) '

-- 到期日期范围
IF @EndDateStart <> '' AND @EndDateEnd <> '' 
	SET @WhereSql += ' AND detail.EndDate <> '''' AND detail.EndDate BETWEEN CONVERT(DATE, @EndDateStart) AND CONVERT(DATE, @EndDateEnd) '

-- 近效日期范围
IF @NearDateStart <> '' AND @NearDateEnd <> '' 
	SET @WhereSql += ' AND detail.EndDate <> '''' AND DATEADD(dd,-goods.NearbyDays,CONVERT(DATE, detail.EndDate)) BETWEEN CONVERT(DATE, @NearDateStart) AND CONVERT(DATE, @NearDateEnd) '

-- 期初的条件不含部门和经手人
SET @JoinOpenSql = @JoinSql
SET @WhereOpenSql = ' WHERE 1 = 1 ' + @WhereSql
SET @WhereSql = ' WHERE bill.BillDate BETWEEN @BillStartDate AND @BillEndDate And bill.IsDraft = 0 ' + @WhereSql

-- 部门  
IF @DeptID <> ''     
   BEGIN
     SET @JoinSql +=' INNER JOIN @TVP_Dept dept ON dept.ChildTypeID = bill.DeptID '
     INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
     SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
         INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
	     WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') dept WHERE dept.typeid = d.DeptID)
	 -- 其实不含部门
	 SET @WhereOpenSql = ' WHERE 1 <> 1 '
   END

-- 经手人	   
IF @ElyID <> ''   
BEGIN
	IF OBJECT_ID('tempdb..#BatchTrackElyTmp', 'U') IS NOT NULL
    DROP TABLE #BatchTrackElyTmp
    CREATE TABLE #BatchTrackElyTmp(typeid INT)
    INSERT INTO #BatchTrackElyTmp SELECT typeid FROM dbo.UF_OT_Split_Int(@ElyID, ',')
	SET @JoinSql += ' INNER JOIN #BatchTrackElyTmp emp ON emp.typeid = bill.ElyID '
	-- 其实不含经手人
    SET @WhereOpenSql = ' WHERE 1 <> 1'
END

-- 后处理往来单位和仓库条件、货位，因有出入库且有些单据没有往来单位
SET @JoinInSql = @JoinSql  
SET @JoinOutSql = @JoinSql    
SET @JoinExceptSql = @JoinSql 
SET @WhereExceptSql = @WhereSql
-- 往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
BEGIN
	IF OBJECT_ID('tempdb..#BatchTrackBLimitTmp', 'U') IS NOT NULL
    DROP TABLE #BatchTrackBLimitTmp
    CREATE TABLE #BatchTrackBLimitTmp(BTypeID INT)
    INSERT INTO #BatchTrackBLimitTmp SELECT BTypeID FROM dbo.UF_BD_BtypeLimit(@OperatorID)
	SET @JoinSql += ' INNER JOIN #BatchTrackBLimitTmp rBtype ON rBtype.BTypeID = bill.BTypeID '
END 

-- 往来单位        
IF @BTypeID <> ''
BEGIN
	IF OBJECT_ID('tempdb..#BatchTrackBtypeTmp', 'U') IS NOT NULL
    DROP TABLE #BatchTrackBtypeTmp
    CREATE TABLE #BatchTrackBtypeTmp(typeid INT)
    INSERT INTO #BatchTrackBtypeTmp SELECT typeid FROM dbo.UF_OT_Split_Int(@BTypeID, ',')
	SET @JoinSql += ' INNER JOIN #BatchTrackBtypeTmp _BType ON _BType.typeid = bill.BTypeID '
    -- 没有往来单位的单据直接筛掉
    SET @WhereExceptSql = ' WHERE 1 <> 1'
    -- 期初不含往来单位
    SET @WhereOpenSql = ' WHERE 1 <> 1'
END

-- 仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)

IF @KtypeLimit = 1  --部份权限
BEGIN
	IF OBJECT_ID('tempdb..#BatchTrackKLimitTmp', 'U') IS NOT NULL
    DROP TABLE #BatchTrackKLimitTmp
    CREATE TABLE #BatchTrackKLimitTmp(WhsID INT)
    INSERT INTO #BatchTrackKLimitTmp SELECT WhsID FROM UF_BD_KtypeLimit(@OperatorID)
	SET @JoinSql += ' INNER JOIN #BatchTrackKLimitTmp rWhs ON rWhs.WhsID = bill.WhsID '
	SET @JoinExceptSql += ' INNER JOIN #BatchTrackKLimitTmp rWhs ON rWhs.WhsID = bill.WhsID '
	SET @JoinInSql += ' INNER JOIN #BatchTrackKLimitTmp rWhs ON rWhs.WhsID = bill.InWhsID '
	SET @JoinOutSql += ' INNER JOIN #BatchTrackKLimitTmp rWhs ON rWhs.WhsID = bill.OutWhsID '
	SET @JoinOpenSql += ' INNER JOIN #BatchTrackKLimitTmp rWhs ON rWhs.WhsID = bill.WhsID '
END
		
-- 仓库
IF @WhsID <> ''
BEGIN
	IF OBJECT_ID('tempdb..#BatchTrackKtypeTmp', 'U') IS NOT NULL
    DROP TABLE #BatchTrackKtypeTmp
    CREATE TABLE #BatchTrackKtypeTmp(typeid INT)
    INSERT INTO #BatchTrackKtypeTmp SELECT typeid FROM  dbo.UF_OT_Split_Int(@WhsID, ',')
	SET @JoinSql += ' INNER JOIN #BatchTrackKtypeTmp whs ON whs.typeid = bill.WhsID '
	SET @JoinExceptSql += ' INNER JOIN #BatchTrackKtypeTmp whs ON whs.typeid = bill.WhsID '
	SET @JoinInSql += ' INNER JOIN #BatchTrackKtypeTmp whs ON whs.typeid = bill.InWhsID '
	SET @JoinOutSql += ' INNER JOIN #BatchTrackKtypeTmp whs ON whs.typeid = bill.OutWhsID '
	SET @JoinOpenSql += ' INNER JOIN #BatchTrackKtypeTmp whs ON whs.typeid = bill.WhsID '
END   

SET @JoinInWptSql = @JoinInSql
SET @JoinOutWptSql = @JoinOutSql

-- 货位名称 							
IF @WhsPtName <> ''   
BEGIN 
   SET @JoinSql += N' INNER JOIN dbo.BD_Whs_Position whsPt ON whsPt.WhsPtID = detail.WhsPtID '
   SET @JoinExceptSql += N' INNER JOIN dbo.BD_Whs_Position whsPt ON whsPt.WhsPtID = detail.WhsPtID '
   SET @JoinInSql += N' INNER JOIN dbo.BD_Whs_Position whsPt ON whsPt.WhsPtID = detail.WhsPtID '
   SET @JoinOutSql += N' INNER JOIN dbo.BD_Whs_Position whsPt ON whsPt.WhsPtID = detail.WhsPtID '
   SET @JoinInWptSql += ' INNER JOIN dbo.BD_Whs_Position whsPt ON whsPt.WhsPtID = detail.InWhsPtID '
   SET @JoinOutWptSql += ' INNER JOIN dbo.BD_Whs_Position whsPt ON whsPt.WhsPtID = detail.OutWhsPtID '
   SET @JoinOpenSql += ' INNER JOIN dbo.BD_Whs_Position whsPt ON whsPt.WhsPtID = detail.WhsPtID '
   SET @Cols += ' ,whsPt.WhsPtNO ,whsPt.WhsPtName '
   IF @WhsPtNameMatch = 0
   BEGIN
	   SET @WhereSql += N' AND whsPt.WhsPtName LIKE ''%'' + @WhsPtName +''%'''
	   SET @WhereOpenSql += N' AND whsPt.WhsPtName LIKE ''%'' + @WhsPtName +''%'''
   END
   ELSE IF @WhsPtNameMatch = 1
   BEGIN
	   SET @WhereSql += N' AND whsPt.WhsPtName = @WhsPtName ' 
	   SET @WhereOpenSql += N' AND whsPt.WhsPtName = @WhsPtName ' 
   END
END
ELSE
BEGIN
	SET @BaseSql += ' , whsPtData AS (SELECT WhsPtID AS wptID, WhsPtNO, WhsPtName FROM dbo.BD_Whs_Position) '
	SET @BaseJoinSql += ' LEFT JOIN whsPtData ON whsPtData.wptID = DATA.WhsPtID '
END 
SET @WhereInSql = @WhereExceptSql
SET @WhereOutSql = @WhereExceptSql

IF @GoodsID <> 0
	SET @WhereOpenSql += @CostPriceParam

-- 单据类型(全部1 入库2 出库3 红冲4) 
IF OBJECT_ID('tempdb..#BatchTrackTmp', 'U') IS NOT NULL
    DROP TABLE #BatchTrackTmp
CREATE TABLE #BatchTrackTmp(BillTypeID VARCHAR(5), BillName VARCHAR(50), BillTable VARCHAR(50), BillDetail VARCHAR(50), InOutType INT)
IF @BillType = 1 OR @BillType = 4		
	INSERT INTO #BatchTrackTmp SELECT BillTypeID, BillName, BillTable, BillDetail, InOutType FROM PD_BillType WHERE CanPost = 1 AND InOutType <> 0
ELSE IF @BillType = 2
	INSERT INTO #BatchTrackTmp SELECT BillTypeID, BillName, BillTable, BillDetail, InOutType FROM PD_BillType WHERE CanPost = 1 AND (InOutType = 1 OR InOutType = 3) 
ELSE
	INSERT INTO #BatchTrackTmp SELECT BillTypeID, BillName, BillTable, BillDetail, InOutType FROM PD_BillType WHERE CanPost = 1 AND (InOutType = 2 OR InOutType = 3)
-- 红冲
IF @BillType = 4
BEGIN
	SET @WhereSql += ' AND bill.Red <> 0 '
	SET @WhereExceptSql += ' AND bill.Red <> 0 '
    SET @WhereInSql += N' AND bill.Red <> 0 '
    SET @WhereOutSql += N' AND bill.Red <> 0 '
END
ELSE IF @BillType <> 1
BEGIN
	SET @WhereSql += ' AND bill.Red = 0 '
	SET @WhereExceptSql += ' AND bill.Red = 0 '
    SET @WhereInSql += N' AND bill.Red = 0 '
    SET @WhereOutSql += N' AND bill.Red = 0 '
END

-- 没有往来单位权限，筛掉含有往来单位的单据（保留其他出入库，往来单位非必填)
IF @BtypeLimit = 0
	DELETE FROM #BatchTrackTmp WHERE InOutType <> 3 AND BillTypeID <> 303 AND BillTypeID <> 304 AND BillTypeID <> 305 AND BillTypeID <> 306 

-- 单出入库类型的：报损报溢没有往来单位，其他出入积分兑换、报损报溢需要单据类型条件
SELECT @Sql += N'UNION ALL (SELECT '''+BillName+''' AS BillName, '+BillTypeID+' AS BillTypeID, bill.BillNo, bill.BillCode, bill.DeptID, 
                            bill.ElyID, bill.PosTime, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.BatchNumber, detail.ProductDate,
                            detail.EndDate, bill.Red, detail.BSQty AS Qty, detail.CostPrice, bill.WhsID, detail.WhsPtID, ' +
                            CASE WHEN BillTypeID IN (305,306) THEN ' 0 ' ELSE ' bill.BTypeID ' END + ' AS BTypeID ' + @Cols +
                            ' FROM '+BillTable+' bill INNER JOIN '+BillDetail+' detail ON bill.BillNo = detail.BillNo ' + 
                            CASE WHEN BillTypeID IN (305,306) THEN @JoinExceptSql + @WhereExceptSql ELSE @JoinSql + @WhereSql END + 
                            CASE WHEN BillTypeID IN (303,304,305,306,600) THEN ' AND bill.BillTypeID = ' + BillTypeID ELSE '' END + 
                            CASE WHEN BillTypeID IN (303,304) AND @BtypeLimit = 0 THEN ' AND bill.BTypeID = 0 ' ELSE '' END + @CostPriceParam + ' ) '
FROM #BatchTrackTmp WHERE InOutType <> 3

-- 出入库类型的：都没有往来单位，调价单只有仓库，调拨单明细有出入库的货位、且需判断调拨验收和单据类型，生产拆装单明细区分出入库
-- 变价调拨入库、调价单入库成本价需计算分开统计手工指定和移动加权                  
SELECT @Sql += CASE WHEN @BillType <> 3 THEN 
             N'UNION ALL (SELECT '''+BillName+'''+''(入库)'' AS BillName, '+BillTypeID+' AS BillTypeID, bill.BillNo, bill.BillCode, bill.DeptID, 
                          bill.ElyID, bill.PosTime, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.BatchNumber, detail.ProductDate, 
                          detail.EndDate, bill.Red, detail.BSQty AS Qty, '+
						  CASE WHEN BillTypeID = 302 THEN ' CAST((detail.AdjTotal/detail.BSQty) AS DECIMAL(20,8)) AS CostPrice, ' 
							   WHEN BillTypeID = 309 THEN ' CAST((detail.AllotTotal/detail.BSQty) AS DECIMAL(20,8)) AS CostPrice, ' 
						       ELSE ' detail.CostPrice, ' END  +
						  CASE WHEN BillTypeID = 302 THEN ' bill.WhsID, ' ELSE ' bill.InWhsID AS WhsID, ' END  +
						  CASE WHEN BillTypeID = 301 OR BillTypeID = 309 THEN ' detail.InWhsPtID AS WhsPtID, ' ELSE ' detail.WhsPtID, ' END  + ' 0 AS BTypeID ' + @Cols +
						  ' FROM '+BillTable+' bill INNER JOIN '+BillDetail+' detail ON bill.BillNo = detail.BillNo ' + 
						  CASE WHEN BillTypeID = 302 THEN @JoinExceptSql + @WhereExceptSql WHEN BillTypeID = 301 OR BillTypeID = 309 THEN @JoinInWptSql + @WhereInSql ELSE @JoinInSql + @WhereExceptSql END +
						  CASE WHEN BillTypeID = 310 THEN ' AND detail.DetailType = 1 ' ELSE '' END + 
						  CASE WHEN BillTypeID = 301 OR BillTypeID = 309 THEN @InspectTagSql + ' AND bill.BillTypeID = ' + BillTypeID ELSE '' END + @CostPriceParam +
						  CASE WHEN @GoodsID <> 0 AND (BillTypeID = 302 OR BillTypeID = 309) THEN ' AND goods.CostMethod = 1 ' ELSE ' ' END  + ' ) '
				ELSE '' END + 
				CASE WHEN @GoodsID <> 0 AND @BillType <> 3 AND (BillTypeID = 302 OR BillTypeID = 309) THEN 
             N'UNION ALL (SELECT '''+BillName+'''+''(入库)'' AS BillName, '+BillTypeID+' AS BillTypeID, bill.BillNo, bill.BillCode, bill.DeptID, 
                          bill.ElyID, bill.PosTime, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.BatchNumber, detail.ProductDate, 
                          detail.EndDate, bill.Red, detail.BSQty AS Qty, '+
						  CASE WHEN BillTypeID = 302 THEN ' CAST((detail.AdjTotal/detail.BSQty) AS DECIMAL(20,8)) AS CostPrice, bill.WhsID, detail.WhsPtID, ' 
						       ELSE ' CAST((detail.AllotTotal/detail.BSQty) AS DECIMAL(20,8)) AS CostPrice, bill.InWhsID AS WhsID, detail.InWhsPtID AS WhsPtID, ' END  + ' 0 AS BTypeID ' + @Cols +
						  ' FROM '+BillTable+' bill INNER JOIN '+BillDetail+' detail ON bill.BillNo = detail.BillNo ' + 
						  CASE WHEN BillTypeID = 302 THEN @JoinExceptSql + @WhereExceptSql ELSE @JoinInWptSql + @WhereInSql + @InspectTagSql + ' AND bill.BillTypeID = ' + BillTypeID END + 
						  ' AND goods.CostMethod = 2 ' + 
						  CASE WHEN BillTypeID = 302 THEN ' AND CAST((detail.AdjTotal/detail.BSQty) AS DECIMAL(20,8)) = @CostPrice ' ELSE ' AND CAST((detail.AllotTotal/detail.BSQty) AS DECIMAL(20,8)) = @CostPrice ' END + ' ) '
				ELSE '' END + 
				CASE WHEN @BillType <> 2 THEN
			  'UNION ALL (SELECT '''+BillName+'''+''(出库)'' AS BillName, '+BillTypeID+' AS BillTypeID, bill.BillNo, bill.BillCode, bill.DeptID, 
                          bill.ElyID, bill.PosTime, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.BatchNumber, detail.ProductDate, 
                          detail.EndDate, bill.Red, detail.BSQty AS Qty, detail.CostPrice, '+
						  CASE WHEN BillTypeID = 302 THEN ' bill.WhsID, ' ELSE ' bill.OutWhsID AS WhsID, ' END  +
						  CASE WHEN BillTypeID = 301 OR BillTypeID = 309 THEN ' detail.OutWhsPtID AS WhsPtID, ' ELSE ' detail.WhsPtID, ' END  + ' 0 AS BTypeID ' + @Cols +
						  ' FROM '+BillTable+' bill INNER JOIN '+BillDetail+' detail ON bill.BillNo = detail.BillNo ' + 
						  CASE WHEN BillTypeID = 302 THEN @JoinExceptSql + @WhereExceptSql WHEN BillTypeID = 301 OR BillTypeID = 309 THEN @JoinOutWptSql + @WhereOutSql ELSE @JoinOutSql + @WhereExceptSql END + 
						  CASE WHEN BillTypeID = 310 THEN ' AND detail.DetailType = 2 ' ELSE '' END + 
						  CASE WHEN BillTypeID = 301 OR BillTypeID = 309 THEN @InspectTagSql + ' AND bill.BillTypeID = ' + BillTypeID ELSE '' END + @CostPriceParam + ' ) '
				ELSE '' END 
FROM #BatchTrackTmp WHERE InOutType = 3

IF @IsHistory = 1
	SET @Sql = @Sql + REPLACE(REPLACE(@Sql, ' bill INNER JOIN', '_His bill INNER JOIN'), ' detail ON', '_His detail ON') 

-- 是否查询期初数据(单据类型为全部才显示期初)
IF EXISTS(SELECT 1 FROM dbo.SS_MonthProc WHERE Period = 1 AND StartDate BETWEEN @BillStartDate AND @BillEndDate) AND @BillType = 1
BEGIN
	SELECT @Sql += N'UNION ALL (SELECT ''期初数据'' AS BillName, 999 AS BillTypeID, 0 AS BillNo, '''' AS BillCode, 0 AS DeptID, 
	                            0 AS ElyID, '''' AS PosTime, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.BatchNumber, detail.ProductDate, 
	                            detail.EndDate, 0 AS Red, detail.Qty, CASE WHEN goods.CostMethod = 1 THEN bill.Price ELSE detail.CostPrice END AS CostPrice, bill.WhsID, detail.WhsPtID, 0 AS BTypeID ' + @Cols + 
	                            ' FROM dbo.BD_OpeningStock bill INNER JOIN dbo.BD_OpeningStock_Detail detail ON bill.StockID = detail.StockID ' + @JoinOpenSql + @WhereOpenSql + ' ) '
END

SET @BaseSql += ' , whs AS (SELECT WhsID AS wID, WhsNO, WhsName FROM dbo.BD_Whs) 
                  , btype AS (SELECT BTypeID AS bID, BTypeCode, BTypeName FROM dbo.BD_Btype)
                  , dept AS (SELECT DeptID AS dID, DeptCode, DeptName FROM dbo.BD_Dept)
                  , ely AS (SELECT ElyID AS eID, ElyCode, ElyName FROM dbo.BD_Employee)
                  , ppt1 AS (SELECT Ppt1ID AS p1ID, Value AS Ppt1Value FROM dbo.BD_Goods_Ppt1)
                  , ppt2 AS (SELECT Ppt2ID AS p2ID, Value AS Ppt2Value FROM dbo.BD_Goods_Ppt2) '
SET @BaseJoinSql += ' LEFT JOIN whs ON whs.wID = DATA.WhsID 
                      LEFT JOIN btype ON btype.bID = DATA.BTypeID 
                      LEFT JOIN dept ON dept.dID = DATA.DeptID 
                      LEFT JOIN ely ON ely.eID = DATA.ElyID 
                      LEFT JOIN ppt1 ON ppt1.p1ID = DATA.Ppt1ID 
                      LEFT JOIN ppt2 ON ppt2.p2ID = DATA.Ppt2ID '

SET @Sql = N' SET NOCOUNT ON; 
           ;WITH PagingData AS (' + SUBSTRING(@Sql, 10, LEN(@Sql)-9) + ' ) ' +
           N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A CROSS JOIN
						(SELECT ROW_NUMBER() OVER(ORDER BY GoodsNo, Ppt1ID, Ppt2ID, BatchNumber, ProductDate, EndDate, CostPrice, PosTime) AS ROWID, * FROM PagingData) B
						WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize) ' + @BaseSql +
			 ' SELECT * FROM DATA ' + @BaseJoinSql
-- 没有仓库权限
IF @KtypeLimit = 0
	SET @Sql = N' SELECT * FROM dbo.PD_BillType WHERE 1 <> 1'

EXEC sp_executesql @Sql,N'@PageNo Int, @PageSize Int, @BillStartDate DATETIME, @BillEndDate DATETIME, @GoodsTypeID INT, @WhsID VARCHAR(MAX), @BtypeID VARCHAR(MAX), @DeptID  VARCHAR(MAX),
						  @ElyID VARCHAR(MAX), @WhsPtNameMatch INT, @WhsPtName VARCHAR(100), @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),
						  @BatchNo VARCHAR(50), @ProductDateStart VARCHAR(25), @ProductDateEnd VARCHAR(25),
	                      @EndDateStart VARCHAR(25), @EndDateEnd VARCHAR(25), @NearDateStart VARCHAR(25), @NearDateEnd VARCHAR(25),
						  @OperatorID INT, @IsHistory INT, @TVP_GoodsType TVP_Type READONLY, @TVP_Dept TVP_Type READONLY,
						  @GoodsID INT, @Ppt1ID INT, @Ppt2ID INT, @ProductDate VARCHAR(25), @EndDate VARCHAR(25),
						  @CostPrice DECIMAL(20, 8)',
						  @PageNo, @PageSize, @BillStartDate, @BillEndDate, @GoodsTypeID, @WhsID, @BtypeID, @DeptID,
						  @ElyID, @WhsPtNameMatch, @WhsPtName, @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName,
						  @BatchNo, @ProductDateStart, @ProductDateEnd, @EndDateStart, @EndDateEnd, @NearDateStart, @NearDateEnd,
						  @OperatorID, @IsHistory, @TVP_GoodsType, @TVP_Dept, @GoodsID, @Ppt1ID, @Ppt2ID, @ProductDate, @EndDate, @CostPrice
			
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_BuyBackList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_BuyBackList]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2014-07-09
	描述：采购退货统计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_BuyBackList]
(
	@PageNo INT=0,	
	@PageSize INT=0,	
	@DateType TINYINT=0,	/*日期类型 0-录单日期 1-制单日期 2-过账日期*/
	@BeginDate DATE,	/*开始日期*/
	@EndDate DATE,	/*结束日期*/
	@BTypeID VARCHAR(MAX)='',	/*往来单位*/
	@DeptID VARCHAR(MAX)='',	/*部门*/
	@ElyID VARCHAR(MAX)='',		/*经手人*/
	@CreatorID VARCHAR(MAX)='', /*制单人*/
	@WhsID VARCHAR(MAX)='',		/*仓库*/
	@GoodsNo VARCHAR(50)='',	/*商品编号*/
	@GoodsNoMatch BIT = 0,
	@GoodsName VARCHAR(100)='',		/*商品名称*/
	@GoodsNameMatch BIT = 0,
	@Model VARCHAR(50) = '',               --型号
	@ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	@Summary VARCHAR(256)='',		/*摘要*/
	@SummaryMatch BIT = 0,
	@Description VARCHAR(100)='',		/*说明*/
	@DescriptionMatch BIT = 0,
	@Remark VARCHAR(100),	/*明细备注*/
	@RemarkMatch BIT = 0,
	@IsGift TINYINT = 0,		/*赠品状态*/
	@SumType TINYINT = 0,		/*汇总条件一:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员*/
	@SumLayer TINYINT = 0,		/*汇总层级一:1,2,3,4,5,汇总条件*/
	@OrderFirst VARCHAR(20) = '',		
	@AscFirst INT = 1, 
	@OrderAgain VARCHAR(20) = '',
	@AscAgain INT = 1,
	@OperatorID INT = 1, 
	@IsHistory BIT = 0,
	@IsContainDiscountTotal BIT = 0,       -- 是否包含优惠金额
	@SumOrNot INT = 1				--是否为合计形式
) 
AS

DECLARE @IndexSql NVARCHAR(MAX) = '', @DetailSql NVARCHAR(MAX) = '', @IndexTableSql NVARCHAR(MAX) = '',@DetailTableSql NVARCHAR(MAX) = ''
DECLARE @CreateTableSql NVARCHAR(MAX) = '', @SurceSql NVARCHAR(MAX) = '', @Sql NVARCHAR(MAX) = '', @Ret INT = 0
DECLARE @SumTable NVARCHAR(MAX) = '', @BDCol NVARCHAR(MAX)='', @ICol NVARCHAR(50)= '', @OrderCol NVARCHAR(200) = ''
DECLARE @Table NVARCHAR(MAX) = '', @RetTable NVARCHAR(MAX) = '', @HisTable NVARCHAR(MAX) = '', @RetHisTable NVARCHAR(MAX) = ''
DECLARE @TotalCol NVARCHAR(MAX) = '', @BaseCol NVARCHAR(50) = ''
DECLARE @DiscountCol NVARCHAR(MAX) = '',@DiscountColRet NVARCHAR(MAX) = '',@DiscountGroupCol NVARCHAR(MAX) = '',
		@DiscountBaseCol NVARCHAR(MAX) = '',@SurceCol NVARCHAR(MAX) = '',@SurceGroupCol NVARCHAR(MAX) = '',
		@DiscountSumCol NVARCHAR(MAX) = ''

EXEC @Ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
	SET @DetailTableSql = ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =I.WhsID'
	
IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
	SET @IndexTableSql = ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID'

IF @DateType = 0 
	SET @IndexSql += ' WHERE I.BillDate BETWEEN @BeginDate AND @EndDate'
ELSE IF @DateType = 1 
	SET @IndexSql += ' WHERE I.CreateTime BETWEEN @BeginDate AND @EndDate'
ELSE IF @DateType = 2
	SET @IndexSql += ' WHERE I.PosTime BETWEEN @BeginDate AND @EndDate'

--按往来单位汇总，无任何往来单位权限/按仓库汇总，无任何仓库权限
IF (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0)
OR (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0)  
BEGIN
	SET @IndexSql = ' AND 1=2'
END

-- 是否包含优惠金额
IF @IsContainDiscountTotal = 1
BEGIN
	SET @DiscountCol += ',I.Privilege AS BuyDiscountTotal, 0 AS BackDiscountTotal'
	SET @DiscountColRet += ',0 AS BuyDiscountTotal, I.Privilege AS BackDiscountTotal'
	SET @DiscountGroupCol += ',I.Privilege'
	SET @DiscountBaseCol += ',SUM(BuyDiscountTotal) BuyDiscountTotal,SUM(BackDiscountTotal) BackDiscountTotal'
	SET @SurceCol += ',BuyDiscountTotal,(SUM(BuyTotal) - BuyDiscountTotal) BuyTotalByDiscount,
						BackDiscountTotal,(SUM(BackTotal) - BackDiscountTotal) BackTotalByDiscount'
	SET @SurceGroupCol += ',BuyDiscountTotal,BackDiscountTotal'
	SET @DiscountSumCol += ',SUM(BuyDiscountTotal)[BuyDiscountTotal],SUM(BuyTotalByDiscount)[BuyTotalByDiscount],
							SUM(BackDiscountTotal)[BackDiscountTotal],SUM(BackTotalByDiscount)[BackTotalByDiscount]'
END


IF @BTypeID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     SET @IndexTableSql += ' INNER JOIN @BType B ON I.BTypeID=B.BTypeID '
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
 SET @IndexTableSql +=' INNER JOIN @DType D ON I.DeptID=D.DeptID '    
END

IF @ElyID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
 SET @IndexTableSql +=' INNER JOIN @EType E ON I.ElyID=E.ElyID '    
END

IF @CreatorID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @Creator Table(CreatorID INT)   
     INSERT  INTO @Creator SELECT typeid AS CreatorID  FROM dbo.UF_OT_Split_Int(@CreatorID,'','')   
     '  
 SET @IndexTableSql +=' INNER JOIN @Creator C ON I.Creator=C.CreatorID '    
END

IF @WhsID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @Whs Table(WhsID INT)   
     INSERT  INTO @Whs SELECT typeid AS WhsID  FROM dbo.UF_OT_Split_Int(@WhsID,'','')   
     '
     SET @IndexTableSql += ' INNER JOIN @Whs K ON I.WhsID=K.WhsID '
END

IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
BEGIN
	SET @DetailTableSql += ' INNER JOIN BD_Goods BG ON Detail.GoodsID = BG.GoodsID '
END	

--IF @BarCode <> ''
--BEGIN 
--	SET @DetailTableSql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = Detail.GoodsID AND pri.UnitID = Detail.UnitID '
--END

IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 1 
		SET @DetailSql += ' AND BG.GoodsNo = @GoodsNo'
	ELSE
		SET @DetailSql += ' AND BG.GoodsNo Like ''%''+@GoodsNo+''%'' ' 
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 1 
		SET @DetailSql += ' AND GoodsName = @GoodsName'
	ELSE
		SET @DetailSql += ' AND GoodsName Like ''%''+@GoodsName+''%'' ' 
END

--商品型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @DetailSql += N' AND BG.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @DetailSql += N' AND BG.Model = @Model ' 
END   
--商品简名    
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @DetailSql += N' AND BG.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @DetailSql += N' AND BG.GoodsAbbName = @GoodsAbbName ' 
END       
--商品品牌
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @DetailSql += N' AND BG.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @DetailSql += N' AND BG.Brand = @Brand ' 
END
--商品规格    
IF @Spec <> ''        
BEGIN 
   IF @SpecMatch = 0
	   SET @DetailSql += N' AND BG.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @DetailSql += N' AND BG.Spec = @Spec '  
END
--商品条码
IF @BarCode <> ''      
BEGIN 
   IF @BarCodeMatch = 0
	   SET @DetailSql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=Detail.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @DetailSql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=Detail.GoodsID)'
END

IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 1 
		SET @IndexSql += ' AND Summary = @Summary'
	ELSE
		SET @IndexSql += ' AND Summary Like ''%''+@Summary+''%'' ' 
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 1 
		SET @IndexSql += ' AND Description = @Description'
	ELSE
		SET @IndexSql += ' AND Description Like ''%''+@Description+''%'' ' 
END
IF @Remark <> ''
BEGIN
	IF @RemarkMatch = 1 
		SET @DetailSql += ' AND Detail.Remark = @Remark'
	ELSE
		SET @DetailSql += ' AND Detail.Remark Like ''%''+@Remark+''%'' ' 
END

IF @IsGift <> 0
BEGIN
	IF @IsGift = 1
		SET @DetailSql += ' AND Gift = 1'
	ELSE 
		SET @DetailSql += ' AND Gift = 0'
END

IF @IsContainDiscountTotal = 1
BEGIN
	SET @TotalCol = ', SUM(BuyQty) BuyQty, SUM(BuyTotal) BuyTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal
					, CASE WHEN (SUM(BuyQty) = 0) OR (SUM(BackQty) = 0) THEN 0 ELSE CONVERT(FLOAT,SUM(BackQty)/SUM(BuyQty)*100) END AS BackRate
					, SUM(BuyQty) - SUM(BackQty) AS InStockQty, (SUM(BuyTotal) - BuyDiscountTotal) - (SUM(BackTotal) - BackDiscountTotal) AS InStockTotal'
END
ELSE
BEGIN
	SET @TotalCol = ', SUM(BuyQty) BuyQty, SUM(BuyTotal) BuyTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal
					, CASE WHEN (SUM(BuyQty) = 0) OR (SUM(BackQty) = 0) THEN 0 ELSE CONVERT(FLOAT,SUM(BackQty)/SUM(BuyQty)*100) END AS BackRate
					, SUM(BuyQty) - SUM(BackQty) AS InStockQty, SUM(BuyTotal) - SUM(BackTotal) AS InStockTotal'
END

IF @SumType = 1 --按商品汇总
BEGIN
	SET @ICol = 'Detail.GoodsID'
	SET @BaseCol = 'GoodsID'
	IF @SumLayer = 6 
		--SELECT  @SumTable = '
		--		INNER JOIN BD_Goods BD ON PD.GoodsID = BD.GoodsID 
		--		GROUP BY BD.GoodsID, BD.GoodsNo, BD.GoodsName',
		--		@BDCol = 'BD.GoodsID AS BaseID, BD.GoodsNo, BD.GoodsName '
				
		SELECT  @SumTable = '
				INNER JOIN BD_Goods BD ON PD.GoodsID = BD.GoodsID
				INNER JOIN BD_Goods_Price pri ON PD.GoodsID = pri.GoodsID AND pri.UnitID = 1
				GROUP BY BD.GoodsID, BD.GoodsNo, BD.GoodsName, BD.Model, BD.GoodsAbbName, BD.Brand, BD.Spec, pri.BarCode',
				@BDCol = 'BD.GoodsID AS BaseID, BD.GoodsNo, BD.GoodsName, BD.Model, BD.GoodsAbbName, BD.Brand, BD.Spec, pri.BarCode '
				
	ELSE
		SELECT  @SumTable = ' 
				INNER JOIN BD_Goods BG ON PD.GoodsID = BG.GoodsID
				INNER JOIN BD_Goods_Price pri ON PD.GoodsID = pri.GoodsID AND pri.UnitID = 1
				INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @SumLayer) BS ON BG.GoodsTypeID = BS.ParID
				INNER JOIN BD_Goods_Type BD ON BS.BaseID = BD.GoodsTypeID 
				GROUP BY BS.BaseID, BD.TypeCode, BD.TypeName', 
				@BDCol = 'BS.BaseID ,BD.TypeCode AS PCode, BD.TypeName AS PName '
END ELSE
IF @SumType = 2 --按往来单位汇总
BEGIN
	SET @ICol = 'I.BTypeID'
	SET @BaseCol = 'BTypeID'
	IF @SumLayer = 6 
		SELECT	
				@SumTable = '
				INNER JOIN BD_Btype BD ON PD.BTypeID = BD.BTypeID
				GROUP BY BD.BTypeID, BD.BTypeCode, BD.BTypeName', 
				@BDCol = 'BD.BTypeID AS BaseID, BD.BTypeCode, BD.BTypeName '
	ELSE
		SELECT	@SumTable = '
				INNER JOIN BD_Btype BG ON PD.BTypeID = BG.BTypeID
				INNER JOIN dbo.UF_BD_BaseSummary(''BTYPE'', @SumLayer) BS ON BG.BtypeTypeID = BS.ParID
				INNER JOIN BD_BType_Type BD ON BS.BaseID = BD.BtypeTypeID
				GROUP BY BS.BaseID, BD.TypeCode, BD.TypeName', 
				@BDCol = 'BS.BaseID, BD.TypeCode AS BCode, BD.TypeName AS BName'
		
END ELSE
IF @SumType = 3 --按仓库汇总
BEGIN
	SET @ICol = 'I.WhsID'
	SET @BaseCol = 'WhsID'
	IF @SumLayer = 6
		SELECT	@SumTable = '
				INNER JOIN BD_Whs BD ON PD.WhsID = BD.WhsID
				GROUP BY BD.WhsID, BD.WhsNO, BD.WhsName', 
				@BDCol = 'BD.WhsID AS BaseID, BD.WhsNO, BD.WhsName'
	ELSE
		SELECT	@SumTable = '
				INNER JOIN BD_Whs BG ON PD.WhsID = BG.WhsID
				INNER JOIN dbo.UF_BD_BaseSummary(''KTYPE'', @SumLayer) BS ON BG.WhsTypeID = BS.ParID
				INNER JOIN BD_Whs_Type BD ON BS.BaseID = BD.WhsTypeID
				GROUP BY BS.BaseID, BD.TypeCode, BD.TypeName', 
				@BDCol = 'BS.BaseID, BD.TypeCode AS KCode, BD.TypeName AS KName'
END ELSE
IF @SumType = 4 --按地区汇总
BEGIN
	SELECT	@ICol = 'I.BTypeID',
			@BaseCol = 'BTypeID', 
			@SumTable = '
				INNER JOIN BD_Btype BG ON PD.BTypeID = BG.BTypeID
				INNER JOIN dbo.UF_BD_BaseSummary(''AREA'', @SumLayer) BS ON BG.AreaID = BS.ParID
				INNER JOIN (SELECT AreaID, AreaNO, AreaName FROM BD_Area 
							UNION ALL
							SELECT 0 AS AreaID, '''' AS AreaNO, ''其他'' AS AreaName
							)BD ON BS.BaseID = BD.AreaID
				GROUP BY BS.BaseID, BD.AreaNO, BD.AreaName', 
				@BDCol = 'BS.BaseID, BD.AreaNO , BD.AreaName '
END
IF @SumType = 5 --按部门汇总
BEGIN
	SET	@ICol = 'I.DeptID'
	SET @BaseCol = 'DeptID'
	IF @SumLayer = 5
		SELECT	@SumTable = '
				INNER JOIN BD_Dept BD ON PD.DeptID = BD.DeptID
				GROUP BY BD.DeptID, BD.DeptCode, BD.DeptName', 
				@BDCol = 'BD.DeptID, BD.DeptCode, BD.DeptName'
	ELSE
		SELECT  @SumTable = '
				INNER JOIN dbo.UF_BD_BaseSummary(''DTYPE'', @SumLayer) BS ON BS.ParID= PD.DeptID
				INNER JOIN BD_Dept BD ON BS.BaseID = BD.DeptID	
				GROUP BY BS.BaseID, BD.DeptCode, BD.DeptName', 
				@BDCol = 'BS.BaseID,BD.DeptCode, BD.DeptName'
END ELSE
IF @SumType = 6 --按经手人汇总
BEGIN
	SELECT	@ICol = 'I.ElyID',
			@BaseCol = 'ElyID',
			@SumTable = '
			INNER JOIN BD_Employee BD ON PD.ElyID = BD.ElyID
			GROUP BY BD.ElyID, BD.ElyCode, BD.ElyName', 
			@BDCol = 'BD.ElyID AS BaseID, BD.ElyCode, BD.ElyName'
END

IF @SumType = 7 --按制单人汇总
BEGIN
	SELECT @ICol = 'I.Creator',
		   @BaseCol = 'Creator',
		   @SumTable = '
		   INNER JOIN BD_Employee BD ON PD.Creator = BD.ElyID
		   GROUP BY BD.ElyID, BD.ElyCode, BD.ElyName',
		   @BDCol = ' BD.ElyID AS BaseID, BD.ElyCode AS OperatorCode, BD.ElyName AS OperatorName'
END

SET @IndexSql += ' AND Red = 0 AND IsDraft = 0'

SET @Table = '
	  SELECT '+ @ICol + @DiscountCol +', ISNULL(SUM(Detail.BSQty), 0) BuyQty, ISNULL(SUM(Detail.DiscTotal), 0) BuyTotal, 0 AS BackQty, 0 AS BackTotal
	  FROM PD_PchBill I INNER JOIN PD_PchDetail Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol

	SET @RetTable = '
	  UNION ALL
	  SELECT '+ @ICol + @DiscountColRet +', 0 AS BuyQty, 0 AS BuyTotal, ISNULL(SUM(BSQty), 0) BackQty, ISNULL(SUM(Detail.DiscTotal), 0) BackTotal
	  FROM PD_PchRetBill I INNER JOIN PD_PchRetDetail Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol

IF @IsHistory = 1
BEGIN
	SET @HisTable = '
	  UNION ALL
	  SELECT '+ @ICol + @DiscountCol +', ISNULL(SUM(Detail.BSQty), 0) BuyQty, ISNULL(SUM(Detail.DiscTotal), 0) BuyTotal, 0 AS BackQty, 0 AS BackTotal 
	  FROM PD_PchBill_His I INNER JOIN PD_PchDetail_His Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol
	  
	SET @RetHisTable = '
	  UNION ALL
	  SELECT '+ @ICol + @DiscountColRet +', 0 AS BuyQty, 0 AS BuyTotal, ISNULL(SUM(BSQty), 0) BackQty, ISNULL(SUM(Detail.DiscTotal), 0) BackTotal 
	  FROM PD_PchRetBill_His I INNER JOIN PD_PchRetDetail_His Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol
END

IF @OrderFirst <> ''
BEGIN
	IF @AscFirst = 2 SET @OrderCol = @OrderFirst+' DESC' ELSE SET @OrderCol = @OrderFirst +' ASC'
END
IF @OrderAgain <> ''
BEGIN
	IF @OrderCol <> '' SET @OrderCol +=', '
	IF @AscAgain = 2 SET @OrderCol += @OrderAgain+' DESC' ELSE SET @OrderCol += @OrderAgain +' ASC'
END

SET @SurceSql +='
	SELECT	'+ @BDCol + @TotalCol + @SurceCol +'
	FROM 
	(	SELECT '+ @BaseCol + @DiscountBaseCol +', SUM(BuyQty) BuyQty, SUM(BuyTotal) BuyTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal
		FROM ( 
				'+@Table + @RetTable + @HisTable + @RetHisTable+'
			) I GROUP BY '+ @BaseCol +'
	) PD 
	'+ @SumTable + @SurceGroupCol

IF @SumOrNot = 0
BEGIN
	SET @Sql = @CreateTableSql + '
		;WITH PagingData AS 
		(
			'+ @SurceSql +'
		)

	   SELECT * FROM (SELECT COUNT(BuyQty) AS ''ROWCOUNT'' FROM PagingData) A
	   CROSS JOIN
	   (
		SELECT	ROW_NUMBER() OVER( ORDER BY '+ @OrderCol +') AS ROWID,
		*
		FROM PagingData

	   ) B
	   WHERE B.ROWID>(@PageNo-1)*@PageSize
		AND B.ROWID<=@PageNo*@PageSize
		
		'
END
IF @SumOrNot = 1
BEGIN
	SET @Sql = @CreateTableSql + '
		;WITH PagingData AS 
		(
			'+ @SurceSql +'
		)

	   SELECT SUM(A.BuyQty)[BuyQty],SUM(A.BuyTotal)[BuyTotal],SUM(A.BackQty)[BackQty],SUM(A.BackTotal)[BackTotal],
			  SUM(A.InStockQty)[InStockQty],SUM(A.InStockTotal)[InStockTotal] '+ @DiscountSumCol +' FROM PagingData A

		'
END
--print @sql
EXEC sp_executesql @sql,
N'@PageNo INT, @PageSize INT,@BeginDate DATE,@EndDate DATE,@BTypeID VARCHAR(MAX),@DeptID VARCHAR(MAX),@ElyID VARCHAR(MAX),@CreatorID VARCHAR(MAX),@WhsID VARCHAR(MAX),@GoodsNo VARCHAR(50),@GoodsName VARCHAR(100),@Summary VARCHAR(256),@Description VARCHAR(100), @Remark VARCHAR(100), @SumLayer INT, @OperatorID INT
,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT,@SumOrNot INT ',
@PageNo, @PageSize,@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@GoodsNo,@GoodsName,@Summary,@Description, @Remark, @SumLayer, @OperatorID
,@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch ,@SumOrNot

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询采购明细
	××××××××××××××××××
	修改：sunzhiyuan
	日期：2015-3-31
	修改描述：62行：取消归档数据判断
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_BuyDetailsSum]
(
	@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BuyBillIn Int = 1,
	@BuyBillOut Int = 1,
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@BillCode VARCHAR(100)='',
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100)='',
	@UserCodeMatch INT=0,
	@UserCode VARCHAR(100)='',
	@FullNameMatch INT=0,
	@Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	@Ppt1 VARCHAR(100)='',
	@Ppt1Match INT=0,
	@Ppt2 VARCHAR(100)='',
	@Ppt2Match INT=0,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=0,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=0,
	@Remark VARCHAR(100)='',
	@RemarkMatch INT=0,
	@GiftFlag INT=0,
	@IsRedFlag Int = 0,
	@OperatorID INT,	
	@ClassID1 Int = 0,
	@ClassType1 Int = 0,
	@ClaseFlag1 Int = 0, 
	@ClassID2 Int = 0,
	@ClassType2 Int = 0,
	@ClaseFlag2 Int = 0,
	@isHistory INT=0,				--是否包含历史数据
	@ClickFlag Int =0
)

AS
SET NOCOUNT ON

--DECLARE @re int 
--execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
--if( @re=1 )return @re;

DECLARE @sql nvarchar(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlMatch varchar(max)='',@SqlWhs nvarchar(max),@SqlDept nvarchar(max),@SqlEly nvarchar(max),@SqlPost nvarchar(max),@SqlUnit nvarchar(2000),
		@SqlUnit1 nvarchar(1000),@SqlUnit2 nvarchar(1000),@SqlUnit3 nvarchar(1000),@SqlBtype nvarchar(max),
		@SqlCreator nvarchar(max),@SqlIn nvarchar(Max),@SqlOut nVarchar(max),@OrderName nvarchar(100),
		@OrderColumn varchar(max)='',@OrderTable varchar(max)='',@GoodsTable varchar(max)='',@GoodsMath varchar(max)='', 
		@SqlGoods Nvarchar(1000),@SqlPpt1 nvarchar(1000),@SqlPpt2 nvarchar(1000), @LimitKtypeSql NVARCHAR(MAX) = '', @LimitBtypeSql NVARCHAR(MAX) = '',@RedStr varchar(100)='',@Red varchar(100)='',
		@SqlClass1 varchar(500)='',@SqlClass2 varchar(500)='',@ExcSql Nvarchar(Max)='',@DecParam NVARCHAR(max),@param NVARCHAR(max),@BtypeLimit INT=0,@KtypeLimit INT=0
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
End
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID1,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON bill.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON bill.ElyID=E.TypeID ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' INNER JOIN @CreateEType CE ON bill.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	SET @SqlTable+=' INNER JOIN @KType W ON bill.WhsID=W.TypeID ' 
END	
if(@Summary <> '')
	Set @SqlMatch += ' And Summary ' + case @SummaryMatch when 0 then ' Like ''%''+@Summary+''%''' Else ' =@Summary ' End
if(@Description <> '')
	Set @SqlMatch += ' And Description ' + case @DescriptionMatch when 0 then ' Like ''%''+@Description+''%''' Else ' =@Description ' END
if(@Remark <> '')
	Set @SqlMatch += ' And Remark ' + case @RemarkMatch when 0 then ' Like ''%''+@Remark+''%''' Else ' =@Remark ' END
if(@BillCode <> '')
	Set @SqlMatch += ' And BillCode ' + case @BillCodeMatch when 0 then ' Like ''%''+@BillCode+''%''' Else ' =@BillCode ' END	
if(@FullName <> '' or @UserCode <> '' or @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> '')
Begin
	if(@FullName <> '')
		Set @GoodsMath += ' And G.GoodsName ' + case @FullNameMatch when 0 then ' Like ''%''+@FullName+''%''' Else ' =@FullName ' END
	if(@UserCode <> '')
		Set @GoodsMath += ' And G.GoodsNo ' + case @UserCodeMatch when 0 then ' Like ''%''+@UserCode+''%''' Else ' =@UserCode ' END
	--商品型号
	IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @GoodsMath += N' AND G.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @GoodsMath += N' AND G.Model = @Model ' 
	END   
	--商品简名    
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @GoodsMath += N' AND G.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @GoodsMath += N' AND G.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @GoodsMath += N' AND G.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @GoodsMath += N' AND G.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
	   IF @SpecMatch = 0
		   SET @GoodsMath += N' AND G.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @GoodsMath += N' AND G.Spec = @Spec '  
	END
	
	Select @GoodsTable += ' And exists(select 1 from BD_GOODS G Where detail.GoodsID = G.GoodsID '+@GoodsMath+')'
End
--商品条码
	IF @BarCode <> ''      
	BEGIN 
	   SET @SqlTable += N' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = detail.GoodsID and pri.UnitID = 1 '
	   IF @BarCodeMatch = 0
		   SET @SqlMatch += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlMatch += N' AND pri.BarCode = @BarCode ' 
	END
	
-- 判断单据时间类型
IF @DateType = 0
	set @SqlDTStr = 'detail.BillDate'
IF @DateType=1
	SET @SqlDTStr='bill.CreateTime'	
IF @DateType=2
	SET @SqlDTStr='bill.PosTime'
	
if(@Ppt1 <> '' or (@ClickFlag = 1 and  @Ppt1Match = 1))
BEGIN
	Set @GoodsMath = ' And GP1.Value ' + case @Ppt1Match when 0 then ' Like ''%''+@Ppt1+''%''' Else ' =@Ppt1 ' END
	Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt1 GP1 Where detail.Ppt1ID = GP1.Ppt1ID '+@GoodsMath+')'
END
if(@Ppt2 <> '' or (@ClickFlag = 1 and  @Ppt2Match = 1))
BEGIN
	Set @GoodsMath = ' And GP2.Value ' + case @Ppt2Match when 0 then ' Like ''%''+@Ppt2+''%''' Else ' =@Ppt2 ' END	
	Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt2 GP2 Where detail.Ppt2ID = GP2.Ppt2ID '+@GoodsMath+')'
END
IF @ClassID1 <> 0
Begin
	SET @SqlClass1 +=' DECLARE @CTb1  as Table(typeid int) INSERT INTO @CTb1(typeid) '
	Set @SqlCreateTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass1 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass1 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then ' And detail.GoodsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on detail.GoodsID = C1.TypeID' end 
											when 2 then case @ClaseFlag1 when 0 then ' And bill.BtypeID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.BtypeID = C1.TypeID' end
											when 3 then case @ClaseFlag1 when 0 then ' And bill.WhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.WhsID = C1.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb1 C1 on BB.AreaID = C1.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb1 C1 on EE.DeptId = C1.TypeID'
											when 6 then ' And bill.ElyID = @ClassID1 '  	
											When 7 then ' And bill.Creator = @ClassID1' end 	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType1 = 4 and @ClassID1 = 0 
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END

IF @ClassID2 <> 0
Begin
	SET @SqlClass2 +=' DECLARE @CTb2  as Table(typeid int) INSERT INTO @CTb2(typeid) '
	Set @SqlCreateTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass2 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass2 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then ' And detail.GoodsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on detail.GoodsID = C2.TypeID' end 
											when 2 then case @ClaseFlag2 when 0 then ' And bill.BtypeID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.BtypeID = C2.TypeID' end
											when 3 then case @ClaseFlag2 when 0 then ' And bill.WhsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.WhsID = C2.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb2 C2 on BB.AreaID = C2.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb2 C2 on EE.DeptId = C2.TypeID'
											when 6 then ' And bill.ElyID = @ClassID2 '  
											When 7 then ' And bill.Creator = @ClassID2' end 	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType2 = 4 and @ClassID2 = 0
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END
--if(@IsRedFlag = 0)
--Begin
	Set @Red = ' And Red = 0 '
--End
--Else
--	Set @RedStr = ',Red'

select  @SqlIn = ' select detail.BSQty as Qty,detail.Total,detail.DiscTotal,detail.Freight,detail.InTotal 
		from PD_PchBill bill INNER JOIN PD_PchDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where '+@SqlDTStr+' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
		+@SqlMatch + @GoodsTable
select @SqlOut = ' select detail.BSQty*-1 as Qty,detail.Total*-1 as Total,detail.DiscTotal*-1 as DiscTotal,0 as Freight,detail.DiscTotal*-1 as InTotal
		from PD_PchRetBill bill INNER JOIN PD_PchRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where '+@SqlDTStr+' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
		+@SqlMatch + @GoodsTable
IF @isHistory=1
Begin
	select  @SqlIn += ' 
		UNION ALL
	select detail.BSQty as Qty,detail.Total,detail.DiscTotal,detail.Freight,detail.InTotal  
		from PD_PchBill_His bill INNER JOIN PD_PchDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where '+@SqlDTStr+' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		UNION ALL
	select detail.BSQty*-1 as Qty,detail.Total*-1 as Total,detail.DiscTotal*-1 as DiscTotal,0 as Freight,detail.DiscTotal*-1 as InTotal
		from PD_PchRetBill_His bill INNER JOIN PD_PchRetDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where '+@SqlDTStr+' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
		+@SqlMatch + @GoodsTable
End		
if (@BuyBillIn = 1)  
begin  
 if(@BuyBillOut = 1)  
  Select @Sql += @SqlIn+ ' UNION ALL ' ;  
 else  
  Select @Sql += @SqlIn ;  
end  
if (@BuyBillOut = 1)  
 Select @Sql += @SqlOut; 
SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
)'
select @Sql += ' select SUM(Qty) as Qty,SUM(total) as Total,SUM(DiscTotal) as DiscTotal,SUM(Freight) as Freight,SUM(InTotal) as InTotal
	 from  Bill '

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

Set @EndDate = CASE WHEN @DateType=0 THEN @EndDate ELSE DATEADD(day,1,@EndDate) END

Select @DecParam = N'@BeginDate VARCHAR(50),@EndDate VARCHAR(50),@BuyBillIn Int ,@BuyBillOut Int,@BTypeID VARCHAR(50),@DeptID1 VARCHAR(50),@ElyID VARCHAR(1000),@CreatorID VARCHAR(1000),@WhsID VARCHAR(1000),@BillCode VARCHAR(100),@FullName VARCHAR(100),@UserCode VARCHAR(100),@Ppt1 VARCHAR(100),@Ppt2 VARCHAR(100),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@OperatorID INT
					,@Model VARCHAR(50), @GoodsAbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50),  @BarCode VARCHAR(100)'

Select @param =  ''''+Cast(@BeginDate as varchar(10))+''''+N','+''''+Cast(@EndDate as varchar(10))+''''+N','+''''+Cast(@BuyBillIn as varchar(2))+''''+N','
				+''''+Cast(@BuyBillOut as varchar(2))+''''+N','+''''+@BTypeID+''''+N','+''''+@DeptID+''''+N','+''''+@ElyID+''''+N','+''''+@CreatorID+''''+N','+''''+@WhsID+''''+N','+''''+@BillCode+''''+N','
				+''''+@FullName+''''+N','+''''+@UserCode+''''+N','+''''+@Ppt1+''''+N','+''''+@Ppt2+''''+N','+''''+@Summary+''''+N','+''''+@Description+''''+N','+''''+@Remark+''''+N','
				+''''+Cast(@OperatorID  as varchar(50))+''''+N','
				+''''+@Model+''''+N','+''''+@GoodsAbbName+''''+N','+''''+@Brand+''''+N','+''''+@Spec+''''+N','+''''+@BarCode+''''
if @ClassID1 <> 0
Begin
	Select @DecParam += ',@ClassID1 Int '
	Select @param += N',' + Cast(@ClassID1  as varchar(50))
	if(@ClassType1 = 1 and @ClaseFlag1 = 1)
	begin
		Select @DecParam += ',@GoodsTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 2 and @ClaseFlag1 = 1)
	begin
		Select @DecParam += ',@BtypeTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 3 and @ClaseFlag1 = 1)
	begin
		Select @DecParam += ',@WhsTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 4)
	begin
		Select @DecParam += ',@AreaTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 5)
	begin
		Select @DecParam += ',@DeptID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	
END
if @ClassID2 <> 0
Begin
	Select @DecParam += ',@ClassID2 Int '
	Select @param += N',' + Cast(@ClassID2  as varchar(50))
	if(@ClassType2 = 1 and @ClaseFlag2 = 1)
	begin
		Select @DecParam += ',@GoodsTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 2 and @ClaseFlag2 = 1)
	begin
		Select @DecParam += ',@BtypeTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 3 and @ClaseFlag2 = 1)
	begin
		Select @DecParam += ',@WhsTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 4)
	begin
		Select @DecParam += ',@AreaTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 5)
	begin
		Select @DecParam += ',@DeptID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	
END
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
Select @ExcSql = N'EXEC sp_executesql @Sql,@DecParam,'+@param 
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 --PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
EXEC sp_executesql @ExcSql,N'@Sql NVARCHAR(max),@DecParam NVARCHAR(max)',@Sql,@DecParam

--EXEC SP_EXECUTESQL @Sql,N'@DateType Int,@BeginDate VARCHAR(50),@EndDate VARCHAR(50),@BuyBillIn Int ,@BuyBillOut Int,@BTypeID VARCHAR(50),@DeptID VARCHAR(50),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@BillCode VARCHAR(100),@FullName VARCHAR(100),@UserCode VARCHAR(100),@Ppt1 VARCHAR(100),@Ppt2 VARCHAR(100),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@OperatorID INT'
--					,@DateType,@BeginDate,@EndDate,@BuyBillIn,@BuyBillOut,@BTypeID,@DeptID,@ElyID,@WhsID,@BillCode,@FullName,@UserCode,@Ppt1,@Ppt2,@Summary,@Description,@Remark,@OperatorID


GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询采购明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_BuyInvoiceStatisticalSum]
(
	@BeginDate DATE,
	@EndDate DATE,
	@BillType Int=0,  --单据类型
	@BTypeID VARCHAR(max)='',
	@IsManual INT=0,  --是否勾选手工开票单独列示
	@IsRedFlag INT=0,				--是否包含红冲单据数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID Int=0
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;

DECLARE @Sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',
		 @LimitBtypeSql NVARCHAR(MAX) = '',@OutStr varchar(max)='',@outRetStr varchar(max)=''
		,@outSql varchar(max)='',@BtypeLimit INT=0,@RedStr varchar(100)=''
		,@InvoiceSql varchar(max)='',@InvoiceModeSql varchar(max)='',@InvoiceOutModeSql varchar(Max)=''
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
--SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
--IF @KtypeLimit = 1
--Begin
--	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
--	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
--End
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
if @IsRedFlag = 0
	select @RedStr = ' And Red=0 '
select @RedStr += ' And IsInvoice = 1 ' --只查询是否开票为是的单据
---------------计算单据金额列信息----------------
Select @OutStr +=' select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
Select @outRetStr +=' select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchRetBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
select @InvoiceSql += ' select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_PchInvoiceBill bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0 group by BTypeID'
if @IsHistory = 1
begin
	Select @OutStr +='
		Union All
		 select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	Select @outRetStr +=' 
		Union All
		select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchRetBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	select @InvoiceSql += '
		Union All
	 select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_PchInvoiceBill_His bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0  group by BTypeID'
end
if @BillType = 0
	Select @Sql += @OutStr + ' Union All ' + @outRetStr
else if @BillType =1
	Select @Sql += @OutStr 
else
	Select @Sql += @outRetStr 
-----------不同的显示方式计算未结金额和超额金额-----------
if @IsManual = 1 
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal2,SUM(UserTotal1) as UserTotal2,sum(Total) - sum(BillTotal1) as NoInvoiceTotal '
	Select @InvoiceOutModeSql +=' Total,BillTotal2,UserTotal2,NoInvoiceTotal'
End
else
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal1,SUM(UserTotal1) as UserTotal1,
					sum(Total) - sum(BillTotal1) - SUM(UserTotal1) as NoInvoiceTotal,sum(BillTotal1) + SUM(UserTotal1)- sum(Total) as OutInvoiceTotal '
	Select @InvoiceOutModeSql +=' Total,BillTotal1,UserTotal1
								,case when total >= 0 then (case when NoInvoiceTotal<=0 then 0 else NoInvoiceTotal end) else (case when NoInvoiceTotal > 0 then 0 else NoInvoiceTotal end) end as NoInvoiceTotal
								,case When total >= 0 then (Case When OutInvoiceTotal <=0 then 0 else OutInvoiceTotal end) Else (Case When OutInvoiceTotal >= 0 then 0 else OutInvoiceTotal end) End as OutInvoiceTotal'
End

SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
),BillTotal as(
	Select BTypeID,sum(Total) as Total,sum(InvoiceTotal) as BillTotal1,0 as UserTotal1 from Bill Group By BTypeID
),InvoiceTotal as(
' +@InvoiceSql+ '
),AllData AS
 (
	select BTypeID,Total,BillTotal1,UserTotal1 from BillTotal
	Union All
	select BTypeID,Total,BillTotal1,UserTotal1 from InvoiceTotal
 ),PagingData AS(
	Select sum(Total) as Total '+@InvoiceModeSql+' 
	from AllData Ad 
 )
'


IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

------------------添加参数---------------------------------------

select @sql +=' select '+@InvoiceOutModeSql+'
	 from PagingData data '
IF @BtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Btype WHERE 1 <> 1'
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 --PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
exec sp_executesql @Sql,N'@BeginDate Date,@EndDate Date,@OperatorID Int,@BTypeID VarChar(MAX)'
			,@BeginDate,@EndDate,@OperatorID,@BTypeID

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_BuyOrderDetailQuery]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_BuyOrderDetailQuery
GO
/****** Object:  StoredProcedure [UP_PD_BuyOrderDetailQuery]    Script Date: 07/28/2014 11:08:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/28
-- Description:	 采购订单明细查询
-- =============================================
CREATE PROCEDURE [UP_PD_BuyOrderDetailQuery](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @DateType INT = 1,                    --日期类型 1=录单日期,2=制单日期
	 @BillStartDate DATETIME,                    --开始日期
	 @BillEndDate DATETIME,                    --结束日期
	 @BTypeID VARCHAR(1000) = '',            --往来单位
	 @DeptID VARCHAR(1000) = '',            --部门
	 @ElyID VARCHAR(1000) = '',            --经手人
	 @WhsID VARCHAR(1000) = '',            --仓库
     @BillCodeMatch INT = 0,   --单据编号匹配方式
     @BillCode VARCHAR(100) = '', --单据编号
     @GoodsNoMatch INT = 0,   --商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',            --商品编号
     @GoodsNameMatch INT = 0,   --商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
     @Ppt1Match INT = 0,   --属性1匹配方式
	 @Ppt1 VARCHAR(10) = '',         --属性1
     @Ppt2Match INT = 0,   --属性2匹配方式
	 @Ppt2 VARCHAR(10) = '',         --属性2
     @SummaryMatch INT = 0,   --摘要匹配方式
	 @Summary VARCHAR(256) = '',         --摘要
     @DescMatch INT = 0,   --说明匹配方式
	 @Description VARCHAR(100) = '',         --说明
     @RemarkMatch INT = 0,   --明细备注匹配方式
	 @Remark VARCHAR(100) = '',         --明细备注
	 @GiftStt INT = 1,                    --赠品状态 1=全部,2=是,3=否
	 @Stt1 BIT = 1,         --订单状态 未调用
	 @Stt2 BIT = 1,         --订单状态 部分调用
	 @Stt3 BIT = 1,         --订单状态 已完成
	 @StopTag INT = 1,                    --中止状态 1=全部,2=已中止,3=未中止
	 @OrderStr VARCHAR(50) = '',         --排序字符串
	 @OperatorID INT = 0,                  --操作员ID   
	 @IsHistory BIT = 0,    --是否查询历史记录  
	 /*以下参数在由采购订单汇总查看明细时用到*/
	 @GoodsTypeID INT = 0, --商品分类
	 @GoodsID INT = 0, --商品
	 @WhsTypeID INT = 0, --仓库分类
	 @BtypeTypeID INT = 0, --往来单位分类
	 @AreaID INT = 0 --地区
   ) 
AS
BEGIN
	IF LTRIM(RTRIM(@OrderStr))=''
		SET @OrderStr = 'BillCode,GoodsNo'
		
	SET NOCOUNT ON;
		
	DECLARE @Re INT 
	EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @BillStartDate, @isHistory = @IsHistory
	IF @Re = 1 RETURN @Re;
	
	DECLARE @Sql NVARCHAR(MAX) = '', @HeadSql NVARCHAR(MAX) = '',
		    @SqlParam NVARCHAR(1000) = N'',
		    @SttParam NVARCHAR(1000) = N'',
	        @DataSql NVARCHAR(2000) = N'', 
	        @BaseSql NVARCHAR(2000) = N'',
	        @BtypeLimit INT = 0, 
	        @KtypeLimit INT = 0
    DECLARE @TVP_Com AS [TVP_Type]
    DECLARE @TVP_Dept AS [TVP_Type]
	SET @HeadSql = N';With PagingData AS (SELECT ord.BillNo, ord.BillCode, ord.BTypeID, ord.DeptID, ord.ElyID, ord.WhsID, ord.BillDate
											   , CreateTime, ord.Creator AS CreatorID, ord.Summary, ord.[Description]
											   , detail.DID, detail.Ppt1ID, detail.Ppt2ID, detail.GoodsID, detail.Gift, detail.UnitID, detail.Qty 
											   , detail.BSQty, detail.ComQty, detail.TaxPrice, detail.TaxTotal, detail.ComTotal, detail.Remark 
											   , detail.StopTag, goods.GoodsNo, goods.GoodsName, creator.ElyName AS Creator
											   , btype.BTypeCode, btype.BTypeName,detail.goodsno as BtypeGoodsNo				   
										 FROM  PD_PchOrdDetail detail 
										 INNER JOIN PD_PchOrdBill ord ON detail.BillNo = ord.BillNo
										 INNER JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID 
										 LEFT JOIN BD_Employee creator ON creator.ElyID = ord.Creator 
										 INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID '
    IF @DateType = 1
       SET @SqlParam = ' WHERE ord.BillDate BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
    ELSE
       SET @SqlParam = ' WHERE ord.CreateTime BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
	   
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)   
	                 
    IF @BtypeLimit = 1  --部份权限
	   SET @Sql +=' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID = ord.BTypeID '
       
    IF @BTypeID <> ''     --往来单位
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = ord.BTypeID '
	   
    IF @DeptID <> ''     --部门
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = ord.DeptID '
         INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
	     SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
	         INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		     WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	   END
	
	IF @GoodsTypeID  <> 0     --商品分类
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _goodsType ON _goodsType.ChildTypeID = goods.GoodsTypeID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM  BD_Goods_Type gt
	         INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
		     WHERE gt.GoodsTypeID = @GoodsTypeID AND cgt.SonNum = 0
	   END
	
	IF @GoodsID  <> 0     --商品
	   SET @SqlParam += N' AND detail.GoodsID = @GoodsID '
	
	IF @BtypeTypeID <> 0     --往来单位分类
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _btypeType ON _btypeType.ChildTypeID = btype.BtypeTypeID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT bt.BtypeTypeID, cbt.BtypeTypeID FROM BD_Btype_Type bt       
	         INNER JOIN BD_Btype_Type cbt ON cbt.[Path] Like bt.[Path] + '%'
		     WHERE bt.BtypeTypeID = @BtypeTypeID AND cbt.SonNum = 0
	   END
      
    --仓库权限                  
    SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)
    
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = ord.WhsID '
	
	IF @WhsTypeID <> 0     --仓库分类
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _whsType ON _whsType.ChildTypeID = ord.WhsID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT cwt.WhsTypeID, w.WhsID FROM BD_Whs w
	         INNER JOIN BD_Whs_Type cwt ON w.WhsTypeID = cwt.WhsTypeID         
	         INNER JOIN BD_Whs_Type wt ON cwt.[Path] Like wt.[Path] + '%'
		     WHERE wt.WhsTypeID = @WhsTypeID AND cwt.SonNum = 0
	   END
	
	IF @AreaID <> 0     --地区
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _area ON _area.ChildTypeID = btype.AreaID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT a.AreaID, ca.AreaID FROM BD_Area a
	         INNER JOIN BD_Area ca ON ca.[Path] Like a.[Path] + '%'
		     WHERE a.AreaID = @AreaID AND ca.SonNum = 0
	   END
	   
    IF @ElyID <> ''     --经手人
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = ord.ElyID '
	   
    IF @WhsID <> ''     --仓库
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = ord.WhsID '
	     							
	IF @BillCode <> ''   --单据编号
	   BEGIN 
		   IF @BillCodeMatch = 0
			   SET @SqlParam += N' AND ord.BillCode LIKE ''%'' + @BillCode +''%'''
		   ELSE IF @BillCodeMatch = 1
			   SET @SqlParam += N' AND ord.BillCode = @BillCode ' 
	   END
	     							
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND goods.GoodsNo = @GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsName = @GoodsName ' 
	   END
	
	IF @Model <> ''      --商品型号
		BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
		END       
		IF @GoodsAbbName <> ''    --商品简名
		BEGIN 
		   IF @GoodsAbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
		   ELSE IF @GoodsAbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
		END       
		IF @Brand <> ''      --商品品牌
		BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
		END
		--商品规格    
		IF @Spec <> ''        
		BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
		END
		--商品条码
		IF @BarCode <> ''      
		BEGIN 
		   SET @Sql += ' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID AND pri.UnitID = 1 '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=detail.GoodsID) '
		   ELSE IF @BarCodeMatch = 1 
	           SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=detail.GoodsID)'
		END
	
	   
	IF @Ppt1 <> ''       --属性一 
	   BEGIN 
		   SET @Sql += N' INNER JOIN BD_Goods_Ppt1 ppt1 ON detail.Ppt1ID = ppt1.Ppt1ID  '
		   IF @Ppt1Match = 0  
			   SET @SqlParam += N' AND ppt1.Value LIKE ''%'' + @Ppt1 +''%'''
		   ELSE IF @Ppt1Match = 1
			   SET @SqlParam += N' AND ppt1.Value = @Ppt1 ' 
	   END 
	   
	IF @Ppt2 <> ''      --属性二
	   BEGIN 
		   SET @Sql += N' INNER JOIN BD_Goods_Ppt2 ppt2 ON detail.Ppt2ID = ppt2.Ppt2ID  ' 
		   IF @Ppt2Match = 0   
			   SET @SqlParam += N' AND ppt2.Value LIKE ''%'' + @Ppt2 +''%'''
		   ELSE IF @Ppt2Match = 1
			   SET @SqlParam += N' AND ppt2.Value = @Ppt2 ' 
	   END 
       							
	IF @Summary <> ''   --摘要 
	   BEGIN 
		   IF @SummaryMatch = 0
			   SET @SqlParam += N' AND ord.Summary LIKE ''%'' + @Summary +''%'''
		   ELSE IF @SummaryMatch = 1
			   SET @SqlParam += N' AND ord.Summary = @Summary ' 
	   END
	   
	IF @Description <> ''  --说明
	   BEGIN 
		   IF @DescMatch = 0
			   SET @SqlParam += N' AND ord.[Description] LIKE ''%'' + @Description +''%'''
		   ELSE IF @DescMatch = 1
			   SET @SqlParam += N' AND ord.[Description] = @Description ' 
	   END
       							
	IF @Remark <> ''   --明细备注 
	   BEGIN 
		   IF @RemarkMatch = 0
			   SET @SqlParam += N' AND detail.Remark LIKE ''%'' + @Remark +''%'''
		   ELSE IF @RemarkMatch = 1
			   SET @SqlParam += N' AND detail.Remark = @Remark ' 
	   END
	   
    IF @GiftStt = 2 --赠品 
       SET @SqlParam += N' AND detail.Gift = 1 '
    ELSE IF @GiftStt = 3 --非赠品
       SET @SqlParam += N' AND detail.Gift = 0 '
       
	IF @Stt1 <> 1 OR @Stt2 <> 1 OR @Stt3 <> 1   --订单状态 未调用 部分调用 已完成
	   BEGIN
	      IF @Stt1 = 1
			  SET @SttParam += N' OR (detail.ComQty = 0 )'
	      IF @Stt2 = 1
			  SET @SttParam += N' OR (detail.ComQty > 0 AND detail.ComQty < detail.Qty )'
	      IF @Stt3 = 1
			  SET @SttParam += N' OR detail.ComQty >= detail.Qty'
		  SET @SqlParam += N' AND ( ' + SUBSTRING(@SttParam, 4, LEN(@SttParam) - 3) + ' ) '
	   END
	
	IF @StopTag = 2    --已中止
       SET @SqlParam += N' AND detail.StopTag = 1 '
    ELSE IF @StopTag = 3 --未中止
       SET @SqlParam += N' AND detail.StopTag = 0 '
       
    SET @BaseSql += N', _DATA_Price AS (SELECT GoodsID AS GoodsID1, UnitID AS UnitID1, Unit,BarCode FROM BD_Goods_Price)
					  , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName FROM BD_Dept)
					  , _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName FROM BD_Employee)
                      , _DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName FROM BD_Whs)
                      , _DATA_Ppt1 AS (SELECT Ppt1ID AS _Ppt1ID, Value AS Ppt1Name FROM BD_Goods_Ppt1)
                      , _DATA_Ppt2 AS (SELECT Ppt2ID AS _Ppt2ID, Value AS Ppt2Name FROM BD_Goods_Ppt2)
                      , _DATA_Goods AS (SELECT GoodsID AS GoodsID,Spec,Model,GoodsAbbName,Brand FROM BD_Goods)'  
                   
    SET @DataSql += N' LEFT JOIN _DATA_Price ON Data.GoodsID = _DATA_Price.GoodsID1 AND _DATA_Price.UnitID1 = 1
					   LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID
					   LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID 
					   LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID 
					   LEFT JOIN _DATA_Ppt1 ON Data.Ppt1ID = _DATA_Ppt1._Ppt1ID
					   LEFT JOIN _DATA_Ppt2 ON Data.Ppt2ID = _DATA_Ppt2._Ppt2ID
					   LEFT JOIN _DATA_Goods ON Data.GoodsID = _DATA_Goods.GoodsID' 
	SET @HeadSql = @HeadSql + @Sql + @SqlParam
	IF @IsHistory = 1
	    SET  @Sql = @HeadSql + ' UNION ALL (SELECT ord.BillNo, ord.BillCode, ord.BTypeID, ord.DeptID, ord.ElyID, ord.WhsID, ord.BillDate
											   , CreateTime, ord.Creator AS CreatorID, ord.Summary, ord.[Description]
											   , detail.DID, detail.Ppt1ID, detail.Ppt2ID, detail.GoodsID, detail.Gift, detail.UnitID, detail.Qty 
											   , detail.BSQty, detail.ComQty, detail.TaxPrice, detail.TaxTotal, detail.ComTotal, detail.Remark 
											   , detail.StopTag, goods.GoodsNo, goods.GoodsName, creator.ElyName AS Creator
											   , btype.BTypeCode, btype.BTypeName				   
										 FROM  PD_PchOrdDetail_His detail 
										 INNER JOIN PD_PchOrdBill_His ord ON detail.BillNo = ord.BillNo
										 INNER JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID 
										 LEFT JOIN BD_Employee creator ON creator.ElyID = ord.Creator 
										 INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID '+ @Sql + @SqlParam +')' 
    ELSE
       SET @Sql = @HeadSql    
    SET @Sql = N'SET NOCOUNT ON;'
               + @Sql + ')' + @BaseSql + 
			   N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
						    CROSS JOIN
						   (SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM PagingData ) B
						    WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				   SELECT * FROM DATA ' + @DataSql + ' ORDER BY ROWID'		
				   
	IF @BtypeLimit = 0 OR @KtypeLimit = 0
		SET @Sql = N' SELECT * FROM PD_PchOrdDetail WHERE 1 <> 1'
			
	--print @Sql	
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @DateType INT, @BillStartDate DATETIME, 
							   @BillEndDate DATETIME, @BTypeID VARCHAR(1000), @DeptID VARCHAR(1000), 
							   @ElyID VARCHAR(1000), @WhsID VARCHAR(1000), @BillCode VARCHAR(100), @GoodsNo VARCHAR(50),
							   @GoodsName VARCHAR(100),  @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT,
							   @Ppt1 VARCHAR(10), @Ppt2 VARCHAR(10),  
							   @Summary VARCHAR(256), @Description VARCHAR(100), @Remark VARCHAR(100),
							   @TVP_Com TVP_Type READONLY, @TVP_Dept TVP_Type READONLY,@GoodsID INT, @OperatorID INT ', 
	                         @PageNo, @PageSize, @DateType, @BillStartDate, @BillEndDate, @BTypeID, @DeptID, @ElyID, 
	                         @WhsID, @BillCode, @GoodsNo, @GoodsName,
	                         @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch,
	                          @Ppt1, @Ppt2, @Summary, @Description, @Remark, @TVP_Com, @TVP_Dept,@GoodsID, @OperatorID
							 
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_BuyOrderDetailSum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_BuyOrderDetailSum
GO
/****** Object:  StoredProcedure [UP_PD_BuyOrderDetailQuery]    Script Date: 07/28/2014 11:08:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		qidan
-- Create date:  2014/7/28
-- Description:	 采购订单明细合计
-- =============================================
CREATE PROCEDURE [UP_PD_BuyOrderDetailSum](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @DateType INT = 1,                    --日期类型 1=录单日期,2=制单日期
	 @BillStartDate DATETIME,                    --开始日期
	 @BillEndDate DATETIME,                    --结束日期
	 @BTypeID VARCHAR(1000) = '',            --往来单位
	 @DeptID VARCHAR(1000) = '',            --部门
	 @ElyID VARCHAR(1000) = '',            --经手人
	 @WhsID VARCHAR(1000) = '',            --仓库
     @BillCodeMatch INT = 0,   --单据编号匹配方式
     @BillCode VARCHAR(100) = '', --单据编号
     @GoodsNoMatch INT = 0,   --商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',            --商品编号
     @GoodsNameMatch INT = 0,   --商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(20) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
     @Ppt1Match INT = 0,   --属性1匹配方式
	 @Ppt1 VARCHAR(10) = '',         --属性1
     @Ppt2Match INT = 0,   --属性2匹配方式
	 @Ppt2 VARCHAR(10) = '',         --属性2
     @SummaryMatch INT = 0,   --摘要匹配方式
	 @Summary VARCHAR(256) = '',         --摘要
     @DescMatch INT = 0,   --说明匹配方式
	 @Description VARCHAR(100) = '',         --说明
     @RemarkMatch INT = 0,   --明细备注匹配方式
	 @Remark VARCHAR(100) = '',         --明细备注
	 @GiftStt INT = 1,                    --赠品状态 1=全部,2=是,3=否
	 @Stt1 BIT = 1,         --订单状态 未调用
	 @Stt2 BIT = 1,         --订单状态 部分调用
	 @Stt3 BIT = 1,         --订单状态 已完成
	 @StopTag INT = 1,                    --中止状态 1=全部,2=已中止,3=未中止
	 @OrderStr VARCHAR(50) = '',         --排序字符串
	 @OperatorID INT = 0,                  --操作员ID   
	 @IsHistory BIT = 0,    --是否查询历史记录  
	 /*以下参数在由采购订单汇总查看明细时用到*/
	 @GoodsTypeID INT = 0, --商品分类
	 @GoodsID INT = 0, --商品
	 @WhsTypeID INT = 0, --仓库分类
	 @BtypeTypeID INT = 0, --往来单位分类
	 @AreaID INT = 0 --地区
   ) 
AS
BEGIN
	SET NOCOUNT ON;
		
	DECLARE @Re INT 
	EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @BillStartDate, @isHistory = @IsHistory
	IF @Re = 1 RETURN @Re;
	
	DECLARE @Sql NVARCHAR(MAX) = '', @HeadSql NVARCHAR(MAX) = '',
		    @SqlParam NVARCHAR(1000) = N'',
		    @SttParam NVARCHAR(1000) = N'',
	        @DataSql NVARCHAR(2000) = N'', 
	        @BaseSql NVARCHAR(2000) = N'',
	        @BtypeLimit INT = 0, 
	        @KtypeLimit INT = 0
    DECLARE @TVP_Com AS [TVP_Type]
    DECLARE @TVP_Dept AS [TVP_Type]
	SET @HeadSql = N';With PagingData AS (SELECT ord.BillNo, ord.BillCode, ord.BTypeID, ord.DeptID, ord.ElyID, ord.WhsID, ord.BillDate
											   , CreateTime, ord.Creator AS CreatorID, ord.Summary, ord.[Description]
											   , detail.DID, detail.Ppt1ID, detail.Ppt2ID, detail.GoodsID, detail.Gift, detail.UnitID, detail.Qty 
											   , detail.BSQty, detail.ComQty, detail.TaxPrice, detail.TaxTotal, detail.ComTotal, detail.Remark 
											   , detail.StopTag, goods.GoodsNo, goods.GoodsName, creator.ElyName AS Creator
											   , btype.BTypeCode, btype.BTypeName				   
										 FROM  PD_PchOrdDetail detail 
										 INNER JOIN PD_PchOrdBill ord ON detail.BillNo = ord.BillNo
										 INNER JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID 
										 LEFT JOIN BD_Employee creator ON creator.ElyID = ord.Creator 
										 INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID '
    IF @DateType = 1
       SET @SqlParam = ' WHERE ord.BillDate BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
    ELSE
       SET @SqlParam = ' WHERE ord.CreateTime BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
	   
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)   
	                 
    IF @BtypeLimit = 1  --部份权限
	   SET @Sql +=' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID = ord.BTypeID '
       
    IF @BTypeID <> ''     --往来单位
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = ord.BTypeID '
	   
    IF @DeptID <> ''     --部门
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = ord.DeptID '
         INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
	     SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
	         INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		     WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	   END
	
	IF @GoodsTypeID  <> 0     --商品分类
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _goodsType ON _goodsType.ChildTypeID = goods.GoodsTypeID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM  BD_Goods_Type gt
	         INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
		     WHERE gt.GoodsTypeID = @GoodsTypeID AND cgt.SonNum = 0
	   END
	
	IF @GoodsID  <> 0     --商品
	   SET @SqlParam += N' AND detail.GoodsID = @GoodsID '
	
	IF @BtypeTypeID <> 0     --往来单位分类
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _btypeType ON _btypeType.ChildTypeID = btype.BtypeTypeID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT bt.BtypeTypeID, cbt.BtypeTypeID FROM BD_Btype_Type bt       
	         INNER JOIN BD_Btype_Type cbt ON cbt.[Path] Like bt.[Path] + '%'
		     WHERE bt.BtypeTypeID = @BtypeTypeID AND cbt.SonNum = 0
	   END
      
    --仓库权限                  
    SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)
    
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = ord.WhsID '
	
	IF @WhsTypeID <> 0     --仓库分类
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _whsType ON _whsType.ChildTypeID = ord.WhsID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT cwt.WhsTypeID, w.WhsID FROM BD_Whs w
	         INNER JOIN BD_Whs_Type cwt ON w.WhsTypeID = cwt.WhsTypeID         
	         INNER JOIN BD_Whs_Type wt ON cwt.[Path] Like wt.[Path] + '%'
		     WHERE wt.WhsTypeID = @WhsTypeID AND cwt.SonNum = 0
	   END
	
	IF @AreaID <> 0     --地区
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Com _area ON _area.ChildTypeID = btype.AreaID '
         INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
	     SELECT a.AreaID, ca.AreaID FROM BD_Area a
	         INNER JOIN BD_Area ca ON ca.[Path] Like a.[Path] + '%'
		     WHERE a.AreaID = @AreaID AND ca.SonNum = 0
	   END
	   
    IF @ElyID <> ''     --经手人
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = ord.ElyID '
	   
    IF @WhsID <> ''     --仓库
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = ord.WhsID '
	     							
	IF @BillCode <> ''   --单据编号
	   BEGIN 
		   IF @BillCodeMatch = 0
			   SET @SqlParam += N' AND ord.BillCode LIKE ''%'' + @BillCode +''%'''
		   ELSE IF @BillCodeMatch = 1
			   SET @SqlParam += N' AND ord.BillCode = @BillCode ' 
	   END
	     							
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND goods.GoodsNo = @GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsName = @GoodsName ' 
	   END
	
	IF @Model <> ''      --商品型号
		BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
		END       
		IF @GoodsAbbName <> ''    --商品简名
		BEGIN 
		   IF @GoodsAbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
		   ELSE IF @GoodsAbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
		END       
		IF @Brand <> ''      --商品品牌
		BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
		END
		--商品规格    
		IF @Spec <> ''        
		BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
		END
		--商品条码
		IF @BarCode <> ''      
		BEGIN 
		   SET @Sql += ' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID AND pri.UnitID = 1 '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=detail.GoodsID) '
		   ELSE IF @BarCodeMatch = 1 
	           SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=detail.GoodsID)'
		END
	
	   
	IF @Ppt1 <> ''       --属性一 
	   BEGIN 
		   SET @Sql += N' INNER JOIN BD_Goods_Ppt1 ppt1 ON detail.Ppt1ID = ppt1.Ppt1ID  '
		   IF @Ppt1Match = 0  
			   SET @SqlParam += N' AND ppt1.Value LIKE ''%'' + @Ppt1 +''%'''
		   ELSE IF @Ppt1Match = 1
			   SET @SqlParam += N' AND ppt1.Value = @Ppt1 ' 
	   END 
	   
	IF @Ppt2 <> ''      --属性二
	   BEGIN 
		   SET @Sql += N' INNER JOIN BD_Goods_Ppt2 ppt2 ON detail.Ppt2ID = ppt2.Ppt2ID  ' 
		   IF @Ppt2Match = 0   
			   SET @SqlParam += N' AND ppt2.Value LIKE ''%'' + @Ppt2 +''%'''
		   ELSE IF @Ppt2Match = 1
			   SET @SqlParam += N' AND ppt2.Value = @Ppt2 ' 
	   END 
       							
	IF @Summary <> ''   --摘要 
	   BEGIN 
		   IF @SummaryMatch = 0
			   SET @SqlParam += N' AND ord.Summary LIKE ''%'' + @Summary +''%'''
		   ELSE IF @SummaryMatch = 1
			   SET @SqlParam += N' AND ord.Summary = @Summary ' 
	   END
	   
	IF @Description <> ''  --说明
	   BEGIN 
		   IF @DescMatch = 0
			   SET @SqlParam += N' AND ord.[Description] LIKE ''%'' + @Description +''%'''
		   ELSE IF @DescMatch = 1
			   SET @SqlParam += N' AND ord.[Description] = @Description ' 
	   END
       							
	IF @Remark <> ''   --明细备注 
	   BEGIN 
		   IF @RemarkMatch = 0
			   SET @SqlParam += N' AND detail.Remark LIKE ''%'' + @Remark +''%'''
		   ELSE IF @RemarkMatch = 1
			   SET @SqlParam += N' AND detail.Remark = @Remark ' 
	   END
	   
    IF @GiftStt = 2 --赠品 
       SET @SqlParam += N' AND detail.Gift = 1 '
    ELSE IF @GiftStt = 3 --非赠品
       SET @SqlParam += N' AND detail.Gift = 0 '
       
	IF @Stt1 <> 1 OR @Stt2 <> 1 OR @Stt3 <> 1   --订单状态 未调用 部分调用 已完成
	   BEGIN
	      IF @Stt1 = 1
			  SET @SttParam += N' OR (detail.ComQty = 0 AND detail.StopTag = 0)'
	      IF @Stt2 = 1
			  SET @SttParam += N' OR (detail.ComQty > 0 AND detail.ComQty < detail.Qty AND detail.StopTag = 0)'
	      IF @Stt3 = 1
			  SET @SttParam += N' OR detail.ComQty >= detail.Qty OR detail.StopTag = 1'
		  SET @SqlParam += N' AND ( ' + SUBSTRING(@SttParam, 4, LEN(@SttParam) - 3) + ' ) '
	   END
	
	IF @StopTag = 2    --已中止
       SET @SqlParam += N' AND detail.StopTag = 1 '
    ELSE IF @StopTag = 3 --未中止
       SET @SqlParam += N' AND detail.StopTag = 0 '
       
    SET @BaseSql += N', _DATA_Price AS (SELECT GoodsID AS GoodsID1, UnitID AS UnitID1, Unit,BarCode FROM BD_Goods_Price)
					  , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName FROM BD_Dept)
					  , _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName FROM BD_Employee)
                      , _DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName FROM BD_Whs)
                      , _DATA_Ppt1 AS (SELECT Ppt1ID AS _Ppt1ID, Value AS Ppt1Name FROM BD_Goods_Ppt1)
                      , _DATA_Ppt2 AS (SELECT Ppt2ID AS _Ppt2ID, Value AS Ppt2Name FROM BD_Goods_Ppt2)
                      , _DATA_Goods AS (SELECT GoodsID AS GoodsID,Spec,Model,GoodsAbbName,Brand FROM BD_Goods)'  
                   
    SET @DataSql += N' LEFT JOIN _DATA_Price ON Data.GoodsID = _DATA_Price.GoodsID1 AND _DATA_Price.UnitID1 = 1
					   LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID
					   LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID 
					   LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID 
					   LEFT JOIN _DATA_Ppt1 ON Data.Ppt1ID = _DATA_Ppt1._Ppt1ID
					   LEFT JOIN _DATA_Ppt2 ON Data.Ppt2ID = _DATA_Ppt2._Ppt2ID
					   LEFT JOIN _DATA_Goods ON Data.GoodsID = _DATA_Goods.GoodsID' 
	SET @HeadSql = @HeadSql + @Sql + @SqlParam
	IF @IsHistory = 1
	    SET  @Sql = @HeadSql + ' UNION ALL (SELECT ord.BillNo, ord.BillCode, ord.BTypeID, ord.DeptID, ord.ElyID, ord.WhsID, ord.BillDate
											   , CreateTime, ord.Creator AS CreatorID, ord.Summary, ord.[Description]
											   , detail.DID, detail.Ppt1ID, detail.Ppt2ID, detail.GoodsID, detail.Gift, detail.UnitID, detail.Qty 
											   , detail.BSQty, detail.ComQty, detail.TaxPrice, detail.TaxTotal, detail.ComTotal, detail.Remark 
											   , detail.StopTag, goods.GoodsNo, goods.GoodsName, creator.ElyName AS Creator
											   , btype.BTypeCode, btype.BTypeName				   
										 FROM  PD_PchOrdDetail_His detail 
										 INNER JOIN PD_PchOrdBill_His ord ON detail.BillNo = ord.BillNo
										 INNER JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID 
										 LEFT JOIN BD_Employee creator ON creator.ElyID = ord.Creator 
										 INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID '+ @Sql + @SqlParam +')' 
    ELSE
       SET @Sql = @HeadSql    
    SET @Sql = N'SET NOCOUNT ON;'
               + @Sql + ')' + @BaseSql + 
			   N', DATA AS (SELECT BSQty,TaxTotal,ComQty,ComTotal,
								 CASE WHEN StopTag=1 AND (BSQty - ComQty)>0 THEN (BSQty - ComQty) ELSE 0 END AS StopQty,
								 CASE WHEN StopTag=1 THEN 0 ELSE (BSQty - ComQty) END AS notComQty,
								 CASE WHEN (TaxTotal-ComTotal)>0 AND StopTag=1 THEN (TaxTotal-ComTotal) ELSE 0 END AS StopTotal,
								 CASE WHEN (TaxTotal-ComTotal)>0 AND StopTag=0 THEN (TaxTotal-ComTotal) ELSE 0 END AS NotComTotal,
								 CASE WHEN (TaxTotal-ComTotal)<0 THEN -(TaxTotal-ComTotal) ELSE 0 END  OverTotal,
								 CASE WHEN (comQty - bsQty)>0 THEN (comQty - bsQty) ELSE 0 END AS OverQty 
							FROM PagingData )
				   SELECT SUM(BSQty) AS BSQty,SUM(TaxTotal) AS TaxTotal,SUM(ComQty) AS ComQty,SUM(ComTotal) AS ComTotal,
						SUM(StopQty) AS StopQty,SUM(notComQty) AS notComQty,SUM(notComQty) AS notComQty,SUM(StopTotal) AS StopTotal,
						SUM(NotComTotal) AS NotComTotal,SUM(OverTotal) AS OverTotal,SUM(OverQty) AS OverQty 
				   FROM DATA  '		
				   
	IF @BtypeLimit = 0 OR @KtypeLimit = 0
		SET @Sql = N' SELECT * FROM PD_PchOrdDetail WHERE 1 <> 1'
			
	print @Sql	
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @DateType INT, @BillStartDate DATETIME, 
							   @BillEndDate DATETIME, @BTypeID VARCHAR(1000), @DeptID VARCHAR(1000), 
							   @ElyID VARCHAR(1000), @WhsID VARCHAR(1000), @BillCode VARCHAR(100), @GoodsNo VARCHAR(50),
							   @GoodsName VARCHAR(100),  @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(50), @BarCodeMatch INT,
							   @Ppt1 VARCHAR(10), @Ppt2 VARCHAR(10),  
							   @Summary VARCHAR(256), @Description VARCHAR(100), @Remark VARCHAR(100),
							   @TVP_Com TVP_Type READONLY, @TVP_Dept TVP_Type READONLY,@GoodsID INT, @OperatorID INT ', 
	                         @PageNo, @PageSize, @DateType, @BillStartDate, @BillEndDate, @BTypeID, @DeptID, @ElyID, 
	                         @WhsID, @BillCode, @GoodsNo, @GoodsName,
	                         @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch,
	                          @Ppt1, @Ppt2, @Summary, @Description, @Remark, @TVP_Com, @TVP_Dept,@GoodsID, @OperatorID
							 
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_BuyOrderSummary]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_BuyOrderSummary
GO
/****** Object:  StoredProcedure [UP_PD_BuyOrderSummary]    Script Date: 07/28/2014 11:09:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/28
-- Description:	 采购订单汇总查询
-- =============================================
CREATE PROCEDURE [UP_PD_BuyOrderSummary](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @DateType INT = 1,                    --日期类型 1=录单日期,2=制单日期
	 @BillStartDate DATETIME,                    --开始日期
	 @BillEndDate DATETIME,                    --结束日期
	 @BTypeID VARCHAR(1000) = '',            --往来单位
	 @DeptID VARCHAR(1000) = '',            --部门
	 @ElyID VARCHAR(1000) = '',            --经手人
	 @WhsID VARCHAR(1000) = '',            --仓库
     @GoodsNoMatch INT = 0,   --商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',            --商品编号
     @GoodsNameMatch INT = 0,   --商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 ---------------update sunzhiyuan 20150906--------------------
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	 ---------------update sunzhiyuan 20150906--------------------
     @SummaryMatch INT = 0,   --摘要匹配方式
	 @Summary VARCHAR(256) = '',         --摘要
     @DescMatch INT = 0,   --说明匹配方式
	 @Description VARCHAR(100) = '',         --说明
     @RemarkMatch INT = 0,   --明细备注匹配方式
	 @Remark VARCHAR(100) = '',         --明细备注
	 @GiftStt INT = 1,                    --赠品状态 1=全部,2=是,3=否
	 @SumParam INT = 0,                   --汇总条件
	 @SumLevel INT = 0,                   --汇总等级
	 @OrderStr VARCHAR(50) = '',         --排序字符串   
	 @OperatorID INT = 0,                  --操作员ID 
	 @IsHistory BIT = 0,    --是否查询历史记录 
	 @SumOrNot INT = 0     --是否为合计形式
   ) 
AS
BEGIN
	SET NOCOUNT ON;
		
	DECLARE @Re INT 
	EXECUTE @Re = UP_OT_CheckHistoryTime @BillStartDate = @BillStartDate, @isHistory = @IsHistory
	IF @Re = 1 RETURN @Re;
	
	DECLARE @HeadSql NVARCHAR(MAX), 
	        @Sql NVARCHAR(MAX) = N'', 
	        @SqlGroup NVARCHAR(1000) = N'',
		    @SqlParam NVARCHAR(1000) = N'',
	        @DataSql NVARCHAR(2000) = N'', 
	        @BaseSql NVARCHAR(2000) = N'',
	        @TypeIDCol NVARCHAR(50) = N'',
	        @BtypeLimit INT = 0, 
	        @KtypeLimit INT = 0,
	        @BaseCols NVARCHAR(2000) = N''
    DECLARE @TVP_Dept AS [TVP_Type], @TVP_GoodsType AS [TVP_Type]   
                  
    IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
       BEGIN
		   SET @Sql += ' INNER JOIN BD_Goods goods ON goods.GoodsID = detail.GoodsID '
		   SET @TypeIDCol = ' , goods.GoodsTypeID '
	   END
	
	-- 条码
	IF @BarCode <> ''
	BEGIN 
		SET @Sql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = detail.GoodsID and pri.UnitID = 1 '
	END    
	
	   
    IF @DateType = 1
       SET @SqlParam = ' WHERE ord.BillDate BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
    ELSE
       SET @SqlParam = ' WHERE ord.CreateTime BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
	   
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)
	                    
    IF @BtypeLimit = 1  --部份权限
	   SET @Sql +=' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID = ord.BTypeID '
       
    IF @BTypeID <> ''     --往来单位
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = ord.BTypeID '
	   
    IF @DeptID <> ''     --部门
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = ord.DeptID '
         INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
	     SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
	         INNER JOIN BD_Dept cd ON cd.[Path] LIKE d.[Path] + '%'
		     WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	   END
	   
    IF @ElyID <> ''     --经手人
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = ord.ElyID '
	   
    IF @WhsID <> ''     --仓库
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = ord.WhsID '
     
    --仓库权限   
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)       
	        
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = ord.WhsID '
	     							
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND goods.GoodsNo = @GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsName = @GoodsName ' 
	   END
     
    --商品型号
    IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @Sql += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @Sql += N' AND goods.Model = @Model ' 
	END       
	--商品简名
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @Sql += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @Sql += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @Sql += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @Sql += N' AND goods.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
	   IF @SpecMatch = 0
		   SET @Sql += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @Sql += N' AND goods.Spec = @Spec '  
	END
	--商品条码
	IF @BarCode <> ''      
	BEGIN 
	IF @BarCodeMatch = 0
	   SET @Sql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=detail.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @Sql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=detail.GoodsID)'
	END
	--IF @BarCode <> ''      
	--BEGIN 
	--   IF @BarCodeMatch = 0
	--	   SET @Sql += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	--   ELSE IF @BarCodeMatch = 1
	--	   SET @Sql += N' AND pri.BarCode = @BarCode ' 
	--END 
       							
	IF @Summary <> ''   --摘要 
	   BEGIN 
		   IF @SummaryMatch = 0
			   SET @SqlParam += N' AND ord.Summary LIKE ''%'' + @Summary +''%'''
		   ELSE IF @SummaryMatch = 1
			   SET @SqlParam += N' AND ord.Summary = @Summary ' 
	   END
	   
	IF @Description <> ''  --说明
	   BEGIN 
		   IF @DescMatch = 0
			   SET @SqlParam += N' AND ord.[Description] LIKE ''%'' + @Description +''%'''
		   ELSE IF @DescMatch = 1
			   SET @SqlParam += N' AND ord.[Description] = @Description ' 
	   END
       							
	IF @Remark <> ''   --明细备注
	   BEGIN 
		   IF @RemarkMatch = 0 
			   SET @SqlParam += N' AND detail.Remark LIKE ''%'' + @Remark +''%'''
		   ELSE IF @RemarkMatch = 1
			   SET @SqlParam += N' AND detail.Remark = @Remark ' 
	   END
	   
    IF @GiftStt = 2 --赠品 
       SET @SqlParam += N' AND detail.Gift = 1 '
    ELSE IF @GiftStt = 3 --非赠品
       SET @SqlParam += N' AND detail.Gift = 0 '    
       
    SET @HeadSql = ';WITH OrdDATA AS (SELECT ord.BTypeID, ord.WhsID, ord.DeptID, ord.ElyID, detail.BSQty, detail.TaxTotal, detail.ComQty, 
										detail.ComTotal, detail.StopTag, detail.GoodsID '+ @TypeIDCol +' FROM PD_PchOrdBill ord  
								  INNER JOIN PD_PchOrdDetail detail ON detail.BillNo = ord.BillNo ' + @Sql + @SqlParam
    IF @IsHistory = 1
	    SET @HeadSql += ' UNION ALL (SELECT ord.BTypeID, ord.WhsID, ord.DeptID, ord.ElyID, detail.BSQty, detail.TaxTotal, detail.ComQty, 
										detail.ComTotal, detail.StopTag, detail.GoodsID '+ @TypeIDCol +' FROM PD_PchOrdBill_His ord  
								  INNER JOIN PD_PchOrdDetail_His detail ON detail.BillNo = ord.BillNo ' + @Sql + @SqlParam +' ) '
    SET @HeadSql += ' ), PagingData AS 
					(SELECT SUM(ord.BSQty) AS Qty, SUM(ord.TaxTotal) AS Total, SUM(ord.ComQty) AS ComQty, SUM(ord.ComTotal) AS ComTotal
						  , SUM(CASE WHEN ord.StopTag = 1 AND ord.BSQty - ord.ComQty > 0 THEN ord.BSQty - ord.ComQty ELSE 0 END) AS StopQty
						  , SUM(CASE WHEN ord.StopTag = 1 AND ord.TaxTotal - ord.ComTotal > 0 THEN ord.TaxTotal - ord.ComTotal ELSE 0 END) AS StopTotal '
    SET @Sql = ' FROM OrdDATA ord ' 
	
	   
	IF @SumParam = 1 --汇总层级：商品分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
	          SET @HeadSql += ', parGoodsType.BaseID AS GoodsTypeID'
	          IF @GoodsNo = '' AND @GoodsName = ''
				  SET @Sql += ' INNER JOIN BD_Goods goods ON goods.GoodsID = ord.GoodsID
				                INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @SumLevel) parGoodsType ON parGoodsType.ParID = goods.GoodsTypeID '
			  ELSE
				  SET @Sql += ' INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @SumLevel) parGoodsType ON parGoodsType.ParID = ord.GoodsTypeID '
			  SET @SqlGroup += ', parGoodsType.BaseID '
			  SET @BaseCols += ', Data.GoodsTypeCode AS Code, Data.GoodsTypeName AS Name '
	        END
	     ELSE IF @SumLevel = 6  --商品
            BEGIN
			  SET @HeadSql += ', ord.GoodsID '
			  SET @SqlGroup += ', ord.GoodsID '
			  SET @BaseCols += ', Data.GoodsNo AS Code, Data.GoodsName AS Name '
	        END
	   END
	   
	IF @SumParam = 2 --汇总层级：往来单位分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
	          SET @HeadSql += ', parBtypeType.BaseID AS BtypeTypeID'  --BaseID 代表层级分类ID，ParID 代表分类ID 
	          SET @Sql += ' INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID
	                        INNER JOIN dbo.UF_BD_BaseSummary(''BTYPE'', @SumLevel) parBtypeType ON parBtypeType.ParID = btype.BtypeTypeID '
			  SET @SqlGroup += ', parBtypeType.BaseID '
			  SET @BaseCols += ', Data.BtypeTypeCode AS Code, Data.BtypeTypeName AS Name '
	        END
	     ELSE IF @SumLevel = 6  --往来单位
            BEGIN
			  SET @HeadSql += ', ord.BTypeID '
			  SET @SqlGroup += ', ord.BTypeID '
			  SET @BaseCols += ', Data.BTypeCode AS Code, Data.BTypeName AS Name '
	        END
	   END
	   
	IF @SumParam = 3 --汇总层级：仓库分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
	          SET @HeadSql += ', parWhsType.BaseID AS WhsTypeID'
	          SET @Sql += ' INNER JOIN BD_Whs whs ON whs.WhsID = ord.WhsID
	                        INNER JOIN dbo.UF_BD_BaseSummary(''KTYPE'', @SumLevel) parWhsType ON parWhsType.ParID = whs.WhsTypeID '
			  SET @SqlGroup += ', parWhsType.BaseID '
			  SET @BaseCols += ', Data.WhsTypeCode AS Code, Data.WhsTypeName AS Name '
	        END
	     ELSE IF @SumLevel = 6  --仓库
            BEGIN
			  SET @HeadSql += ', ord.WhsID '
			  SET @SqlGroup += ', ord.WhsID '
			  SET @BaseCols += ', Data.WhsNO AS Code, Data.WhsName AS Name '
	        END
	   END
	   
	IF @SumParam = 4 --汇总层级：地区
	   BEGIN
          SET @HeadSql += ', parArea.BaseID AS AreaID'
          SET @Sql += ' INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID
                        INNER JOIN dbo.UF_BD_BaseSummary(''AREA'', @SumLevel) parArea ON parArea.ParID = btype.AreaID '
		  SET @SqlGroup += ', parArea.BaseID '
		  SET @BaseCols += ', Data.AreaNO AS Code, Data.AreaName AS Name '
	   END
	   
	IF @SumParam = 5 --汇总层级：部门
	   BEGIN
          SET @HeadSql += ', parDept.BaseID AS DeptID'
          SET @Sql += ' INNER JOIN dbo.UF_BD_BaseSummary(''DTYPE'', @SumLevel) parDept ON parDept.ParID = ord.DeptID '
		  SET @SqlGroup += ', parDept.BaseID '
		  SET @BaseCols += ', Data.DeptCode AS Code, Data.DeptName AS Name '
	   END
	   
	IF @SumParam = 6 --汇总层级：职员
	   BEGIN
          SET @HeadSql += ', ord.ElyID'
		  SET @SqlGroup += ', ord.ElyID '
		  SET @BaseCols += ', Data.ElyCode AS Code, Data.ElyName AS Name '
	   END
	SET @Sql = @HeadSql + @Sql + ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1)  + ' )'
    SET @Sql += N', MainData AS (SELECT PagingData.* ' 
    IF @SumParam = 1 AND @SumLevel <> 6
		SET @Sql += N', g.TypeCode AS GoodsTypeCode, g.TypeName AS GoodsTypeName FROM PagingData
		              INNER JOIN BD_Goods_Type g on g.GoodsTypeID = PagingData.GoodsTypeID' 
	ELSE IF @SumParam = 1 AND @SumLevel = 6         
        SET @Sql += N', goods.GoodsNo, goods.GoodsName,goods.Model,goods.GoodsAbbName,goods.Brand,goods.Spec,pri.BarCode FROM PagingData
				      INNER JOIN BD_Goods goods on goods.GoodsID = PagingData.GoodsID
                      INNER JOIN BD_Goods_Price pri ON pri.GoodsID = PagingData.GoodsID and pri.UnitID = 1 '    
	ELSE IF @SumParam = 2 AND @SumLevel <> 6
		SET @Sql += N', b.TypeCode AS BtypeTypeCode, b.TypeName AS BtypeTypeName FROM PagingData
		              INNER JOIN BD_Btype_Type b on b.BtypeTypeID = PagingData.BtypeTypeID ' 
	ELSE IF @SumParam = 2 AND @SumLevel = 6
		SET @Sql += N', btype.BTypeCode, btype.BTypeName FROM PagingData
		              INNER JOIN BD_Btype btype on btype.BTypeID = PagingData.BTypeID ' 
	ELSE IF @SumParam = 3 AND @SumLevel <> 6
		SET @Sql += N', w.TypeCode AS WhsTypeCode, w.TypeName AS WhsTypeName FROM PagingData
		              INNER JOIN BD_Whs_Type w on w.WhsTypeID = PagingData.WhsTypeID ' 
	ELSE IF @SumParam = 3 AND @SumLevel = 6
		SET @Sql += N', whs.WhsNO, whs.WhsName FROM PagingData
		             INNER JOIN BD_Whs whs on whs.WhsID = PagingData.WhsID ' 
	ELSE IF @SumParam = 4
		SET @Sql += N', a.AreaNO, a.AreaName FROM PagingData 
		             INNER JOIN BD_Area a on a.AreaID = PagingData.AreaID ' 
	ELSE IF @SumParam = 5
		SET @Sql += N', d.DeptCode, d.DeptName FROM PagingData 
		             INNER JOIN BD_Dept d on d.DeptID = PagingData.DeptID ' 
	ELSE IF @SumParam = 6
		SET @Sql += N', e.ElyCode, e.ElyName FROM PagingData 
		             INNER JOIN BD_Employee e on e.ElyID = PagingData.ElyID ' 
    SET @Sql += N')'  
    
    IF @SumOrNot = 0
    BEGIN
		SET @Sql=N'SET NOCOUNT ON;'
             + @Sql + 
			 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM MainData) A 
						 CROSS JOIN
						(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM MainData) B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				SELECT *, Qty - StopQty - ComQty AS NotComQty, Total - StopTotal - ComTotal AS NotComTotal ' + @BaseCols + ' FROM DATA ORDER BY ROWID'
    END
    IF @SumOrNot = 1
    BEGIN
		SET @Sql=N'SET NOCOUNT ON;'
             + @Sql + 
			 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM MainData) A 
						 CROSS JOIN
						(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM MainData) B)
				SELECT SUM(Qty)[Qty],SUM(Total)[Total],
					   SUM(StopQty)[StopQty],SUM(StopTotal)[StopTotal],
					   SUM(ComQty)[ComQty],SUM(ComTotal)[ComTotal],
					   SUM(Qty - StopQty - ComQty) AS NotComQty, SUM(Total - StopTotal - ComTotal) AS NotComTotal  FROM DATA '
    END
	
	IF @BtypeLimit = 0 OR @KtypeLimit = 0
		SET @Sql = N' SELECT * FROM PD_PchOrdBill WHERE 1 <> 1'
				
	PRINT @Sql
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @DateType INT, @BillStartDate DATETIME, 
							   @BillEndDate DATETIME, @BTypeID VARCHAR(1000), @DeptID VARCHAR(1000), 
							   @ElyID VARCHAR(1000), @WhsID VARCHAR(1000), @GoodsNo VARCHAR(50),
							   @GoodsName VARCHAR(100), @Summary VARCHAR(256), @Description VARCHAR(100), @OperatorID INT,@SumOrNot INT,
							   @Remark VARCHAR(100), @SumLevel INT, @TVP_Dept TVP_Type READONLY, @TVP_GoodsType TVP_Type READONLY 
							   , @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT ', 
	                         @PageNo, @PageSize, @DateType, @BillStartDate, @BillEndDate, @BTypeID, @DeptID, @ElyID, 
	                         @WhsID, @GoodsNo, @GoodsName, @Summary, @Description, @OperatorID,@SumOrNot, @Remark, @SumLevel, @TVP_Dept, @TVP_GoodsType
	                         , @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
END
GO




if exists (select * from sysobjects where id = object_id(N'[UP_PD_CashBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_PD_CashBill]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		雷洋
-- Create date:  2014/6/17
-- Description:	 调价单
-- =============================================
CREATE PROCEDURE [UP_PD_CashBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	declare @IsAccounts int =0
	if exists(select 1 from PD_MulAccounts where BillTypeID = 403 and BillNo = @BillNo)
		select @IsAccounts = 1
		
	if exists( select 1 from MF_FeeRecBill where BillNo = @BillNo)
	begin
		select  BillNo,
			BillTypeID,
			BillDate,
			BillCode,
			Bill.DeptID,
			Bill.ElyID,
			CASE @IsAccounts WHEN 0 THEN bill.FinanceID ELSE -100 end as FinanceID,
			--bill.FinanceID,
			Total,
			Creator,
			PosElyID,
			Summary,
			Description,
			IsDraft,
			Red,
			CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '【多账户】' end as FinanceName,
			--f.FinanceName,
			d.DeptName,
			e.ElyName,
			ec.ElyName as CreatorName,
			ep.ElyName as PosName,
			@IsAccounts as IsAccounts,
			bill.AuditStatus
			from MF_FeeRecBill bill
		LEFT JOIN BD_Finance f ON bill.FinanceID = f.FinanceID
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 where BillNo = @BillNo
	     
		  SELECT	  detail.[DID]
			  ,detail.[BillNo]
			  ,detail.FinanceID
			  ,detail.Total
			  ,detail.[Remark]
			  ,f.FinanceNO
			  ,f.FinanceName
	 FROM MF_FeeRecDetail detail
		  INNER JOIN BD_Finance F ON detail.FinanceID=f.FinanceID	
	 WHERE detail.BillNo = @BillNo;  --查询明细 
	 
		SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 403 and BillNo = @BillNo    
 End 
 Else
 BEGIN
			select  BillNo,
			BillTypeID,
			BillDate,
			BillCode,
			Bill.DeptID,
			Bill.ElyID,
			CASE @IsAccounts WHEN 0 THEN bill.FinanceID ELSE -100 end as FinanceID,
			Total,
			Creator,
			PosElyID,
			Summary,
			Description,
			IsDraft,
			Red,
			CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '【多账户】' end as FinanceName,
			--f.FinanceName,
			d.DeptName,
			e.ElyName,
			ec.ElyName as CreatorName,
			ep.ElyName as PosName,
			@IsAccounts as IsAccounts,
			bill.AuditStatus			
			from MF_FeeRecBill_His bill
		LEFT JOIN BD_Finance f ON bill.FinanceID = f.FinanceID
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 where BillNo = @BillNo
	     
		  SELECT	  detail.[DID]
			  ,detail.[BillNo]
			  ,detail.FinanceID
			  ,detail.Total
			  ,detail.[Remark]
			  ,f.FinanceNO
			  ,f.FinanceName
	 FROM MF_FeeRecDetail_His detail
		  INNER JOIN BD_Finance F ON detail.FinanceID=f.FinanceID	
	 WHERE detail.BillNo = @BillNo;  --查询明细
	 
		SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 403 and BillNo = @BillNo    
	 
 END                                           
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_ChangeIsReconciled]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_ChangeIsReconciled]
GO
/****** Object:  StoredProcedure [UP_PD_GetGoodsPrice]    Script Date: 06/16/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		leiyang
-- Create date:  2014/7/22
-- Description:	 修改往来对账标记
-- =============================================
CREATE PROCEDURE [UP_PD_ChangeIsReconciled]
(
	@BillTypeID INT=0,
	@BillNo INT =0,
	@IsReconciled INT=0,
	@GoodsID INT=0,
	@FinanceID INT=0,
	@BtypeID INT=0,
	@Ppt1ID Int =0,
	@Ppt2ID Int = 0
) 
AS
BEGIN
	if(@GoodsID <>0)
	BEGIN
		Declare @Sql nvarchar(max) = ''	
		SELECT @Sql += 'UPDATE ' + BillDetail + ' Set IsReconciled = @IsReconciled where BillNo = @BillNo And GoodSID= @GoodsID And Ppt1ID= @Ppt1ID And Ppt2ID = @Ppt2ID '
		from PD_BillType where BillTypeID = @BillTypeID
		exec sp_executesql @sql,N'@IsReconciled Int,@BillNo Int,@GoodsID Int,@Ppt1ID INT,@Ppt2ID INT',@IsReconciled,@BillNo,@GoodsID,@Ppt1ID,@Ppt2ID
	END
	Else
	BEGIN
		UPDATE PD_ListTable  Set IsReconciled = @IsReconciled where BillNo = @BillNo And BillTypeID= @BillTypeID AND FinanceID = @FinanceID	AND BtypeID=@BtypeID	
	END
END
GO




if exists (select * from sysobjects where id = object_id(N'[UP_PD_GetAbnormalStock]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [UP_PD_GetAbnormalStock]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2015-1-30
	描述：异常库存数据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_GetAbnormalStock]
(
	@WhsID INT=0			--仓库ID	
)
AS
SET NOCOUNT ON
	;with StockData as(
select StockID,WhsID,GoodsID,Qty,0 as Price,Total from PD_GoodsStock where WhsID=@WhsID and Qty = 0 and Total <> 0
union all
select StockID,WhsID,GoodsID,Qty,Price,Total from PD_GoodsStock where WhsID=@WhsID and Qty > 0 and Total < 0
)

select a.*,gpr1.BarCode,gpr1.Unit,gpr1.UnitID,gpr1.Convfactor,
		a.Qty as BSQty,A.Price as CostPrice,A.Price as GoodsCostPrice,
		0 as AdjPrice,a.Total as CostTotal,
		0 as AdjTotal,'' as [Remark]
		,g.GoodsNo
	  ,g.GoodsName
	  ,g.Model
	  ,g.Spec 
	  ,gpr1.Convfactor as Convfactor1
	  ,ISNULL(gpr2.Convfactor,1) as Convfactor2
	  ,ISNULL(gpr3.Convfactor,1) as Convfactor3
	  ,gpr1.BarCode[BarCode1],gpr2.BarCode[BarCode2],gpr3.BarCode[BarCode3]
	  ,gpr1.Unit as Unit1
	  ,gpr2.Unit as Unit2
	  ,gpr3.Unit as Unit3
	from StockData A
	inner join BD_Goods G on a.GoodsID = g.GoodsID
	  LEFT JOIN BD_Goods_Price gpr1 ON g.GoodsID = gpr1.GoodsID and gpr1.UnitID = 1
	  LEFT JOIN BD_Goods_Price gpr2 ON g.GoodsID = gpr2.GoodsID and gpr2.UnitID = 2
	  LEFT JOIN BD_Goods_Price gpr3 ON g.GoodsID = gpr3.GoodsID and gpr3.UnitID = 3
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_GetGoodsPrice]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_GetGoodsPrice
GO
/****** Object:  StoredProcedure [UP_PD_GetGoodsPrice]    Script Date: 06/16/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		hanlin
-- Create date:  2014/6/16
-- Description:	 查询商品的价格
-- =============================================
CREATE PROCEDURE [UP_PD_GetGoodsPrice]
(
	@GoodsID INT=0,
	@BTypeID INT =0,
	@WhsID INT=0,
	@UnitID INT=0,
	@UserID int=0
) 
AS
BEGIN
	DECLARE @PrePrice DECIMAL(20,8)=0,@CostPrice DECIMAL(20,8)=0,@PriceType varchar(10),@Convfactor DECIMAL(20,8)=1
	
	SELECT top 1 @PrePrice = ROUND(PchDis*PchPrice,8)  FROM PD_PriceTrail WHERE GoodsID=@GoodsID AND UnitID=@UnitID ORDER BY  PchDate DESC
	
	SELECT @Convfactor=Convfactor FROM BD_Goods_Price WHERE UnitID=@UnitID AND GoodsID=@GoodsID
	SELECT @CostPrice=ROUND(@Convfactor*Price,8) FROM PD_GoodsStock WHERE GoodsID=@GoodsID AND WhsID=@WhsID 
	
	select a.Price,a.PriceLvl,n.DisplayName PriceType from 
	(
		SELECT Price,PriceType,REPLACE(PriceType,'Price','') PriceLvl FROM BD_Goods_Price G 
		UNPIVOT(Price FOR PriceType IN(price1,price2,price3,price4,price5,price6,price7,price8,price9,price10
		,price11,price12,price13,price14,price15)) AS Total 
		INNER JOIN BD_PriceName n on n.PriceID=substring(PriceType,6,2)
		where n.IsDisplay in(1,2) AND  Total.Goodsid=@GoodsID	AND Total.UnitID=@UnitID
		UNION ALL
		SELECT @PrePrice,'最近进价',22 PriceLvl
		UNION ALL
		SELECT @CostPrice,'库存均价',23 PriceLvl
	)a
	inner join dbo.UF_OT_GoodsPriceLimit(@UserID) p on a.pricelvl=p.pricelvl
	inner join BD_PriceName n on a.PriceLvl=N.PriceID 
	if @BTypeID=0
		select 0 as priceid,'' as displayname
	else
		select n.priceid,n.displayname From bd_btype b
						INNER JOIN BD_PriceName n  ON b.PriceLvl=n.PriceID		
								
		 where Btypeid=@Btypeid
END
GO




if exists (select * from sysobjects where id = object_id(N'[UP_PD_GetSaleInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [UP_PD_GetSaleInfo]
GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2015-1-30
	描述：库存分布销售信息查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_GetSaleInfo]
(
	@GoodsID INT=0,				--查询商品ID	
	@OperatorID Int=0
)
AS
SET NOCOUNT ON
	declare @WeekStartDate date = DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)
	declare @MonthStartDate date,@YearStartDate date,@EndDate date,@Sql Nvarchar(Max)='',@LimitKtypeSql Nvarchar(Max)='',@KtypeLimit INT=0,@SqlCreateTable varchar(max)= ''
	Select @MonthStartDate = DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)
	Select @YearStartDate = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
	select @EndDate = GETDATE()
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF @KtypeLimit = 1
	Begin
		if not exists(select 1 from SS_Role_Jur rj inner join SS_Role r on rj.RoleID = r.RoleID inner join SS_Oper_Role op on r.RoleID = op.RoleID where rj.JurID =  1431010 and rj.opp = 1 and op.OperID = @OperatorID )
		begin
			SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
			SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
		End
	End
	select @Sql +=@SqlCreateTable +'
	;with SaleDate as(
		select SUM(BSQty) as WeekSaleQty,SUM(DiscTotal) as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @WeekStartDate AND @EndDate And IsDraft = 0 And Red=0  
		Union All
		select SUM(BSQty) as WeekSaleQty,SUM(DiscTotal) as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @WeekStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,SUM(BSQty) as MonthSaleQty,SUM(DiscTotal) as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @MonthStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,SUM(BSQty) as MonthSaleQty,SUM(DiscTotal) as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @MonthStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,SUM(BSQty) as YearSaleQty,SUM(DiscTotal) as YearSaleTotal from PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @YearStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,SUM(BSQty) as YearSaleQty,SUM(DiscTotal) as YearSaleTotal from PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @YearStartDate AND @EndDate And IsDraft = 0 And Red=0 
	),RetDate as(
		select SUM(BSQty) as WeekSaleQty,SUM(DiscTotal) as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @WeekStartDate AND @EndDate And IsDraft = 0 And Red=0  
		Union All
		select SUM(BSQty) as WeekSaleQty,SUM(DiscTotal) as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellRetBill_His bill INNER JOIN PD_SellRetDetail_His detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @WeekStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,SUM(BSQty) as MonthSaleQty,SUM(DiscTotal) as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @MonthStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,SUM(BSQty) as MonthSaleQty,SUM(DiscTotal) as MonthSaleTotal,0 as YearSaleQty ,0 as YearSaleTotal from PD_SellRetBill_His bill INNER JOIN PD_SellRetDetail_His detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @MonthStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,SUM(BSQty) as YearSaleQty,SUM(DiscTotal) as YearSaleTotal from PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @YearStartDate AND @EndDate And IsDraft = 0 And Red=0 
		Union All
		select 0 as WeekSaleQty,0 as WeekSaleTotal,0 as MonthSaleQty,0 as MonthSaleTotal,SUM(BSQty) as YearSaleQty,SUM(DiscTotal) as YearSaleTotal from PD_SellRetBill_His bill INNER JOIN PD_SellRetDetail_His detail on bill.BillNo = detail.BillNo '+@LimitKtypeSql+' where GoodsID = @GoodsID And Bill.BillDate BETWEEN @YearStartDate AND @EndDate And IsDraft = 0 And Red=0 
	),AllSaleDate as(
		select SUM(WeekSaleQty) as SaleWeekSaleQty,SUM(WeekSaleTotal) as SaleWeekSaleTotal
			   ,SUM(MonthSaleQty) as SaleMonthSaleQty,SUM(MonthSaleTotal) as SaleMonthSaleTotal
			   ,SUM(YearSaleQty) as SaleYearSaleQty,SUM(YearSaleTotal) as SaleYearSaleTotal
		from SaleDate
	),AllRetDate as(
		select SUM(WeekSaleQty) as RetWeekSaleQty,SUM(WeekSaleTotal) as RetWeekSaleTotal
		   ,SUM(MonthSaleQty) as RetMonthSaleQty,SUM(MonthSaleTotal) as RetMonthSaleTotal
		   ,SUM(YearSaleQty) as RetYearSaleQty,SUM(YearSaleTotal) as RetYearSaleTotal
		from RetDate
	),AllDateSum as(
		select @GoodsID as GoodsID,SUM(a.SaleWeekSaleQty) - SUM(b.RetWeekSaleQty) as WeekSaleQty,SUM(a.SaleWeekSaleTotal)-SUM(b.RetWeekSaleTotal) as WeekSaleTotal
			   ,SUM(a.SaleMonthSaleQty)-SUM(b.RetMonthSaleQty) as MonthSaleQty,SUM(a.SaleMonthSaleTotal)-SUM(b.RetMonthSaleTotal) as MonthSaleTotal
			   ,SUM(a.SaleYearSaleQty)-SUM(b.RetYearSaleQty) as YearSaleQty,SUM(a.SaleYearSaleTotal) -SUM(b.RetYearSaleTotal)as YearSaleTotal
		 from AllSaleDate a,AllRetDate b
	),DisBuyPrice as(
		select goodsid,MIN(BuyDisPrice) as BuyDisPrice from (
		select GoodsID,PchPrice*PchDis/(select Convfactor from BD_Goods_Price where GoodsID = @GoodsID and UnitID = a.UnitID) as BuyDisPrice from PD_PriceTrail a where GoodsID = @GoodsID and PchDate in (select MAX(PchDate) from PD_PriceTrail where GoodsID = @GoodsID)) a group by GoodsID
	),DisSalePrice as(
		select  GoodsID,SellPrice*SellDis/(select Convfactor from BD_Goods_Price where GoodsID = @GoodsID and UnitID = a.UnitID) as SaleDisPrice from PD_PriceTrail a where GoodsID = @GoodsID and SellDate in (select MAX(SellDate) from PD_PriceTrail where GoodsID = @GoodsID)
	),AllQtyAndTotal as(
		select @GoodsID as GoodsID,SUM(Qty) as allQty,SUM(Total) as AllTotal from PD_GoodsStock Bill '+@LimitKtypeSql+' where GoodsID = @GoodsID
	)
	
	select convert(numeric(16,4),isnull(SUM(WeekSaleQty),0)) as WeekSaleQty,convert(numeric(14,2),isnull(SUM(WeekSaleTotal),0)) as WeekSaleTotal,convert(numeric(16,4),isNUll(SUM(MonthSaleQty),0)) as MonthSaleQty
			,convert(numeric(14,2),isnull(SUM(MonthSaleTotal),0)) as MonthSaleTotal,convert(numeric(16,4),isnull(SUM(YearSaleQty),0)) as YearSaleQty,convert(numeric(14,2),isnull(SUM(YearSaleTotal),0)) as YearSaleTotal
			,isnull(SUM(BuyDisPrice),0) as BuyDisPrice,isnull(SUM(SaleDisPrice),0) as SaleDisPrice,convert(numeric(16,4),isnull(SUM(allQty),0)) as allQty,convert(numeric(14,2),isnull(SUM(AllTotal),0)) as AllTotal 
	 from AllDateSum Ad left join DisBuyPrice BD on ad.GoodsID= bd.GoodsID left join  DisSalePrice SD on Ad.GoodsID=sd.GoodsID left join AllQtyAndTotal AQT on ad.GoodsID=AQT.GoodsID  '
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
	 exec sp_executesql @Sql,N'@WeekStartDate Date,@MonthStartDate Date,@YearStartDate Date,@EndDate Date,@GoodsID Int,@OperatorID int'
			,@WeekStartDate,@MonthStartDate,@YearStartDate,@EndDate,@GoodsID,@OperatorID
GO




if exists (select * from sysobjects where id = object_id(N'[UP_PD_GetWXRefundInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_PD_GetWXRefundInfo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		雷洋
-- Create date:  2016/3/18
-- Description:	 获取红冲单据退款信息
-- =============================================
CREATE PROCEDURE [UP_PD_GetWXRefundInfo](
     @BillTypeID int = 0, --单据类型
     @BillNo Int =0, --单据编号
     @BillCode varchar(50) = '' --用于销售退货单处理（红冲不管此条件）
   ) 
AS	
SET NOCOUNT ON
	declare @Sql nvarchar(max) =''
	if(@BillTypeID = 202)
	Begin
		Select @Sql =' Declare @out_trade_no varchar(100),@total_fee decimal,@refund_fee decimal
		 select @out_trade_no = out_trade_no from PD_WeiXinRecord wx inner join PD_SellBill bfm on wx.BillNo = bfm.BillNo 
		 where bfm.BillCode = @BillCode and bfm.Red<>2 and wx.BillTypeID = 201 and result_code = '''+'SUCCESS'+'''
		
		select @refund_fee = (Total * 100) from PD_WeiXinAccounts where  BillTypeID = @BillTypeID and BillNo = @BillNo and FinanceID = 42

		select @total_fee = (wx.Total * 100) from PD_WeiXinAccounts wx inner join PD_SellBill bfm on wx.BillNo = bfm.BillNo 
		where bfm.BillCode = @BillCode and bfm.Red<>2  
		select @out_trade_no as out_trade_no,@total_fee as total_fee,@refund_fee as refund_fee '
	END
	Else
	BEGIN
		select @Sql = '
			Declare @out_trade_no varchar(100),@total_fee decimal,@refund_fee decimal
			 select @out_trade_no = out_trade_no from PD_WeiXinRecord wx 
			inner join '+BillTable+' bmf on wx.BillNo = bmf.BillNo 
			inner join '+BillTable+' rmf on rmf.BillCode = bmf.BillCode 
			where wx.BillTypeID = @BillTypeID and rmf.BillNo = @BillNo and rmf.Red = 2 and result_code = '''+'SUCCESS'+'''
			
			select @total_fee = (Total * 100) from PD_WeiXinAccounts where  BillTypeID = @BillTypeID and BillNo = @BillNo and FinanceID = 42
			
			select @refund_fee = (wx.Total * 100) from PD_WeiXinAccounts wx 
			inner join '+BillTable+' bmf on wx.BillNo = bmf.BillNo and bmf.Red = 1
			inner join '+BillTable+' rmf on bmf.BillCode = rmf.BillCode 
			where wx.BillTypeID = @BillTypeID and rmf.BillNo = @BillNo and rmf.Red=2 
			select @out_trade_no as out_trade_no,@total_fee as total_fee,@refund_fee as refund_fee
			'
			from PD_BillType where BillTypeID = @BillTypeID
	END	
	
	EXEC sp_executesql @Sql,N'@BillTypeID INT,@BillNo INT,@BillCode VARCHAR(50)',@BillTypeID,@BillNo,@BillCode	  
          
GO



/****** Object:  StoredProcedure [UP_PD_GoodsBatchList]    Script Date: 02/23/2016 14:56:58 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_GoodsBatchList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_GoodsBatchList]
GO

/****** Object:  StoredProcedure [UP_PD_GoodsBatchList]    Script Date: 02/23/2016 14:56:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：李文博
	日期：2016-02-23
	描述：商品批次信息
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_GoodsBatchList]
(
	@BatchNumber VARCHAR(50)='',
	@GoodsID INT = 0,
	@WhsID INT = 0,
	@Ppt1ID INT = 0,
	@Ppt2ID INT = 0,
	@WhsPtID INT = 0
)

AS

DECLARE @sql NVARCHAR(max) = '', @OutQty NUMERIC(20,10) = 0



SELECT @sql='
SELECT	  GD.DetailID,
		  GD.WhsPtID ,
		  WP.WhsPtName,	
		  GD.GoodsID ,
		  GD.Ppt1ID ,
		  GD.Ppt2ID ,
		  GD.Qty AS StockQty,
		  @OutQty AS OutQty,
		  CostPrice ,
		  BatchNumber ,
		  ProductDate ,
		  EndDate,
		  G.NearbyDays,
		  CASE WHEN EndDate <> '''' AND EndDate <= CONVERT(VARCHAR(10),GETDATE(),120) THEN 2 
			   WHEN EndDate <> '''' AND CONVERT(VARCHAR(10),DATEADD(DAY, G.NearbyDays*(-1) , EndDate),120) <= CONVERT(VARCHAR(10),GETDATE(),120) THEN 1
			   ELSE 0 END AS BatchFlag
FROM PD_GoodsStock_Detail GD
INNER JOIN PD_GoodsStock GT ON GD.StockID = GT.StockID
LEFT JOIN BD_Whs_Position WP ON WP.WhsPtID = GD.WhsPtID
LEFT JOIN BD_Goods G ON GD.GoodsID = G.GoodsID
WHERE 1=1 AND GT.WhsID = @WhsID AND GD.GoodsID = @GoodsID
AND GD.Ppt1ID = @Ppt1ID AND GD.Ppt2ID = @Ppt2ID '

IF @WhsPtID <> 0
BEGIN
	SET @sql += ' AND GD.WhsPtID = @WhsPtID '
END	

IF @BatchNumber <> ''
	SET @sql +=' AND BatchNumber Like ''%''+@BatchNumber+''%'' '


EXEC sp_executesql @sql,N'@WhsID INT, @GoodsID INT, @Ppt1ID INT, @Ppt2ID INT, @WhsPtID INT, 
						  @BatchNumber VARCHAR(50), @OutQty NUMERIC(20,10)',
						  @WhsID, @GoodsID, @Ppt1ID, @Ppt2ID, @WhsPtID, @BatchNumber, @OutQty

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------  
    作者：leiyang  
 日期：2014-8-15  
 描述：商品往来对账查询  
-------------------------------------------*/  
CREATE PROCEDURE [UP_PD_GoodsWLDZSum]  
(  
 @BeginDate DATE,  
 @EndDate DATE,  
 @BTypeID Int=0,  
 @DeptID VARCHAR(max)='',  
 @ElyID VARCHAR(max)='',  
 @ShowDZ INT=0,  
 @RedFlag Int = 0,  
 @isHistory INT=0    --是否包含历史数据   
)  
  
AS  
SET NOCOUNT ON  
  
DECLARE @re int   
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory  
if( @re=1 )return @re;  
  
IF (@BTypeID<=0)   
BEGIN  
  RAISERROR ('请选择"往来单位"进行查询！' , 16, 1) WITH NOWAIT  
      RETURN 1  
END  
  
DECLARE @sql nvarchar(MAX)='',@SqlBuy nvarchar(max)='',@SqlBuyBack nvarchar(max)='',@SqlSell nvarchar(max)='',@SqlSellBack nvarchar(max)=''  
 ,@sqlSellLogist nvarchar(max)='',@SqlBuyHis nvarchar(max)='',@SqlBuyBackHis nvarchar(max)='',@SqlSellHis nvarchar(max)='',@SqlSellBackHis nvarchar(max)=''  
 ,@sqlBuyLogist nvarchar(max)='',@SqlTable nvarchar(max)='',@SqlRed varchar(100)='',@SqlDZ1 varchar(200)='',@SqlDZ2 varchar(200)='',@SqlDZ3 varchar(200)='',  
 @SqlCreateTable varchar(max)='',@SqlBaseTable varchar(max)='',@RedStr varchar(100)='',@RedStr1 varchar(100)='',@sqlListTable varchar(max)='',@SqlRet varchar(max)=''  
IF @DeptID<>''  
BEGIN  
 SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''  
 SET @SqlBaseTable+=' INNER JOIN @DType D ON I.DeptID=D.TypeID '  
END   
IF @ElyID<>''  
BEGIN  
 SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '  
 SET @SqlBaseTable+=' INNER JOIN @EType E ON I.ElyID=E.TypeID '   
END   
if(@RedFlag = 0)   
 Select @SqlRed = ' And Red = 0 '  
else  
Begin  
 Select @RedStr = ',Red '  
 Select @RedStr1 = ',A.Red '  
End  
if(@ShowDZ = 1)   
Begin  
 Select @SqlDZ1 = ' Where IsReconciled = 1 '  
 Select @SqlDZ2 = ' And IsReconciled = 1 '  
 select @SqlDZ3 = ' Where 1=2 ' 
ENd  
if(@ShowDZ = 2)   
Begin  
 Select @SqlDZ1 = ' Where IsReconciled = 0 '  
 Select @SqlDZ2 = ' And IsReconciled = 0 '   
ENd  
  
if @isHistory = 1  
 Set @sqlListTable += ' (select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal,IsReconciled,[Order],Red from PD_ListTable  
      union all  
      select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal,IsReconciled,[Order],Red from PD_ListTable_His)'  
else  
 Set @sqlListTable += 'PD_ListTable'  
  
SELECT @sql+='
Union All
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,BTypeID,I.BillNo'  
 +' FROM '+BillTable+' I ' + @SqlBaseTable  
 +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID  
 AND BillDate BETWEEN @BeginDate AND @EndDate'   
  +CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END  
FROM PD_BillType b  
WHERE CanPost=1 And BillTypeID in (401,402,404,405,501,502,503,504)  
  
Select @SqlBuy += '  
SELECT  101 AS BillTypeID,BTypeID,I.BillNo,I.Freight  
  FROM PD_PchBill I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
'  
Select @SqlBuyBack += '  
SELECT  102 AS BillTypeID,BTypeID,I.BillNo  
  FROM PD_PchRetBill I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
'  
Select @SqlSell += '  
SELECT  201 AS BillTypeID,BTypeID,I.BillNo  
  FROM PD_SellBill I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
'  
Select @SqlSellBack += '  
SELECT  202 AS BillTypeID,BTypeID,I.BillNo  
  FROM PD_SellRetBill I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
'  
SELECT @sqlSellLogist+='  
UNION ALL   
SELECT  201 AS BillTypeID,LogistBTypeID as BtypeID,I.BillNo  
  FROM PD_SellBill I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate'   
SELECT @sqlBuyLogist+='  
SELECT  101 AS BillTypeID,LogistBTypeID as BtypeID,I.BillNo,I.Freight  
  FROM PD_PchBill I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate' 
    
IF @isHistory=1  
Begin  
 SELECT @sql+='  
UNION ALL   
 SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,BTypeID,I.BillNo'  
  +' FROM '+BillTable+'_His I ' + @SqlBaseTable  
  +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID  
  AND BillDate BETWEEN @BeginDate AND @EndDate'   
   +CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END  
 FROM PD_BillType b  
 WHERE CanPost=1 And BillTypeID in (401,402,404,405,501,502,503,504)  
  
 Select @SqlBuyHis += '  
 SELECT  101 AS BillTypeID,BTypeID,I.BillNo,I.Freight   
   FROM PD_PchBill_His I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
 '  
 Select @SqlBuyBackHis += '  
 SELECT  102 AS BillTypeID,BTypeID,I.BillNo  
   FROM PD_PchRetBill_His I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
 '  
 Select @SqlSellHis += '  
 SELECT  201 AS BillTypeID,BTypeID,I.BillNo  
   FROM PD_SellBill_His I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
 '  
 Select @SqlSellBackHis += '  
 SELECT  202 AS BillTypeID,BTypeID,I.BillNo  
   FROM PD_SellRetBill_His I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate  
 '  
 SELECT @sqlSellLogist+='  
 UNION ALL   
 SELECT  201 AS LogistBTypeID,LogistBTypeID as BtypeID,I.BillNo  
   FROM PD_SellBill_His I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate'  
SELECT @sqlBuyLogist+='  
 UNION ALL
SELECT  101 AS BillTypeID,LogistBTypeID as BtypeID,I.BillNo,I.Freight    
  FROM PD_PchBill_His I '+ @SqlBaseTable +' WHERE IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate' 
End  

--统计单据明细数据  
Select @SqlRet += '  
 Select 0 as DTotal,isnull(DiscTotal,0) as JTotal  
 from BuyBill I left Join PD_PchDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 Select isnull(DiscTotal,0)  as DTotal,0 as JTotal  
 from BuyBackBill I left Join PD_PchRetDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 Select isnull(DiscTotal,0)  as DTotal,0 as JTotal  
 from SellBill I left Join PD_SellDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 Select 0 as DTotal,isnull(DiscTotal,0)  as JTotal  
 from SellBackBill I left Join PD_SellRetDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 '  
IF @isHistory=1  
Begin  
Select @SqlRet += '  
 Select 0 as DTotal,isnull(DiscTotal,0)  as JTotal  
 from BuyBill_His I left Join PD_PchDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 Select isnull(DiscTotal,0)  as DTotal,0 as JTotal  
 from BuyBackBill_His I left Join PD_PchRetDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 Select isnull(DiscTotal,0)  as DTotal,0 as JTotal  
 from SellBill_His I left Join PD_SellDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 Select 0 as DTotal,isnull(DiscTotal,0)  as JTotal  
 from SellBackBill_His I left Join PD_SellRetDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'  
 Union ALL  
 '  
End  
SELECT @sql=@SqlCreateTable+@SqlTable + '  
;WITH Bill AS   
(' 
+STUFF(@sql+@sqlSellLogist,1,12,'')+'  
),SellBill as  
(' +@sqlSell+  
'),SellBackBill as  
('+@SqlSellBack+'  
),BuyBill as  
('+@SqlBuy+')  
,BuyBackBill As  
('+@SqlBuyBack+')
,BuyLogistBill As  
('+@sqlBuyLogist+')'  
IF @isHistory=1  
 Select @sql+= '  
  ,SellBill_His as  
 (' +@SqlSellHis+  
 '),SellBackBill_His as  
 ('+@SqlSellBackHis+'  
 ),BuyBill_His as  
 ('+@SqlBuyHis+')  
 ,BuyBackBill_His As  
 ('+@SqlBuyBackHis+')'  
Select @sql +=',AllData as  
(   
 '+@SqlRet+'
 Select isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal
 from BuyLogistBill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID  
 where FinanceID not in(33,37) '+@SqlDZ2+' 
 Union All
 Select 0 as DTotal,Freight as JTotal
 from BuyLogistBill '+@SqlDZ3+'    
 Union All
 Select isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal  
 from Bill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID  
 where FinanceID not in(33,37) '+@SqlDZ2+'  
 Union ALL  
  Select isnull(L.DTotal,0) as DTotal ,isnull(L.JTotal,0) as JTotal  
 from sellbill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID  
 where FinanceID not in(33,37,11,35,8) '+@SqlDZ2+'  
 Union ALL  
  Select isnull(L.DTotal,0) as DTotal ,isnull(L.JTotal,0) as JTotal  
 from SellBackBill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID  
 where FinanceID not in(33,37,11,35,8,20) '+@SqlDZ2+'  
 Union ALL  
 Select isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal  
 from BuyBill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID  
 where FinanceID not in(33,37,35) '+@SqlDZ2+'  
 Union ALL  
 Select isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal  
 from BuyBackBill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID  
 where FinanceID not in(33,37,35,20) '+@SqlDZ2+'  
   
)  
Select Sum(JTotal) as JTotal,SUm(DTotal) as DTotal from AllData  
'  
--select @total as total  
IF @sql IS NULL OR @sql=''  
BEGIN  
 SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错  
 RETURN   
END  
--select @PageNo,@PageSize,@BeginDate,@EndDate,@BTypeID,@RowCount  
------------------添加参数---------------------------------------  
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''  
--  WHILE (@curPos < len(@sql))    
--  BEGIN    
--   PRINT substring(@sql, @curPos, @curPos + 3999)    
--   SET @curPos += 3999 + 1    
--   SET @count += 1    
--  END    
exec sp_executesql @sql,N'@BeginDate Date,@EndDate Date,@BTypeID VarChar(MAX),@DeptID VarChar(MAX),@ElyID VarChar(MAX)',@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID  

Go
  



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：Wangwei	
	日期：2015-01-20
	描述：历史进价
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_HistoryBuyPrice]
(
	@PageNo INT=0
	,@PageSize INT=0
	,@BtypeID INT=0--往来单位
	,@GoodsID INT=0 --商品
	,@OperatorID INT=0 --操作员
)

AS
SET NOCOUNT ON

IF (@GoodsID<=0) 
BEGIN
	 RAISERROR ('请选择对应的商品信息！' , 16, 1) WITH NOWAIT
      RETURN 1
END

DECLARE @isBtypeLimit INT 
SET @isBtypeLimit=2
IF @BtypeID=0
	SET @isBtypeLimit=dbo.UF_BD_IsAllBtypeLimit(@OperatorID)


DECLARE @sql nvarchar(max)
SET @sql=';WITH data as (

			SELECT	
					d.Qty
					,d.price
					,d.TaxPrice
					,d.DiscPrice
					,b.BillDate
					,d.Discount
					,b.BillCode
					,b.Red
					,b.PosTime
					,bb.BtypeID
					,bb.BtypeName
					,bb.BtypeCode
					,g.GoodsID
					,g.GoodsNo
					,g.GoodsName
					,gp.UnitID
					,gp.Unit
		'
SET @sql+=' FROM PD_PchDetail d  
				 INNER JOIN PD_PchBill b ON d.BillNo=b.BillNo
				 INNER JOIN BD_Btype bb ON b.BtypeID=bb.Btypeid
				 INNER JOIN BD_Goods g ON d.GoodsID=g.GoodsID
				 INNER JOIN BD_Goods_Price gp ON d.GoodsID=gp.GoodsID AND d.UnitID=gp.UnitID '
if @BtypeID=0 AND @isBtypeLimit=1
	SET @sql+='	 INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BtypeID=b.BtypeID '
			 	
SET @sql+=' WHERE b.Red=0 AND  b.IsDraft=0 AND  d.GoodsID=@GoodsID AND d.Gift=0 	'		
IF @BtypeID<>0
	SET @sql+='  AND b.BtypeID=@BtypeID '			
	
		
SET @sql+=' ) 
,PageData AS (
				SELECT 
						ROW_NUMBER() OVER( ORDER BY'
  
IF  @BtypeID=0
	SET @sql+='		BtypeCode asc,	'
	
SET @sql+='                 PosTime desc   ) AS RowID,  count(*) over() as '''+'RowCount'+''', *	 
				FROM data 
			) 
		SELECT* FROM PageData 
		WHERE ROWID>(@PageNo-1)*@PageSize aND ROWID<=@PageNo*@PageSize
		  ORDER BY  '	
		   
IF  @BtypeID=0
	SET @sql+=' BtypeCode asc , '  
	
SET @sql+=' PosTime desc '
  			 							
exec sp_executesql @sql,N'@PageNo Int,@PageSize Int,@BtypeID INT,@GoodsID INT,@OperatorID INT '
						,@PageNo,@PageSize,@BtypeID,@GoodsID,@OperatorID


GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：Wangwei	
	日期：2015-01-20
	描述：历史售价
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_HistorySalePrice]
(
	@PageNo INT=0
	,@PageSize INT=0
	,@BtypeID INT=0--往来单位
	,@GoodsID INT=0 --商品
	,@OperatorID INT=0 --操作员
)

AS
SET NOCOUNT ON

IF (@GoodsID<=0) 
BEGIN
	 RAISERROR ('请选择对应的商品信息！' , 16, 1) WITH NOWAIT
      RETURN 1
END

DECLARE @isBtypeLimit INT 
SET @isBtypeLimit=2
IF @BtypeID=0
	SET @isBtypeLimit=dbo.UF_BD_IsAllBtypeLimit(@OperatorID)


DECLARE @sql nvarchar(max)
SET @sql=';WITH data as (

			SELECT	
					d.Qty
					,d.price
					,d.TaxPrice
					,d.DiscPrice
					,b.BillDate
					,d.Discount
					,b.BillCode
					,b.Red
					,b.PosTime
					,bb.BtypeID
					,bb.BtypeName
					,bb.BtypeCode
					,g.GoodsID
					,g.GoodsNo
					,g.GoodsName
					,gp.UnitID
					,gp.Unit
		'
SET @sql+=' FROM PD_SellDetail d  
				 INNER JOIN PD_SellBill b ON d.BillNo=b.BillNo
				 INNER JOIN BD_Btype bb ON b.BtypeID=bb.Btypeid
				 INNER JOIN BD_Goods g ON d.GoodsID=g.GoodsID
				 INNER JOIN BD_Goods_Price gp ON d.GoodsID=gp.GoodsID AND d.UnitID=gp.UnitID '
if @BtypeID=0 AND @isBtypeLimit=1
	SET @sql+='	 INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BtypeID=b.BtypeID '
			 	
SET @sql+=' WHERE b.Red=0 AND b.IsDraft=0 AND  d.GoodsID=@GoodsID AND d.Gift=0	'		
IF @BtypeID<>0
	SET @sql+='  AND b.BtypeID=@BtypeID '			
	
		
SET @sql+=' ) 
,PageData AS (
				SELECT 
						ROW_NUMBER() OVER( ORDER BY'
  
IF  @BtypeID=0
	SET @sql+='		BtypeCode asc,	'
	
SET @sql+='                 PosTime desc   ) AS RowID,  count(*) over() as '''+'RowCount'+''', *	 
				FROM data 
			) 
		SELECT* FROM PageData 
		WHERE ROWID>(@PageNo-1)*@PageSize aND ROWID<=@PageNo*@PageSize
		  ORDER BY  '	
		   
IF  @BtypeID=0
	SET @sql+=' BtypeCode asc , '  
	
SET @sql+=' PosTime desc '
  			 							
exec sp_executesql @sql,N'@PageNo Int,@PageSize Int,@BtypeID INT,@GoodsID INT,@OperatorID INT '
						,@PageNo,@PageSize,@BtypeID,@GoodsID,@OperatorID


GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-8-5
	描述：查询采购明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_InOutDetailsSum]
(
	--@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(max)='',
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@InWhsID VARCHAR(max)='',
	@OutWhsID VARCHAR(max)='',
	@FinanceID VARCHAR(max)='',
	@BillCode VARCHAR(100)='',
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100)='',
	@UserCodeMatch INT=0,
	@UserCode VARCHAR(100)='',
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@FullNameMatch INT=0,
	@LogistBillNo VARCHAR(100) = '',
	@LogistBillNoMatch INT=0,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=0,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=0,
	@Remark VARCHAR(100)='',
	@RemarkMatch INT=0,	
	@IsRedFlag Int=0,
	@OperatorID INT,
	@ClassID1 Int = 0,		--汇总条件一，ID
	@ClassType1 Int = 0,	--汇总条件一类型 1为单据汇总，2为仓库汇总
	@ClaseFlag1 Int = 0,	--汇总条件一分类 0为非分类，1为分类汇总
	@ClassID2 Int = 0,		--汇总条件二，ID
	@ClassType2 Int = 0,	--汇总条件二类型 1为商品
	@ClaseFlag2 Int = 0,		--汇总条件二分类 0为非分类，1为分类汇总
	@isHistory INT=0,				--是否包含历史数据
	@BillFlag INT=0			--处理调价单和调拨单的出入库明细
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;
DECLARE @sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlWhs nvarchar(max)='',
		@SqlWhsOut varchar(max)='',@SqlWhsin varchar(max)='',@GoodsMath varchar(max)='', 
		 @LimitSql NVARCHAR(MAX) = '',@LimitSqlIN NVARCHAR(max)='',@LimitSqlOut NVARCHAR(max)='',@conditionStr varchar(max)='',
		 @RedStr varchar(100)='',@Red varchar(100)='',@SqlClass1 varchar(500)='',@SqlClass2 varchar(500)='',@sqlWhsInClick varchar(max)='',
		 @sqlWhsOutClick varchar(max)='',@sqlWhsClick varchar(max)='', @SqlFreight varchar(500)='',@SqlAtype varchar(500)='',
		 @SaleStr varchar(max)=' ',@buyStr varchar(max)=' ',@saleRetStr varchar(max)=' ',@AssemblyInStr varchar(Max)=' ',@AssemblyOutStr varchar(Max)=' '
		 ,@buyRetStr varchar(max)=' ',@AdjPriceInStr varchar(max)=' ',@AdjPriceOutStr varchar(max)=' '
		 ,@LossISpil varchar(max)='',@LossOSpil varchar(max)=' '
		 ,@AllToTInStrO varchar(max)=' ',@AllToBInStrO varchar(max)=' ',@AllToTOutStrO varchar(max)=' ',@AllToBOutStrO varchar(max)=' '		 
		 ,@BtypeLimit INT=0,@KtypeLimit INT=0,@InspectTagStr varchar(100)='',
		 @InOutIStr varchar(max)='',@InOutOStr varchar(max)=''
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
if object_id('tempdb..#BillType','U') is not null drop table #BillType
CREATE TABLE #BillType(billtype int)
IF @BillTypeID<>''		
	INSERT INTO #BillType SELECT typeid FROM  dbo.UF_OT_Split_Int(@BillTypeID,',') Where typeid IN(101,102,201,202,301,302,303,304,305,306,309,310,600) 
ELSE
	INSERT INTO #BillType SELECT BillTypeID  FROM PD_BillType  WHERE CanPost=1 And BillTypeID IN(101,102,201,202,301,302,303,304,305,306,309,310,600) 
--------------------根据条件筛选单据类型---------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM #BillType WHERE billtype=0)
BEGIN
	IF @BTypeID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,303,304,600)
	IF @FinanceID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,201,102,202)   
	IF @UserCode<>'' OR @FullName<>'' OR @WhsID<>'' OR @Model <> '' OR @AbbName <> '' OR @Brand <> '' OR @Spec <> ''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,301,302,303,304,305,306,309,310,600)   
	if @LogistBillNo <> ''
		DELETE FROM #BillType WHERE billtype NOT IN(201)   
	if @ClassType1 = 1
		DELETE FROM #BillType WHERE billtype <> @ClassID1 
END  
if exists(select 1 from SS_SysCfg where CfgName='AllotWithInspect' and CfgValue = 1) --判断是否启用调拨验证
	select @InspectTagStr = ' AND I.InspectTag = 1 '
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' Inner Join @BType B on I.BTypeID=B.TypeID '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' Inner Join @DType D On I.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' Inner Join @EType E On I.ElyID=E.TypeID ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' Inner Join @CreateEType CE On I.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	Set @SqlWhs += ' Inner Join @KType W On I.WhsID=W.TypeID ' 
	Set @SqlWhsOut += ' Inner Join @KType W On I.OutWhsID = W.TypeID or I.InWhsID=W.TypeID ' 
	--Set @SqlWhsIn += ' And exists( Select 1 from  @KType W where I.InWhsID=W.TypeID) ' 
END	
IF @InWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @InKType As Table(TypeID INT) insert into @InKType Select typeid from dbo.UF_OT_Split_Int(@InWhsID,'','') '
	SET @SqlWhsIn+='  Inner Join @InKType Wi On I.InWhsID=Wi.TypeID ' 
END	
IF @OutWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @OutKType As Table(TypeID INT) insert into @OutKType Select typeid from dbo.UF_OT_Split_Int(@OutWhsID,'','') '
	SET @SqlWhsOut+=' Inner Join @OutKType Wo On I.OutWhsID=Wo.TypeID ' 
END	
IF @BtypeLimit = 1
Begin
	Select @SqlCreateTable += ' DECLARE @LimitBTYPE AS TABLE(BTypeID INT) Insert into  @LimitBTYPE Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '
End
 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSql += ' Inner Join @LimitKType LW On I.WhsID=LW.TypeID ' 
	Set @LimitSqlIN += ' Inner Join @LimitKType LW On LW.TypeID =i.InWhsID ' 	
	Set @LimitSqlOut += ' Inner Join @LimitKType LW On LW.TypeID =i.OutWhsID ' 	
End	
IF @FinanceID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @FType As Table(TypeID INT) insert into @FType Select f2.FinanceID from BD_Finance f INNER JOIN dbo.UF_OT_Split_Int(@FinanceID,'','') f1 ON f1.typeid=f.FinanceID INNER JOIN BD_Finance f2 ON f2.Path like f.Path+''%'''
	SET @SqlAtype+=' Inner Join @FType F On I.FinanceID=F.TypeID ' 
	SET @SqlFreight+=' Inner Join @FType A On  i.FinanceID=A.TypeID or i.FreightFinanceID = a.TypeID ' 
END	 
if(@Summary <> '')
	Set @conditionStr += ' And Summary ' + case @SummaryMatch when 0 then ' Like ''%''+@Summary+''%''' Else ' =@Summary ' End
if(@Description <> '')
	Set @conditionStr += ' And Description ' + case @DescriptionMatch when 0 then ' Like ''%''+@Description+''%''' Else ' =@Description ' END
IF @LogistBillNo <>'' 
	SET @conditionStr = ' AND LogistBillNo'+CASE @LogistBillNoMatch WHEN 0 THEN ' Like''%''+@LogistBillNo+''%''' ELSE ' =@LogistBillNo' END
if(@Remark <> '')
	Set @conditionStr += ' And Remark ' + case @RemarkMatch when 0 then ' Like ''%''+@Remark+''%''' Else ' =@Remark ' END
if(@BillCode <> '')
	Set @conditionStr += ' And BillCode ' + case @BillCodeMatch when 0 then ' Like ''%''+@BillCode+''%''' Else ' =@BillCode ' END	
/*新增商品查询条件 start 150901*/
DECLARE @NewGoodsParam VARCHAR(4000) = ''
IF(@Model <> '')
	SET @NewGoodsParam += ' AND Model ' + CASE @ModelMatch WHEN 0 THEN ' LIKE ''%''+@Model+''%''' ELSE ' =@Model ' END
IF(@AbbName <> '')
	SET @NewGoodsParam += ' AND GoodsAbbName ' + CASE @AbbNameMatch WHEN 0 THEN ' LIKE ''%''+@AbbName+''%''' ELSE ' =@AbbName ' END
IF(@Brand <> '')
	SET @NewGoodsParam += ' AND Brand ' + CASE @BrandMatch WHEN 0 THEN ' LIKE ''%''+@Brand+''%''' ELSE ' =@Brand ' END
IF(@Spec <> '')
	SET @NewGoodsParam += ' AND Spec ' + CASE @SpecMatch WHEN 0 THEN ' LIKE ''%''+@Spec+''%''' ELSE ' =@Spec ' END
IF @BarCode <> ''
	BEGIN
		SET @SqlCreateTable+=' DECLARE @BarCodeParam AS TABLE(TypeID INT) INSERT INTO @BarCodeParam SELECT DISTINCT GoodsID  FROM dbo.BD_Goods_Price WHERE BarCode ' + CASE @BarCodeMatch WHEN 0 THEN ' Like ''%'' + @BarCode + ''%''' ELSE ' =@BarCode ' END
		SET @SqlTable += ' INNER JOIN @BarCodeParam BParam ON BD.GoodsID = BParam.TypeID '
	END
/*end*/	
if(@FullName <> '' or @UserCode <> '' OR @NewGoodsParam <> '')
Begin
	if(@FullName <> '')
		Set @GoodsMath += ' And GoodsName ' + case @FullNameMatch when 0 then ' Like ''%''+@FullName+''%''' Else ' =@FullName ' END
	if(@UserCode <> '')
		Set @GoodsMath += ' And GoodsNo ' + case @UserCodeMatch when 0 then ' Like ''%''+@UserCode+''%''' Else ' =@UserCode ' END
	SET @SqlCreateTable+=' DECLARE @PType As Table(TypeID INT,GoodsName Varchar(100),GoodsNo varchar(50)) insert into @PType Select GoodsID,GoodsName,GoodsNo from BD_GOODS Where 1=1 '+@GoodsMath+@NewGoodsParam	
	Select @SqlTable += ' Inner Join @PType GT On BD.GoodsID = GT.TypeID '
End
IF @ClassID1 <> 0
Begin
	SET @SqlClass1 +=' DECLARE @CTb1  as Table(typeid int) INSERT INTO @CTb1(typeid) '
	Set @SqlCreateTable += Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											Else '' End
    --Set @SqlTable += Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.WhsID = @ClassID1 ' else 'And exists( Select 1 from @CTb1 C1 where I.WhsID=C1.TypeID )' end
				--					  Else '' End
	Set @sqlWhsClick +=	Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.WhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 On I.WhsID=C1.TypeID ' end
									  Else '' End							 
	Set @sqlWhsInClick +=	Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.INWhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 On I.INWhsID=C1.TypeID ' end
									  Else '' End	
	Set @sqlWhsOutClick +=	Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.OutWhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 On I.OutWhsID=C1.TypeID ' end
									  Else '' End										  										  
End
IF @ClassID2 <> 0
Begin
	SET @SqlClass2 +=' DECLARE @CTb2  as Table(typeid int) INSERT INTO @CTb2(typeid) '
	Set @SqlCreateTable += case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') end 											
    Set @SqlTable +=  case @ClaseFlag2 when 0 then ' And BD.GoodsID = @ClassID2 ' else ' Inner Join @CTb2 C2 On BD.GoodsID=C2.TypeID ' end 
End
if(@IsRedFlag=0)
Begin
	Set @Red = ' And Red = 0 '
End
Else
Begin
	Set @RedStr = ',Red'
End
select @buyStr += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
Select @buyRetStr += ' 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
Select @SaleStr += ' 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
select @saleRetStr += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
Select @InOutIStr += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		,0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
Select @InOutOStr += ' 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal	'		
Select @LossISpil += '
		 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
select @LossOSpil += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
Select @AllToTInStrO += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
Select @AllToTOutStrO += ' 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
Select @AllToBInStrO += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		, 0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.AllotTotal * -1 Else Bd.AllotTotal end as Total
		,Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as DiscTotal
		,Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as GoodsCostTotal	 '
Select @AllToBOutStrO += ' 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty 
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '	
Select @AdjPriceInStr += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		,0 as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.AdjTotal * -1 Else Bd.AdjTotal end as Total
		,Case When I.Red=2 then BD.AdjTotal * -1 Else BD.AdjTotal End as DiscTotal
		,Case When I.Red=2 then BD.AdjTotal * -1 Else BD.AdjTotal End as GoodsCostTotal'
select 	@AdjPriceOutStr += ' 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal	'	
Select @AssemblyInStr += ' Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		,0 as OutQty 
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal 
		,BD.GoodsCostTotal'	
Select @AssemblyOutStr += ' 0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal '
select @sql +='
	UNION ALL 
	SELECT  '
	+ Case  When BillTypeID = 101 then @buyStr
			When BillTypeID = 102 then @buyRetStr
			When BillTypeID = 201 then @SaleStr
			When BillTypeID = 202 then @saleRetStr
			When BillTypeID = 303 then @InOutIStr
			When BillTypeID = 304 then @InOutOStr
			When BillTypeID = 305 then @LossISpil
			When BillTypeID = 306 then @LossOSpil
			When BillTypeID = 600 then @InOutOStr
			Else '' End	
	+' FROM  ' + BillDetail + ' BD  Inner Join '+BillTable+' I On I.BillNo=bd.BillNo '+ @SqlTable + @sqlWhsClick + @LimitSql
	+ @SqlWhs 
	--+ Case When BillTypeID = 201 then @SqlFreight Else @SqlAtype End  只有单账户情况下 update 150619
	+ ' where 
	 BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red 
	
	+CASE WHEN @FinanceID='' OR billtypeid NOT IN(101,201,102,202) THEN '' ELSE ' AND EXISTS(SELECT 1 FROM @FType A WHERE I.FinanceID=A.TypeID '+case when billtypeid in (101,201) THEN 'OR I.FreightFinanceID=A.TypeID ' ELSE '' END+'
			OR EXISTS(SELECT 1 FROM PD_MulAccounts M WHERE M.BillTypeID='+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo and M.FinanceID= a.TypeID))' END 
	  	
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	+@conditionStr
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0 
WHERE CanPost=1 and billtype not in (301,302,309,310)
if exists (select 1 from #BillType where billtype= 301)
begin
  if @BillFlag = 1 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @Sql+='
	UNION ALL 
		SELECT  '+@AllToTOutStrO+' 
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '+@SqlTable +@sqlWhsOutClick + @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 301 ' +@Red		
		+@conditionStr
  if @BillFlag = 2 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @Sql +='
	UNION ALL 
		SELECT  '+@AllToTInStrO+' 
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 301 ' + @Red + @InspectTagStr
		+@conditionStr
End
if exists (select 1 from #BillType where billtype= 309)
begin
  if @BillFlag = 1 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @Sql+='
	UNION ALL 
		SELECT  '+@AllToBOutStrO+' 
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '+@SqlTable +@sqlWhsOutClick + @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 309 ' +@Red		
		+@conditionStr
  if @BillFlag = 2 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @Sql +='
	UNION ALL 
		SELECT  '+@AllToBInStrO+' 
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 309 ' + @Red+ @InspectTagStr
		+@conditionStr
End
if exists (select 1 from #BillType where billtype= 302)
begin
  if @BillFlag = 3 or @BillFlag = 0	
	Select @Sql+='
	UNION ALL 
		SELECT  ' + @AdjPriceInStr +' 
		FROM  PD_AdjPriceDetail BD  Inner Join PD_AdjPriceBill I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
		+@conditionStr
  if @BillFlag = 4 or @BillFlag = 0	
	Select @Sql +='
	UNION ALL 
		SELECT  ' + @AdjPriceOutStr+' 
		FROM  PD_AdjPriceDetail BD  Inner Join PD_AdjPriceBill I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
		+@conditionStr
End
if exists (select 1 from #BillType where billtype= 310)
begin
  if @BillFlag = 5 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @InWhsID <> '')
	Select @Sql+='
	UNION ALL 
		SELECT  ' + @AssemblyInStr + ' 
		FROM  PD_AssemblyDetail BD  Inner Join PD_AssemblyBill I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=1 ' + @Red
		+@conditionStr
  if @BillFlag = 6 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @OutWhsID <> '')
	Select @Sql +='
	UNION ALL 
		SELECT  ' + @AssemblyOutStr+' 
		FROM  PD_AssemblyDetail BD  Inner Join PD_AssemblyBill I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsOutClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=2 ' + @Red
		+@conditionStr
End

IF @isHistory=1
Begin
	select @sql +='
	UNION ALL 
		SELECT  '
	+ Case  When BillTypeID = 101 then @buyStr
			When BillTypeID = 102 then @buyRetStr
			When BillTypeID = 201 then @SaleStr
			When BillTypeID = 202 then @saleRetStr
			When BillTypeID = 303 then @InOutIStr
			When BillTypeID = 304 then @InOutOStr
			When BillTypeID = 305 then @LossISpil
			When BillTypeID = 306 then @LossOSpil
			When BillTypeID = 600 then @InOutOStr
			Else '' End	 
		+' FROM  ' + BillDetail + '_His BD  Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo '
		+ @SqlTable + @sqlWhsClick	+ @LimitSql	
		+ @SqlWhs 
		--+ Case When BillTypeID = 201 then @SqlFreight Else @SqlAtype End  只有单账户情况 update 150619
		+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red 
		
		+CASE WHEN @FinanceID='' OR billtypeid NOT IN(101,201,102,202,403,404,405,406) THEN '' ELSE ' AND EXISTS(SELECT 1 FROM @FType A WHERE I.FinanceID=A.TypeID '+case when billtypeid in (101,201) THEN 'OR I.FreightFinanceID=A.TypeID ' ELSE '' END+'
			OR EXISTS(SELECT 1 FROM PD_MulAccounts M WHERE M.BillTypeID='+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo and M.FinanceID= a.TypeID))' END
		
		+CASE WHEN BillTable+'_His' IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+@conditionStr
	FROM PD_BillType b
	INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0 
	WHERE CanPost=1 and billtype not in (301,302,309,310)
	if exists (select 1 from #BillType where billtype= 301)
	begin
	  if @BillFlag = 1 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = ''  and @OutWhsID = '')
		Select @Sql+='
	UNION ALL 
			SELECT  '+@AllToTOutStrO+' 
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsOutClick+ @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 301 ' +@Red
			+@conditionStr
	  if @BillFlag = 2 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
		Select @Sql +='
	UNION ALL 
			SELECT  '+@AllToTInStrO+' 
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsInClick + @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 301 ' + @Red+ @InspectTagStr
			+@conditionStr
	End
	if exists (select 1 from #BillType where billtype= 309)
	begin
	  if @BillFlag = 1 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0 and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = ''  and @OutWhsID = '')
		Select @Sql+='
	UNION ALL 
			SELECT  '+@AllToBOutStrO+' 
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsOutClick+ @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 309 ' +@Red
			+@conditionStr
	  if @BillFlag = 2 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
		Select @Sql +='
	UNION ALL 
			SELECT   '+@AllToBInStrO+' 
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsInClick + @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND BillTypeID = 309 ' + @Red+ @InspectTagStr
			+@conditionStr
	End
	if exists (select 1 from #BillType where billtype= 302)
	begin
	  if @BillFlag = 3 or @BillFlag = 0	
		Select @Sql+='
	UNION ALL 
			SELECT  ' + @AdjPriceInStr +' 
			FROM  PD_AdjPriceDetail_His BD  Inner Join PD_AdjPriceBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
			+@conditionStr
	  if @BillFlag = 4 or @BillFlag = 0	
		Select @Sql +='
	UNION ALL 
			SELECT  ' + @AdjPriceOutStr +' 
			FROM  PD_AdjPriceDetail_His BD  Inner Join PD_AdjPriceBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
			+@conditionStr
	End
	if exists (select 1 from #BillType where billtype= 310)
	begin
	  if @BillFlag = 5 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @InWhsID <> '')
		Select @Sql+='
		UNION ALL 
			SELECT  ' + @AssemblyInStr + ' 
			FROM  PD_AssemblyDetail_His BD  Inner Join PD_AssemblyBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=1 ' + @Red
			+@conditionStr
	  if @BillFlag = 6 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @OutWhsID <> '')
		Select @Sql +='
		UNION ALL 
			SELECT  ' + @AssemblyOutStr+' 
			FROM  PD_AssemblyDetail_His BD  Inner Join PD_AssemblyBill_His I On I.BillNo=bd.BillNo '+@SqlTable + @sqlWhsOutClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=2 ' + @Red
			+@conditionStr
	End
End

drop table #BillType	
SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+STUFF(@sql,1,12,'')+'
)
select SUM(InQty) as InQty,SUM(OutQty) as OutQty,SUM(Qty) as Qty,SUM(Total) as Total,SUM(DiscTotal) as DiscTotal,SUM(GoodsCostTotal) as GoodsCostTotal from Bill'

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
Exec sp_executesql @Sql,N'@BeginDate Date,@EndDate Date,@OperatorID Int,@ClassID1 Int,@WhsTypeID Int,
			@ClassID2 Int,@GoodsTypeID Int,@BTypeID VarChar(MAX),@DeptID VarChar(MAX)
			,@ElyID VarChar(MAX),@CreatorID varchar(MAx),@WhsID VarChar(MAX),@BillCode VarChar(MAX),@FullName VarChar(100),@UserCode VarChar(50)
			,@Summary VarChar(256),@Description VarChar(100),@Remark VarChar(256),@FinanceID VarChar(Max),@LogistBillNo VarChar(100),@InWhsID VarChar(100),@OutWhsID VarChar(100), @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)'
			,@BeginDate,@EndDate,@OperatorID,@ClassID1,@ClassID1,@ClassID2,@ClassID2,
			@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@BillCode,@FullName,
			@UserCode,@Summary,@Description,@Remark,@FinanceID,@LogistBillNo,@InWhsID,@OutWhsID, @Model, @AbbName, @Brand, @Spec, @BarCode 



GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2015-10-27
	描述：查询进销存明细合计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_JXCSum]
(
	@BeginDate DATE,
	@EndDate DATE,
	@WhsID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@PtypeID VARCHAR(max)='',
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@OperatorID INT,
	@isHistory INT=0,			--是否包含历史数据
	@ShowTotal Int = 0          --是否显示金额
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;

DECLARE @sql nvarchar(MAX)='',@InBill varchar(max)='',@OutBill varchar(Max)='',@StartOrEndInStock varchar(max)='',@EndOutStock varchar(max)='',
@sqlAllotOut nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlGoods nvarchar(max)='',@OrderName varchar(200)=''
,@SqlWhs varchar(Max)='',@SqlWhsStock varchar(Max)='',@SqlWhsInDb varchar(max)='',@SqlWhsOutDb varchar(max)='',@DateFlag int,
@SqlOrder NVARCHAR(MAX) = '',@SqlColumns Varchar(Max)='',@SqlGroup Nvarchar(MAX) = '',@SqlBase varchar(max)='',	@InspectTagStr varchar(100)='',	
@SummaryStr varchar(max)='',@DescriptionStr varchar(max)='',@RemarkStr varchar(max)='', @LimitSql NVARCHAR(MAX) = '',@LimitSqlIN nvarchar(max)='',@LimitSqlOut nvarchar(Max)='',@KtypeLimit INT=0
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
Select @DateFlag=Case when datediff(DAY,MIN(StartDate), @BeginDate) >dateDiff(DAY,@EndDate,getdate()) then 1 Else 0 end  from SS_MonthProc
--select @DateFlag = 0
if exists(select 1 from SS_SysCfg where CfgName='AllotWithInspect' and CfgValue = 1) --判断是否启用调拨验证
	select @InspectTagStr = ' AND I.InspectTag = 1 '
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSql += ' Inner Join  @LimitKType LW On I.WhsID=LW.TypeID  ' 
	Set @LimitSqlIN += ' Inner Join  @LimitKType LW On I.InWhsID=LW.TypeID  ' 
	Set @LimitSqlOut += ' Inner Join @LimitKType LW On I.OutWhsID=LW.TypeID ' 	
End	
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' Inner Join @DType D On I.DeptID=D.TypeID  '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' Inner Join @EType E On I.ElyID=E.TypeID  ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' Inner Join @CreateEType CE On I.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	Select @SqlWhs += ' Inner Join @KType W On I.WhsID=W.TypeID ' 
	Select @SqlWhsStock += ' Inner Join @KType W On I.WhsID=W.TypeID ' 
	Select @SqlWhsInDb += ' Inner Join @KType W On I.InWhsID=W.TypeID ' 
	Select @SqlWhsOutDb += ' Inner Join @KType W On I.OutWhsID=W.TypeID ' 
END

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)='',  @TBAlias VARCHAR(1) = 'I' 
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   BEGIN
	   SET @SqlCreateTable+=' DECLARE @GoodsParam As Table(TypeID INT) insert into @GoodsParam Select goods.GoodsID FROM dbo.BD_Goods goods WHERE 1 = 1 ' + @ClauseParam
	   SET @SqlGoods+=' Inner Join @GoodsParam GP On '+@TBAlias+'.GoodsID=GP.TypeID  '
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
	   SET @SqlCreateTable+=' DECLARE @BarCodeParam As Table(TypeID INT) insert into @BarCodeParam Select DISTINCT pri.GoodsID FROM dbo.BD_Goods_Price pri WHERE 1 = 1 '	
	   IF @BarCodeMatch = 0
		   SET @SqlCreateTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlCreateTable += N' AND pri.BarCode = @BarCode '    
	   SET @SqlGoods+=' Inner Join @BarCodeParam BCP On '+@TBAlias+'.GoodsID=BCP.TypeID  '
   END    
/*end*/
	
IF @PtypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @PType As Table(TypeID INT) insert into @PType Select typeid from dbo.UF_OT_Split_Int(@PTypeID,'','') '
	SET @SqlGoods+=' Inner Join @PType P On I.GoodsID=P.TypeID '
END	
Set @SqlColumns+=' BaseID,'
Set @SqlGroup +=' BaseID'
Set @SqlBase += ' (Select GoodsID As BaseID from BD_Goods I ' + @SqlGoods +') G'

--
select @InBill +=' 
UNION ALL 
	SELECT  BD.GoodsID,'
	+ CASE WHEN BillTypeID = 101 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyQty,'
	+ ' 0 As BuyBackQty,'
	+ ' 0 As SaleQty,'
	+ CASE WHEN BillTypeID = 202 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleBackQty,'
	+ CASE WHEN BillTypeID = 301 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotTInQty,'
	+ CASE WHEN BillTypeID = 309 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotBInQty,'
	+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyInQty,'
	+' 0 As AllotTOutQty,'
	+' 0 As AllotBOutQty,'
	+' 0 As AssemblyOutQty,'
	+ CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceInQty,'
    + ' 0 As AdjuestPriceOutQty,'
	+ CASE WHEN BillTypeID = 303 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherInQty,'
	+ ' 0 As OtherOutQty,'
	+ CASE WHEN BillTypeID = 306 then ' Sum(BD.BSQty)' else ' 0' End + ' As PlusStockQty,'
	+ ' 0 AS ExchangeOutQty, 0 As MinusStockQty,'
	+ CASE WHEN BillTypeID IN (301,309) THEN ' Sum(BD.InspectQty)' ELSE ' Sum(BD.BSQty) ' END + ' as InBsQty,' 
	+ ' 0 as OutBsQty' 
	+ Case When @ShowTotal = 1 then	
		 CASE WHEN BillTypeID = 101 then ' ,sum(BD.GoodsCostTotal)' else ' ,0' End + ' As BuyTotal,'
		+ ' 0 As BuyBackTotal,'
		+ ' 0 As SaleTotal,'
		+ CASE WHEN BillTypeID = 202 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleBackTotal,'
		+ CASE WHEN BillTypeID = 301 then ' sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' else ' 0' End + ' As AllotTInTotal,'
		+ CASE WHEN BillTypeID = 309 then ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' else ' 0' End + ' As AllotBInTotal,'
		+ CASE WHEN BillTypeID = 310 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyInTotal,'
		+ ' 0 As AllotTOutTotal,'
		+ ' 0 As AllotBOutTotal,'
		+ ' 0 As AssemblyOutTotal,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.AdjTotal)' else ' 0' End + ' As AdjuestPriceInTotal,'
		+ ' 0 As AdjuestPriceOutTotal,'
		+ CASE WHEN BillTypeID = 303 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherInTotal,'
		+ ' 0 As OtherOutTotal,'
		+ CASE WHEN BillTypeID = 306 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As PlusStockTotal,'
		+ ' 0 AS ExchangeOutTotal, 0 As MinusStockTotal,'
		+ CASE BillTypeID WHEN 302 Then ' Sum(BD.AdjTotal)' WHEN 309 THEN ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' when 301 then ' SUM(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' Else ' Sum(BD.GoodsCostTotal)' End + ' AS InToTal,'
		+ ' 0 AS OutToTal'
	Else ''	End
	+' FROM  ' + BillDetail + ' BD '
	+'Inner Join  '+BillTable+' I On I.BillNo=bd.BillNo ' + @SqlTable
		+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
		+Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs Else @SqlWhsInDb End
	+' Where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  '	
	+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=1 ' ELSE '' END 	 
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
	+' Group By GoodsID
	 '
FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309,310)
And CanPost=1 
Select @OutBill += '
UNION ALL 
	SELECT  BD.GoodsID,'
	+ ' 0 As BuyQty,'
	+ CASE WHEN BillTypeID = 102 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyBackQty,'
	+ CASE WHEN BillTypeID = 201 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleQty,'
	+ ' 0 As SaleBackQty,'
	+ ' 0 As AllotTInQty,'
	+ ' 0 As AllotBInQty,'
	+ ' 0 As AssemblyInQty,'
	+ CASE WHEN BillTypeID = 301 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotTOutQty,'
	+ CASE WHEN BillTypeID = 309 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotBOutQty,'
	+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyOutQty,'
	+ ' 0 As AdjuestPriceInQty,'
    + CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceOutQty,'
	+ ' 0 As OtherInQty,'
	+ CASE WHEN BillTypeID = 304 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherOutQty,'
	+ ' 0 As PlusStockQty,'
	+ CASE WHEN BillTypeID = 600 then ' Sum(BD.BSQty)' else ' 0' End + ' As ExchangeOutQty,'
	+ CASE WHEN BillTypeID = 305 then ' Sum(BD.BSQty)' else ' 0' End + ' As MinusStockQty,'	
	+ ' 0 as InBsQty,' 
	+ ' Sum(BD.BSQty) as OutBsQty' 
	+ Case When @ShowTotal = 1 then	
		 ' ,0 As BuyTotal,'
		+ CASE WHEN BillTypeID = 102 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As BuyBackTotal,'
		+ CASE WHEN BillTypeID = 201 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleTotal,'
		+ ' 0 As SaleBackTotal,'
		+ ' 0 As AllotTInTotal,'
		+ ' 0 As AllotBInTotal,'
		+ ' 0 As AssemblyInTotal,'
		+ CASE WHEN BillTypeID = 301 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotTOutTotal,'
		+ CASE WHEN BillTypeID = 309 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotBOutTotal,'
		+ CASE WHEN BillTypeID = 310 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyOutTotal,'
		+ ' 0 As AdjuestPriceInTotal,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AdjuestPriceOutTotal,'
		+ ' 0 As OtherInTotal,'
		+ CASE WHEN BillTypeID = 304 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherOutTotal,'
		+ ' 0 As PlusStockTotal,'
		+ CASE WHEN BillTypeID = 600 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As ExchangeOutTotal,'
		+ CASE WHEN BillTypeID = 305 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As MinusStockTotal,'
		+ ' 0 AS InToTal,'
		+ ' Sum(BD.GoodsCostTotal) AS OutToTal'
	Else '' End
	+' FROM  ' + BillDetail + ' BD '
	+'Inner Join  '+BillTable+' I On I.BillNo=bd.BillNo  ' + @SqlTable
		+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
		+Case When billtypeid IN(102,201,302,304,305,600) Then @SqlWhs Else @SqlWhsOutDb End
	 +' where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 '	
	 + CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=2 ' ELSE '' END 	 
	 +CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
	+' Group By GoodsID
	 '
FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)

Select @StartOrEndInStock += '
UNION ALL 
	SELECT  BD.GoodsID,'
	+ CASE WHEN BillTypeID IN (301.309) THEN 'SUM(BD.InspectQty)' ELSE 'Sum(bd.BSQty)' END + ' as BsQty'
	+ Case When @ShowTotal = 1 then	
		case When BillTypeID = 302 then ' ,Sum(bd.AdjTotal)'
		When BillTypeID = 301 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)'
		When BillTypeID = 309 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.AllOtTotal End)'
		Else ' ,Sum(bd.GoodsCostTotal)' End +' as GoodsCostTotal '
	Else '' End
	+' From ' + BillDetail +' BD Inner Join  '+BillTable+' I On I.BillNo=bd.BillNo '	
	+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
	+ @SqlTable +Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs Else @SqlWhsInDb End
	+' where ' + Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End + ' and IsDraft=0 And Red = 0 '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END			 
	+' Group By GoodsID
	 '
	FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309)
Select @StartOrEndInStock += '
UNION ALL 
	SELECT  BD.GoodsID,Sum(bd.BSQty)*-1 as BsQty '
	+ Case When @ShowTotal = 1 then	',SUM(bd.GoodsCostTotal)*-1 as GoodsCostTotal '
	  Else '' End
	+' From ' + BillDetail +' BD Inner Join '+BillTable+' I On I.BillNo=bd.BillNo '
	+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
	+ @SqlTable +Case When billtypeid IN (102,201,302,304,305,600) Then @SqlWhs Else @SqlWhsOutDb End
	+' where ' + Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End +' and IsDraft=0 And Red = 0 '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
	 
	+' Group By GoodsID
	 '
	FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)
if @isHistory = 1 or @DateFlag=0
Begin
	Select @StartOrEndInStock += '
	UNION ALL 
		SELECT  BD.GoodsID,' 
		+ CASE WHEN BillTypeID IN (301.309) THEN 'SUM(BD.InspectQty)' ELSE 'Sum(bd.BSQty)' END + ' as BsQty'
		+ Case When @ShowTotal = 1 then	
			case When BillTypeID = 302 then ' ,Sum(bd.AdjTotal)' 
			When BillTypeID = 301 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)'
			When BillTypeID = 309 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.AllOtTotal End)'
			Else ' ,Sum(bd.GoodsCostTotal)' End +' as GoodsCostTotal '
		Else '' End
		+ ' From '	+ BillDetail +'_His BD Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo '
		+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
		+ @SqlTable +Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs Else @SqlWhsInDb End
		+' where '+ Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End +' and IsDraft=0 And Red = 0  '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		
		+' Group By GoodsID '
		FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309,310)
	Select @StartOrEndInStock += '
	UNION ALL 
		SELECT  BD.GoodsID,Sum(bd.BSQty)*-1 as BsQty '
		+ Case When @ShowTotal = 1 then	',SUM(bd.GoodsCostTotal)*-1 as GoodsCostTotal '
		  Else '' End
		+' From ' + BillDetail +'_His BD Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo '
		+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
		+ @SqlTable +Case When billtypeid IN (102,201,302,304,305,600) Then @SqlWhs Else @SqlWhsOutDb End
		+' where ' + Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End +' and IsDraft=0 And Red = 0 '
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		
		+' Group By GoodsID '
		FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)
End
IF @isHistory=1
Begin
	select @InBill +=' 
	UNION ALL 
		SELECT  BD.GoodsID,'
		+ CASE WHEN BillTypeID = 101 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyQty,'
		+ ' 0 As BuyBackQty,'
		+ ' 0 As SaleQty,'
		+ CASE WHEN BillTypeID = 202 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleBackQty,'
		+ CASE WHEN BillTypeID = 301 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotTInQty,'
		+ CASE WHEN BillTypeID = 309 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotBInQty,'
		+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyInQty,'
		+' 0 As AllotTOutQty,'
		+' 0 As AllotBOutQty,'
		+' 0 As AssemblyOutQty,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceInQty,'
		+ ' 0 As AdjuestPriceOutQty,'
		+ CASE WHEN BillTypeID = 303 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherInQty,'
		+ ' 0 As OtherOutQty,'
		+ CASE WHEN BillTypeID = 306 then ' Sum(BD.BSQty)' else ' 0' End + ' As PlusStockQty,'
		+ ' 0 As ExchangeOutQty, 0 As MinusStockQty,'
		+ CASE WHEN BillTypeID IN (301,309) THEN ' Sum(BD.InspectQty)' ELSE ' Sum(BD.BSQty) ' END + ' as InBsQty,' 
		+ ' 0 as OutBsQty' 
		+ Case When @ShowTotal = 1 then	
			 CASE WHEN BillTypeID = 101 then ' ,sum(BD.GoodsCostTotal)' else ' ,0' End + ' As BuyTotal,'
			+ ' 0 As BuyBackTotal,'
			+ ' 0 As SaleTotal,'
			+ CASE WHEN BillTypeID = 202 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleBackTotal,'
			+ CASE WHEN BillTypeID = 301 then ' sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' else ' 0' End + ' As AllotTInTotal,'
			+ CASE WHEN BillTypeID = 309 then ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' else ' 0' End + ' As AllotBInTotal,'
			+ CASE WHEN BillTypeID = 310 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyInTotal,'
			+ ' 0 As AllotTOutTotal,'
			+ ' 0 As AllotBOutTotal,'
			+ ' 0 As AssemblyOutTotal,'
			+ CASE WHEN BillTypeID = 302 then ' Sum(BD.AdjTotal)' else ' 0' End + ' As AdjuestPriceInTotal,'
			+ ' 0 As AdjuestPriceOutTotal,'
			+ CASE WHEN BillTypeID = 303 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherInTotal,'
			+ ' 0 As OtherOutTotal,'
			+ CASE WHEN BillTypeID = 306 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As PlusStockTotal,'
			+ ' 0 As ExchangeOutTotal, 0 As MinusStockTotal,'
			+ CASE BillTypeID WHEN 302 Then ' Sum(BD.AdjTotal)' WHEN 309 THEN ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' WHEN 301 THEN ' sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' Else ' Sum(BD.GoodsCostTotal)' End + ' AS InToTal,'
			+ ' 0 AS OutToTal'
		Else '' ENd
		+' FROM  ' + BillDetail + '_His BD '
		+' Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo ' + @SqlTable
			+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
			+Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs Else @SqlWhsInDb End
			+' where  BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 '
			+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=1 ' ELSE '' END 
			
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		+'  Group By GoodsID
		 '
	FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309,310)
	And CanPost=1 
	Select @OutBill += '
	UNION ALL 
		SELECT  BD.GoodsID,'
		+ ' 0 As BuyQty,'
		+ CASE WHEN BillTypeID = 102 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyBackQty,'
		+ CASE WHEN BillTypeID = 201 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleQty,'
		+ ' 0 As SaleBackQty,'
		+ ' 0 As AllotTInQty,'
		+ ' 0 As AllotBInQty,'
		+ ' 0 As AssemblyInQty,'
		+ CASE WHEN BillTypeID = 301 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotTOutQty,'
		+ CASE WHEN BillTypeID = 309 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotBOutQty,'
		+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyOutQty,'
		+ ' 0 As AdjuestPriceInQty,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceOutQty,'
		+ ' 0 As OtherInQty,'
		+ CASE WHEN BillTypeID = 304 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherOutQty,'
		+ CASE WHEN BillTypeID = 600 then ' Sum(BD.BSQty)' else ' 0' End + ' As ExchangeOutQty,'
		+ ' 0 As PlusStockQty,'
		+ CASE WHEN BillTypeID = 305 then ' Sum(BD.BSQty)' else ' 0' End + ' As MinusStockQty,'	
		+ ' 0 as InBsQty,' 
		+ ' Sum(BD.BSQty) as OutBsQty' 
		+ Case When @ShowTotal = 1 then	
			 ' ,0 As BuyTotal,'
			+ CASE WHEN BillTypeID = 102 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As BuyBackTotal,'
			+ CASE WHEN BillTypeID = 201 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleTotal,'
			+ ' 0 As SaleBackTotal,'
			+ ' 0 As AllotTInTotal,'
			+ ' 0 As AllotBInTotal,'
			+ ' 0 As AssemblyInTotal,'
			+ CASE WHEN BillTypeID = 301 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotTOutTotal,'
			+ CASE WHEN BillTypeID = 309 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotBOutTotal,'
			+ CASE WHEN BillTypeID = 310 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyOutTotal,'
			+ ' 0 As AdjuestPriceInTotal,'
			+ CASE WHEN BillTypeID = 302 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AdjuestPriceOutTotal,'
			+ ' 0 As OtherInTotal,'
			+ CASE WHEN BillTypeID = 304 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherOutTotal,'
			+ ' 0 As PlusStockTotal,'
			+ CASE WHEN BillTypeID = 600 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As ExchangeOutTotal,'
			+ CASE WHEN BillTypeID = 305 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As MinusStockTotal,'
			+ ' 0 AS InToTal,'
			+ ' Sum(BD.GoodsCostTotal) AS OutToTal'
		Else '' End
		+' FROM  ' + BillDetail + '_His BD '
		+' Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo ' + @SqlTable
			+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
			+Case When billtypeid IN(102,201,302,304,305,600) Then @SqlWhs Else @SqlWhsOutDb End
			+' Where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  '
			+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=2 ' ELSE '' END 
			
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		+' Group By GoodsID
		 '
	FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)

End

SELECT @sql +=@SqlCreateTable+'
;WITH Bill AS 
('	+STUFF(@InBill+@OutBill,1,12,'')+'
)'
Select @Sql +=',StartOrEndInOutStock as
(' +STUFF(@StartOrEndInStock,1,12,'')+')
,StartOrEndStock as --开始日期之前或者截止日期之后数量，金额
(
	select GoodsID,sum(BSQty) as StartOrEndStockQty'+ Case When @ShowTotal = 1 then	',SUM(GoodsCostTotal) as StartOrEndStockTotal ' else '' end
	+'  from StartOrEndInOutStock group by GoodsID	
)
,GoodsStock as  --库存(或者期初)数量，金额
('+Case When @DateFlag =1 then ' select G.goodsid,SUM(Qty) as qty'+ Case When @ShowTotal = 1 then	',SUM(Total) as total ' else '' end
	+' from bd_Goods g Left join (select GoodsID,WhsID,Qty' + case when @ShowTotal = 1 then ',total ' else '' end +' from PD_GoodsStock I '+@SqlWhsStock +@LimitSql +') I on g.GoodsID = I.goodsID   group by G.goodsid '
	Else
	' select G.goodsid,SUM(Qty) as qty'+ Case When @ShowTotal = 1 then	',SUM(Total) as total ' else '' end
	+' from  bd_Goods g Left join (select GoodsID,WhsID,Qty' + case when @ShowTotal = 1 then ',total ' else '' end +' from BD_OpeningStock I '+@SqlWhsStock+ @LimitSql+') I on g.GoodsID = I.goodsID group by G.goodsid '
	End	
+')'
select @sql += '
	,InOutStockSum as  --出库合计和入库合计
	(
		select 	GoodsID,sum(InBsQty) as INStockQty,sum(OutBsQty) as OutStockQty ' + Case When @ShowTotal = 1 then ',SUM(InToTal) as INStockTotal,SUM(OutToTal) as OutStockTotal '  Else '' End 
		+ ' from bill group by GoodsID
	)'
if @DateFlag = 1 
Begin
	select @sql += ',EndStockSum as --截止数量，金额
	(
		select a.goodsid,IsNull(a.Qty,0) - isnull(b.StartOrEndStockQty,0) as EndStockQty'
		+ Case When @ShowTotal = 1 then	',IsNull(a.Total,0)-  ISNULL(b.StartOrEndStockTotal,0) as EndStockTotal ' else '' End 
		+ ' from GoodsStock a left join StartOrEndStock b on a.GoodsID = b.GoodsID
	)'
	select @sql += '
	,StartStockSum as --开始数量、金额
	(
		select A.GoodsID,IsNUll(OutStockQty,0) - ISNULL(InStockQty,0) + ISNULL(EndStockQty,0) as BeforeQty '
			   + Case When @ShowTotal = 1 then ',ISNULL(OutStockTotal,0) - ISNULL(InStockTotal,0) + ISNULL(EndStockTotal,0) as BeforeTotal ' Else '' End
		+ ' from EndStockSum A left Join InOutStockSum B on a.GoodsID= b.GoodsID 
	)'
End
Else
Begin	
	select @sql +=',StartStockSum as --开始数量、金额
	(
		select a.goodsid,IsNull(a.Qty,0) + isnull(b.StartOrEndStockQty,0) as BeforeQty'
		+ Case When @ShowTotal = 1 then	',isnull(a.Total,0) + ISNULL(b.StartOrEndStockTotal,0) as BeforeTotal ' else '' End 
		+ ' from GoodsStock a left join StartOrEndStock b on a.GoodsID = b.GoodsID
	)'
	select @sql += ',EndStockSum as --截止数量，金额
	(
	select A.GoodsID,ISNULL(BeforeQty,0) + IsNUll(InStockQty,0) - ISNULL(OutStockQty,0)  as EndStockQty '
			   + Case When @ShowTotal = 1 then ',ISNULL(BeforeTotal,0)+ISNULL(InStockTotal,0) - ISNULL(OutStockTotal,0) as EndStockTotal ' Else '' End
		+ ' from StartStockSum A left Join InOutStockSum B on a.GoodsID= b.GoodsID 
	)'
End
Select @Sql += ' ,StockData as
( 	select  GoodsID,Sum(BuyQty) as BuyQty,Sum(BuyBackQty) as BuyBackQty,Sum(SaleQty) as SaleQty,Sum(SaleBackQty) as SaleBackQty,Sum(AllotTInQty) as AllotTInQty,Sum(AllotBInQty) as AllotBInQty,Sum(AllotTOutQty) as AllotTOutQty,Sum(AllotBOutQty) as AllotBOutQty,
	Sum(AdjuestPriceInQty) as AdjuestPriceInQty,Sum(AdjuestPriceOutQty) as AdjuestPriceOutQty,Sum(OtherInQty) as OtherInQty,Sum(OtherOutQty) as OtherOutQty,Sum(PlusStockQty) as PlusStockQty,Sum(ExchangeOutQty) as ExchangeOutQty,Sum(MinusStockQty) as MinusStockQty,Sum(AssemblyInQty) as AssemblyInQty,Sum(AssemblyOutQty) as AssemblyOutQty'
	+ Case When @ShowTotal = 1 then	',Sum(BuyTotal) as BuyTotal,Sum(BuyBackTotal) as BuyBackTotal,Sum(SaleTotal) as SaleTotal,Sum(SaleBackTotal) as SaleBackTotal,Sum(AllotTInTotal) as AllotTInTotal,Sum(AllotBInTotal) as AllotBInTotal,Sum(AllotTOutTotal) as AllotTOutTotal,Sum(AllotBOutTotal) as AllotBOutTotal,
	Sum(AdjuestPriceInTotal) as AdjuestPriceInTotal,Sum(AdjuestPriceOutTotal) as AdjuestPriceOutTotal,Sum(OtherInTotal) as OtherInTotal,Sum(OtherOutTotal) as OtherOutTotal,Sum(PlusStockTotal) as PlusStockTotal,Sum(ExchangeOutTotal) as ExchangeOutTotal,Sum(MinusStockTotal) as MinusStockTotal,sum(AssemblyInTotal) as AssemblyInTotal,sum(AssemblyOutTotal) as AssemblyOutTotal '
	Else '' End
	+' from Bill Group By  GoodsID
) '
select @Sql += ',PagingData as
(
	select Sum(BuyQty) as BuyQty,Sum(BuyBackQty) as BuyBackQty,Sum(SaleQty) as SaleQty,Sum(SaleBackQty) as SaleBackQty,Sum(AllotTInQty) as AllotTInQty,Sum(AllotBInQty) as AllotBInQty,Sum(AllotTOutQty) as AllotTOutQty,Sum(AllotBOutQty) as AllotBOutQty,
	Sum(AdjuestPriceInQty) as AdjuestPriceInQty,Sum(AdjuestPriceOutQty) as AdjuestPriceOutQty,Sum(OtherInQty) as OtherInQty,Sum(OtherOutQty) as OtherOutQty,Sum(PlusStockQty) as PlusStockQty,Sum(ExchangeOutQty) as ExchangeOutQty,Sum(MinusStockQty) as MinusStockQty,Sum(AssemblyInQty) as AssemblyInQty,Sum(AssemblyOutQty) as AssemblyOutQty,
	Sum(IOSS.InStockQty) as InStockQty,Sum(IOSS.OutStockQty) as OutStockQty,Sum(sss.BeforeQty) as BeforeQty,Sum(ESS.EndStockQty) as EndStockQty '
	+ Case When @ShowTotal = 1 then ',Sum(BuyTotal) as BuyTotal,Sum(BuyBackTotal) as BuyBackTotal,Sum(SaleTotal) as SaleTotal,Sum(SaleBackTotal) as SaleBackTotal,Sum(AllotTInTotal) as AllotTInTotal,Sum(AllotBInTotal) as AllotBInTotal,Sum(AllotTOutTotal) as AllotTOutTotal,Sum(AllotBOutTotal) as AllotBOutTotal,
	Sum(AdjuestPriceInTotal) as AdjuestPriceInTotal,Sum(AdjuestPriceOutTotal) as AdjuestPriceOutTotal,Sum(OtherInTotal) as OtherInTotal,Sum(OtherOutTotal) as OtherOutTotal,Sum(PlusStockTotal) as PlusStockTotal,Sum(ExchangeOutTotal) as ExchangeOutTotal,Sum(MinusStockTotal) as MinusStockTotal,sum(AssemblyInTotal) as AssemblyInTotal,sum(AssemblyOutTotal) as AssemblyOutTotal
	,Sum(IOSS.InStockTotal) as InStockTotal,Sum(IOSS.OutStockTotal) as OutStockTotal,Sum(sss.BeforeTotal) as BeforeTotal,Sum(ESS.EndStockTotal) as EndStockTotal,case sum(EndStockQty) when 0 then 0 else Convert(NUMERIC(17,8),sum(EndStockTotal))/Convert(NUMERIC(17,8),sum(EndStockQty)) end as CostPrice '
	Else '' End
	+' from '+@SqlBase+' Left Join StockData SD on g.BaseID = SD.GoodsID 	
	left Join InOutStockSum IOSS  on G.BaseID =IOSS.GoodsID 
	Left join StartStockSum SSS on G.BaseID = SSS.GoodsID
	left join EndStockSum ESS on G.BaseID = ESS.GoodsID
	where BuyQty<>0 Or BuyBackQty <> 0 Or SaleQty<>0 Or SaleBackQty<>0 Or AllotTInQty<>0 Or AllotTOutQty<>0 Or AllotBInQty<>0 Or AllotBOutQty<>0 Or AdjuestPriceInQty <> 0 
			Or AdjuestPriceOutQty <> 0 Or OtherInQty <> 0 Or OtherOutQty<>0 OR ExchangeOutQty <>0 Or PlusStockQty <> 0 Or MinusStockQty <> 0 
			Or IOSS.InStockQty <> 0 Or IOSS.OutStockQty<>0 Or sss.BeforeQty <> 0 Or ESS.EndStockQty <> 0'
	+ Case When @ShowTotal = 1 then ' Or BuyToTal<>0 Or BuyBackToTal <> 0 Or SaleToTal<>0 Or SaleBackToTal<>0 Or AllotTInToTal<>0 Or AllotBInToTal<>0 
			Or AllotTOutToTal<>0 Or AllotBOutToTal<>0 Or AdjuestPriceInToTal <> 0 Or AdjuestPriceOutToTal <> 0 Or OtherInToTal <> 0 Or OtherOutToTal<>0 
			Or PlusStockToTal <> 0 OR ExchangeOutTotal <> 0 Or MinusStockToTal <> 0 Or IOSS.InStockTotal<>0 Or IOSS.OutStockTotal<>0 Or sss.BeforeTotal<>0
			Or ESS.EndStockTotal <> 0'
	Else '' End
	+ ' 
)
select * from PagingData
'
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
exec sp_executesql @sql,N'@BeginDate Date,@EndDate Date,@OperatorID Int,@DeptID VarChar(MAX),@ElyID VarChar(MAX),@CreatorID varchar(MAx)
						,@WhsID VarChar(MAX),@PTypeID VarChar(MAX), @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)'
						,@BeginDate,@EndDate,@OperatorID,@DeptID,@ElyID,@CreatorID,@WhsID,@PTypeID, @Model, @AbbName, @Brand, @Spec, @BarCode

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UP_PD_MonthSaleStatus]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [dbo].UP_PD_MonthSaleStatus
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		HLin
-- Create date:  2015/3/13
-- Description:	 单据右键--月度销售情况
-- =============================================
CREATE PROCEDURE [dbo].[UP_PD_MonthSaleStatus](
	 @BeginMonth DATE,
	 @EndMonth DATE,
	 @BTypeID VARCHAR(1000) = '',          --往来单位
	 @GoodsID INT=0,					   --商品	
	 @OperatorID INT = 0                   --操作员ID      
	 --@Type INT
   ) 
AS
SET NOCOUNT ON;
	DECLARE @NewMonth DATE
	SET @NewMonth=@BeginMonth
	SET @EndMonth=DATEADD(DAY,-1,DATEADD(MONTH,1,@EndMonth))
	CREATE TABLE #Month(YEAR INT,MONTH INT,ID INT IDENTITY(1,1))
	WHILE @NewMonth<@EndMonth
	BEGIN
		INSERT INTO #Month
				( YEAR, MONTH )
		VALUES  ( YEAR(@NewMonth), -- YEAR - int
				  MONTH(@NewMonth)  -- MONTH - int
				  )
		SET @NewMonth=DATEADD(MONTH,1,@NewMonth)
	END                         
	
	CREATE TABLE #BType (TypeID INT) 
	IF @BTypeID<>'' OR dbo.UF_BD_IsAllBtypeLimit(@OperatorID)<>2
	BEGIN
		IF @BTypeID<>'' AND dbo.UF_BD_IsAllBtypeLimit(@OperatorID)=2 
			insert into #BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,',') 
		ELSE IF @BTypeID='' AND dbo.UF_BD_IsAllBtypeLimit(@OperatorID)<>2
			INSERT INTO #BType SELECT BTypeID from dbo.UF_BD_BtypeLimit(@OperatorID) 
		ELSE
			INSERT INTO #BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,',') a inner join dbo.UF_BD_BtypeLimit(@OperatorID) b ON b.BtypeID =a.typeid 
	END
	ELSE
		INSERT INTO #BType( TypeID )SELECT BTypeID FROM dbo.BD_Btype
		
	SELECT m.Year,m.Month,a.* ,COUNT(*)OVER()AS [ROWCOUNT]
	FROM #Month m
	LEFT JOIN 
	(	
		SELECT Year,Month,SUM(Qty)Qty,SUM(Total)Total,CASE WHEN ISNULL(SUM(Qty),0)=0 THEN NULL ELSE CAST(SUM(Total)/SUM(Qty)AS DECIMAL(20,8)) END Price
		FROM
		(
			SELECT YEAR(d.BillDate)Year,MONTH(d.BillDate)MONTH,BTypeID,SUM(BSQty)Qty,SUM(d.DiscTotal)Total 
			FROM dbo.PD_SellDetail d
			INNER JOIN  dbo.PD_SellBill b ON d.BillNo = b.BillNo
			WHERE d.BillDate BETWEEN @BeginMonth AND @EndMonth  AND IsDraft=0 AND Red=0 AND GoodsID=@GoodsID
			GROUP BY YEAR(d.BillDate),MONTH(d.BillDate),BTypeID
			UNION ALL
			SELECT YEAR(d.BillDate),MONTH(d.BillDate),BTypeID,SUM(BSQty),SUM(d.DiscTotal) 
			FROM dbo.PD_SellDetail_HIS d
			INNER JOIN  dbo.PD_SellBill_His b ON d.BillNo = b.BillNo
			WHERE d.BillDate BETWEEN @BeginMonth AND @EndMonth  AND IsDraft=0 AND Red=0 AND GoodsID=@GoodsID
			GROUP BY YEAR(d.BillDate),MONTH(d.BillDate),BTypeID
			UNION ALL
			SELECT YEAR(d.BillDate),MONTH(d.BillDate),BTypeID,SUM(-BSQty),SUM(-d.DiscTotal) 
			FROM dbo.PD_SellRetDetail d
			INNER JOIN  dbo.PD_SellRetBill b ON d.BillNo = b.BillNo
			WHERE d.BillDate BETWEEN @BeginMonth AND @EndMonth  AND IsDraft=0 AND Red=0 AND GoodsID=@GoodsID
			GROUP BY YEAR(d.BillDate),MONTH(d.BillDate),BTypeID
			UNION ALL
			SELECT YEAR(d.BillDate),MONTH(d.BillDate),BTypeID,SUM(-BSQty),SUM(-d.DiscTotal) 
			FROM dbo.PD_SellRetDetail_HIS d
			INNER JOIN  dbo.PD_SellRetBill_His b ON d.BillNo = b.BillNo
			WHERE d.BillDate BETWEEN @BeginMonth AND @EndMonth  AND IsDraft=0 AND Red=0 AND GoodsID=@GoodsID
			GROUP BY YEAR(d.BillDate),MONTH(d.BillDate),BTypeID
		)b INNER JOIN #BType b1 ON b1.TypeID=b.BTypeID
		GROUP BY YEAR,MONTH
	)a ON m.MONTH = a.Month AND m.YEAR = a.Year

	DROP TABLE #Month,#BType
	
GO




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

/*------------------------------------------
    作者：李文博
	日期：2014-09-10
	描述：往来单位未结算单据选择
-------------------------------------------*/
CREATE PROCEDURE UP_PD_NoPaidBillSelect
(
	@PageNo INT = 0,
	@PageSize INT = 0,
	@BtypeID INT = 0,
	@BillTypeID VARCHAR(MAX),
	@DeptID VARCHAR(MAX),
	@ElyID VARCHAR(MAX),
	@BillCode VARCHAR(50),
	@Summary VARCHAR(256),
	@Description VARCHAR(100),
	@BeginDate VARCHAR(10),
	@EndDate VARCHAR(10),
	@PayRecType INT = 0,
	@PayRecBillNo INT = 0
)
AS

DECLARE @Sql NVARCHAR(MAX)='', @CreateTableSql NVARCHAR(MAX)='', @IndexSql NVARCHAR(MAX) ='', @TableSql NVARCHAR(MAX) = ''
DECLARE @BtypeName VARCHAR(100), @QCBillDate DATE = '1900-01-01', @BillTypeSql NVARCHAR(MAX) = '', @BuyFeeBill NVARCHAR(MAX) = ''
DECLARE @BuyBill NVARCHAR(MAX) = '', @BuyBackBill NVARCHAR(MAX) = '', @SaleBill NVARCHAR(MAX) = '', @SaleBackBill NVARCHAR(MAX) = ''
DECLARE @FeeRecBill NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = '', @QCBill NVARCHAR(MAX) = '', @SaleFeeBill NVARCHAR(MAX) = ''

SELECT @BtypeName = BTypeName FROM BD_Btype WHERE BTypeID = @BtypeID
SELECT @QCBillDate = StartDate FROM SS_MonthProc WHERE Period = 1

IF @BeginDate <> ''
	SET @IndexSql += ' AND BillDate >= @BeginDate'
IF @EndDate <> ''
	SET @IndexSql += ' AND BillDate <= @EndDate'

SET @IndexSql += ' AND BillCode like ''%''+@BillCode+''%''  AND Summary Like ''%''+@Summary+''%'' AND Description Like ''%''+@Description+''%'' '

IF @DeptID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT) 
				 INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d 
				 INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID 
				 INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''
				 WHERE d2.SonNum = 0
				 '
	SET @TableSql+=' INNER JOIN @DType D ON I.DeptID=D.DeptID '	 
END
	
IF @ElyID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT) 
				 INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','') 
				 '
	SET @TableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '	 
END

IF @BillTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BillType Table(BillTypeID INT) 
				 INSERT  INTO @BillType SELECT typeid AS BillTypeID  FROM dbo.UF_OT_Split_Int(@BillTypeID,'','') 
		'
	SET @BillTypeSql += ' INNER JOIN @BillType bill ON bd.BillTypeID=bill.BillTypeID '	
END


SET @CreateTableSql += ' DECLARE @PayRecList Table(BillTypeID INT, BillNo INT, PaidTotal DECIMAL(20,8), Tag TINYINT)
	 INSERT  INTO @PayRecList SELECT BillTypeID, BillNo, PaidTotal, Tag FROM MF_PayRecList WHERE PayRecBillNo = @PayRecBillNo
	'


IF @PayRecType = 401 --付款
BEGIN
	--采购单
	SET @BuyBill = '
	SELECT	I.BillNo,	BillCode,	BillDate,	101 AS BillTypeID,	Summary,	Description, 
			Total,	(Total - I.PaidTotal - PayRecTotal - Privilege + ISNULL(ISNULL(PRL.PaidTotal,0),0)) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_PchBill I '+ @TableSql +'
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = 101 
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--采购退货单
	SET @BuyBackBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	102 AS BillTypeID,	Summary,	Description, 
			Total*(-1) AS Total, (Total - I.PaidTotal -PayRecTotal-Privilege + ISNULL(ISNULL(PRL.PaidTotal,0),0))*(-1) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_PchRetBill I '+ @TableSql +'
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = 102
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--一般费用单	
	SET @FeeRecBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	I.BillTypeID,		Summary,	Description, 
			Total,		(Total - I.PaidTotal - PayRecTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0)) AS BalanceTotal,	0 AS Tag,	4 AS GroupID   
		FROM MF_FeeRecBill I ' + @TableSql + '
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = I.BillTypeID
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND I.BillTypeID = 404 '+ @IndexSql
	--应付增加/减少	
	SET @ARAPBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	I.BillTypeID,		Summary,	Description, 
			   CASE I.BillTypeID WHEN 503 THEN Total ELSE Total*(-1) END AS Total, 
			   CASE I.BillTypeID WHEN 503 THEN (Total - I.PaidTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0)) ELSE (Total - I.PaidTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0))*(-1) END AS BalanceTotal,
			   0 AS Tag,	5 AS GroupID  
		FROM MF_ARAPBill I ' + @TableSql + '
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = I.BillTypeID 
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND I.BillTypeID IN (503, 504) ' + @IndexSql
	--期初应付	
	SET @QCBill = '
	UNION ALL
	SELECT	ARAPID AS BillNo,	''本年期初应付'' AS BillCode,	@QCBillDate AS BillDate,	999 AS BillTypeID, 
			   ''【' +@BtypeName+'】本年期初应付'' AS Summary,	'''' AS Description,	QcAP AS Total, 
			   QcAP - APPaidTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0) AS  BalanceTotal ,	0 AS Tag,	1 AS GroupID 
		FROM BD_ARAP I 
		LEFT JOIN @PayRecList PRL ON I.ARAPID = PRL.BillNo AND PRL.BillTypeID = 999
		WHERE BtypeID = @BtypeID AND QcAP <>0 '
	--销售单运费	
	SET @SaleFeeBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	201 AS BillTypeID,		''【物流运费】''+Summary,	Description, 
			   Freight AS Total,	(Freight - FreightPaidTotal - FreightTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0)) AS BalanceTotal,
			   1 AS Tag,	6 AS GroupID  
		FROM PD_SellBill I' + @TableSql +'
		LEFT JOIN @PayRecList PRL ON I.BillNo = PRL.BillNo AND PRL.BillTypeID = 201 AND PRL.Tag = 1
		WHERE LogistBTypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND IsOS = 0 AND Freight <> 0'+@IndexSql
	--采购单运费	
	SET @BuyFeeBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	101 AS BillTypeID,		''【物流运费】''+Summary,	Description, 
			   Freight AS Total,	(Freight - FreightPaidTotal - FreightTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0)) AS BalanceTotal,
			   1 AS Tag,	6 AS GroupID  
		FROM PD_PchBill I' + @TableSql +'
		LEFT JOIN @PayRecList PRL ON I.BillNo = PRL.BillNo AND PRL.BillTypeID = 101 AND PRL.Tag = 1
		WHERE LogistBTypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND Freight <> 0'+@IndexSql
END ELSE
IF @PayRecType = 402 --收款
BEGIN
	--销售单
	SET @SaleBill = '
	SELECT	I.BillNo,		BillCode,	BillDate,	201 AS BillTypeID,	Summary,	Description, 
			Total,	(Total - I.PaidTotal - PayRecTotal - Privilege + ISNULL(ISNULL(PRL.PaidTotal,0),0)) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_SellBill I '+ @TableSql +'
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = 201 AND PRL.Tag = 0
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--销售退货单
	SET @BuyBackBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	202 AS BillTypeID,	Summary,	Description, 
			Total*(-1) AS Total, (Total - I.PaidTotal -PayRecTotal-Privilege + ISNULL(ISNULL(PRL.PaidTotal,0),0))*(-1) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_SellRetBill I '+ @TableSql +'
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = 202
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--其它收入单
	SET @FeeRecBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	I.BillTypeID,		Summary,	Description, 
			Total,		(Total - I.PaidTotal - PayRecTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0)) AS BalanceTotal,	0 AS Tag,	4 AS GroupID   
		FROM MF_FeeRecBill I ' + @TableSql + '
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = I.BillTypeID 
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND I.BillTypeID = 405 '+ @IndexSql
	--应收增加/减少
	SET @ARAPBill = '
	UNION ALL
	SELECT	I.BillNo,		BillCode,	BillDate,	I.BillTypeID,		Summary,	Description, 
			   CASE I.BillTypeID WHEN 501 THEN Total ELSE Total*(-1) END AS Total, 
			   CASE I.BillTypeID WHEN 501 THEN (Total - I.PaidTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0)) ELSE (Total - I.PaidTotal + ISNULL(ISNULL(PRL.PaidTotal,0),0))*(-1) END AS BalanceTotal,
			   0 AS Tag,	5 AS GroupID  
		FROM MF_ARAPBill I ' + @TableSql + '
		LEFT JOIN @PayRecList PRL ON I.BillNo= PRL.BillNo AND PRL.BillTypeID = I.BillTypeID 
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND I.BillTypeID IN (501, 502) ' + @IndexSql
	SET @QcBill = '
	UNION ALL
	SELECT	ARAPID AS BillNo,	''本年期初应收'' AS BillCode,	@QCBillDate AS BillDate,	998 AS BillTypeID, 
			   ''【' +@BtypeName+'】本年期初应付'' AS Summary,	'''' AS Description,	QcAR AS Total, 
			   QcAR - ARPaidTotal + ISNULL(PRL.PaidTotal,0) AS  BalanceTotal ,	0 AS Tag,	1 AS GroupID 
		FROM BD_ARAP I 
		LEFT JOIN @PayRecList PRL ON I.ARAPID= PRL.BillNo AND PRL.BillTypeID = 998
		WHERE BtypeID = @BtypeID AND QcAR <>0 '
END

SET @Sql = @CreateTableSql + '
; WITH PagingData AS (
SELECT		BillNo,		BD.BillCode,	BillDate,	BD.BillTypeID,	BillName,	Summary,	Description,
			Total,		BalanceTotal,	Tag,		GroupID 
FROM (
	'+ @BuyBill + @SaleBill + @BuyBackBill + @SaleBackBill + @FeeRecBill + @ARAPBill + @QcBill + @SaleFeeBill + @BuyFeeBill + '
	) BD '+ @BillTypeSql+'
INNER JOIN PD_BillType BT ON BD.BillTypeID = BT.BillTypeID
WHERE BalanceTotal <> 0
) 
'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate','DATE', @BeginDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate','DATE', @EndDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillTypeID','VARCHAR(MAX)', @BillTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BtypeID','INT', @BtypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID','VARCHAR(MAX)',@DeptID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ElyID','VARCHAR(MAX)',@ElyID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillCode','VARCHAR(50)',@BillCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Summary','VARCHAR(256)',@Summary)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Description','VARCHAR(100)',@Description)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@QCBillDate','DATE',@QCBillDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@PayRecBillNo','INT', @PayRecBillNo)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, 'BillDate ASC, GroupID ASC','','ROWID ASC',1,1
	

GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询采购明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_OrdBuyDetailsSum]
(
	@DID Int = 0
)

AS
SET NOCOUNT ON

Declare @Sql Nvarchar(max)='',@SqlUnit1 varchar(500)='',@SqlUnit2 varchar(500)='',@SqlUnit3 varchar(500)='',@SqlWhs varchar(500)='',@SqlDept varchar(500)=''
		,@SqlEly varchar(500)='',@SqlCreator varchar(500)='',@SqlPost varchar(500)='',@SqlBSUnit varchar(500)='',@SqlUnit varchar(500)='',@SqlGoods varchar(500)=''
		,@SqlBtype varchar(500)='',@SqlPpt1 varchar(500)='',@SqlPpt2 varchar(500)=''

Select @Sql += ' select detail.BSQty as Qty,detail.Total,detail.DiscTotal,detail.Freight,detail.InTotal 
		from PD_PchDetail detail  Left Join PD_PchBill bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red = 0 And IsDraft = 0
		Union All
		select detail.BSQty as Qty,detail.Total,detail.DiscTotal,detail.Freight,detail.InTotal 
		from PD_PchDetail_His detail Left Join PD_PchBill_His bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red = 0 And IsDraft = 0
		'
SELECT @sql= '
;WITH Bill AS 
('	+@sql+'
)'
 select @Sql += ' select SUM(Qty) as Qty,SUM(total) as Total,SUM(DiscTotal) as DiscTotal,SUM(Freight) as Freight,SUM(InTotal) as InTotal
	 from  Bill '
 EXEC sp_executesql @sql,N'@DID Int',@DID

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询销售明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_OrdSaleDetailsSum]
(
	@DID Int = 0
)

AS
SET NOCOUNT ON

Declare @Sql Nvarchar(max)='',@SqlUnit1 varchar(500)='',@SqlUnit2 varchar(500)='',@SqlUnit3 varchar(500)='',@SqlWhs varchar(500)='',@SqlDept varchar(500)=''
		,@SqlEly varchar(500)='',@SqlCreator varchar(500)='',@SqlPost varchar(500)='',@SqlBSUnit varchar(500)='',@SqlUnit varchar(500)='',@SqlGoods varchar(500)=''
		,@SqlBtype varchar(500)='',@SqlPpt1 varchar(500)='',@SqlPpt2 varchar(500)=''

Select @Sql += ' select detail.BSQty as Qty,detail.Total,detail.DiscTotal,detail.GoodsCostTotal,
		(detail.DiscTotal-detail.GoodsCostTotal) as Profit
		from PD_SellDetail detail  Left Join PD_SellBill bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red = 0 And IsDraft = 0
		Union All
		select detail.BSQty as Qty,detail.Total,detail.DiscTotal,detail.GoodsCostTotal,
		(detail.DiscTotal-detail.GoodsCostTotal) as Profit
		from PD_SellDetail_His detail Left Join PD_SellBill_His bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red = 0 And IsDraft = 0
		'
SELECT @sql= '
;WITH Bill AS 
('	+@sql+'
)'
 select @Sql += ' select SUM(Qty) as Qty,SUM(total) as Total,SUM(DiscTotal) as DiscTotal,SUM(GoodsCostTotal) as GoodsCostTotal,SUM(Profit) as Profit
	 from  Bill '
 EXEC sp_executesql @sql,N'@DID Int',@DID

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：李文博	
	日期：2015-01-22
	描述：条件方案列表
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_PricePlanList]
(
	@PageNo INT =1,
	@PageSize INT = 20,
	@OperatorID INT = 1
)

AS
SET NOCOUNT ON

DECLARE @sql NVARCHAR(MAX)

SELECT @sql='
WITH PagingData AS 
(
	SELECT PlanID, 
		CreateTime, 
		Creator, 
		ElyName, 
		''新''+ pn1.PriceName+'' = ''+pn2.PriceName + 
		CASE pp.SignMark WHEN 0 THEN '' + '' WHEN 1 THEN '' - '' WHEN 2 THEN '' * '' WHEN 3 THEN '' / '' END 
		+ CONVERT(NVARCHAR(50),CONVERT(FLOAT, SianValue))+'' （保留''+CONVERT(NVARCHAR(5),[Precision])+''位小数）'' AS Expression,
		TargetPriceID AS NewField,
		SourcePriceID AS CurrField,
		SignMark AS Opera,
		SianValue AS NumberValue,
		Precision AS DigitLen
		FROM PD_PricePlan pp
INNER JOIN BD_Employee e ON pp.Creator = e.ElyID
INNER JOIN BD_PriceName pn1 ON pp.TargetPriceID = pn1.PriceID
INNER JOIN (
			SELECT PriceID, ''现''+PriceName AS PriceName FROM BD_PriceName
			UNION ALL
			SELECT -1 AS PriceID, ''成本均价'' AS PriceName
			UNION ALL
			SELECT -2 AS PriceID, ''最近进价'' AS PriceName
			UNION ALL
			SELECT 0 AS PriceID, ''0'' AS PriceName
			) pn2 ON pp.SourcePriceID = pn2.PriceID
WHERE Creator = @OperatorID	
) '

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)


EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'CreateTime ASC','','ROWID ASC',1,0

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_PriceTrailList]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_PriceTrailList]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



/*------------------------------------------
    作者：WangWei
	日期：2014-5-23
	描述：商品价格跟踪
-------------------------------------------*/
CREATE PROCEDURE UP_PD_PriceTrailList
(
	 @pageNo INT=0
	,@pageSize INT=0
	,@BtypeID int=0
	,@GoodsTypeID INT=0
	,@fullName VARCHAR(100)=''
	,@fullNameMatch int =0
	,@userCode VARCHAR(50)=''
	,@userCodeMatch int =0
	,@Spec VARCHAR(50)=''--规格
	,@SpecMatch int =0
	,@Model VARCHAR(50)=''--型号
	,@ModelMatch int =0
	,@Place VARCHAR(50)=''--产地
	,@PlaceMatch int =0
	,@Name VARCHAR(50)=''--简名
	,@NameMatch int =0
	,@Brand VARCHAR(50)=''--品牌
	,@BrandMatch int =0
	,@BarCode VARCHAR(100)=''--条码
	,@BarCodeMatch int =0
	,@UnitID int =0--计量单位
	,@PriceColumn Varchar(20) =''--价格类型
	,@PriceMin decimal(20,8)=-1 --最小值
	,@PriceMax decimal(20,8)=-1 --最大值
	,@showStopped BIT=0 --/*是否显示停用信息*/ 0=所有
	,@OperatorID INT --操作员ID
)

AS
SET NOCOUNT ON
begin
	DECLARE @isALL INT =2
	SELECT @isALL=dbo.UF_BD_IsAllBtypeLimit(@OperatorID) --是否所有权限

	DECLARE @sql NVARCHAR(max), @TVP as TVP_Paging_Param
	SET @sql=''

	IF @GoodsTypeID>0
	BEGIN
		
		SET	@sql+='  
					DECLARE @GoodsTypeTd as table(GoodsTypeID int,TypeCode varchar(50),TypeName varchar(100))
					
					INSERT INTO @GoodsTypeTd( GoodsTypeID,TypeCode,TypeName)
					SELECT gt.GoodsTypeID,gt.TypeCode,gt.TypeName
					FROM BD_Goods_Type t	
					INNER JOIN BD_Goods_Type gt ON gt.[Path] like t.[Path]+''%''			
					WHERE t.GoodsTypeID=@GoodsTypeID  AND gt.SonNum=0 '
			INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsTypeID','int',@GoodsTypeID)
	END


SET @sql+=';WITH '
IF 	 @BarCode<>''
BEGIN
	SET @sql+=' GoodsBarCode as
		(
			select distinct GoodsID from BD_Goods_Price where ' + case @BarCodeMatch when 0 then ' BarCode like ''%''+@BarCode+''%'' ' else ' BarCode = @BarCode ' end
		+' ), '
END
	

SET @sql+='
	PagingData AS
	(
		SELECT 
			t.TID
		   ,t.[GoodsID]
		  ,t.[UnitID]
		  ,t.BtypeID
		  ,t.PchPrice
		  ,t.SellPrice
		  ,t.PchDis
		  ,t.SellDis
		  ,t.PchDate
		  ,t.SellDate
		  ,b.BtypeName
		  ,b.BtypeCode
		  ,gt.GoodsTypeID
		  ,gt.TypeCode
		  ,gt.TypeName
		  ,g.GoodsName
		  ,g.GoodsNo
		  ,g.Spell
		  ,g.Spec
		  ,g.Model
		  ,g.Place
		  ,p.Unit
		  ,p.[Convfactor]
		  ,p.[BarCode]
		  ,g.Stt
		  ,g.GoodsAbbName as Name
		  ,g.Brand
		  '
SET 	@sql+='
	FROM [PD_PriceTrail] t'

IF @isALL=2
	SET 	@sql+=' INNER JOIN BD_Btype b ON b.BtypeID=t.BtypeID'
ELSE if @isALL=1
	SET 	@sql+=' 
					INNER JOIN BD_Btype b ON b.BtypeID=t.BtypeID
					INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bb ON b.BtypeID=bb.BtypeID'

SET 	@sql+=' 
			LEFT JOIN BD_Goods_Price p ON t.GOODSID=p.GOODSID AND t.UnitID=p.UnitID
			INNER JOIN BD_Goods g ON g.GoodsID=p.GoodsID '	
IF @GoodsTypeID>0
	SET @sql+='
			INNER JOIN @GoodsTypeTd  gt ON g.GoodsTypeID=gt.GoodsTypeID '
else 
	SET @sql+='
			INNER JOIN BD_Goods_Type gt ON g.GoodsTypeID=gt.GoodsTypeID '
IF @BarCode<>''
	SET @sql+='
			INNER JOIN GoodsBarCode Gbc ON g.GoodsID=Gbc.GoodsID '

if @isALL=0 --无权限
	SET @sql+='	WHERE 1=0 '
ELSE  
	SET @sql+='	WHERE 1=1 '


if @BtypeID>0
BEGIN
		SET	@sql+=' AND t.BtypeID=@BtypeID '
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BtypeID','int',@BtypeID)
END


if (@PriceColumn<>'' AND   @PriceColumn<>'0' AND ( @PriceMin<>-1 OR  @PriceMax<>-1))
BEGIN
	if (@PriceMin<>-1 )
		SET	@sql+=' AND (t.'+CAST(@PriceColumn as Varchar)+' >= @PriceMin )  '	
		 
	if (@PriceMax<>-1 )
		SET	@sql+=' AND (t.'+CAST(@PriceColumn as Varchar)+' <= @PriceMax)  '	 
	
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@PriceMin','decimal(20,8)',@PriceMin)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@PriceMax','decimal(20,8)',@PriceMax)
	
END


IF @UnitID>0
BEGIN
		SET	@sql+=' AND p.UnitID=@UnitID '
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UnitID','int',@UnitID)
END


IF 	 @userCode<>''
BEGIN
	
		if(@userCodeMatch=0)
				SET @sql +=' AND g.GoodsNo like ''%''+@userCode+''%'' '
		else if(@userCodeMatch=1)
				SET @sql +=' AND g.GoodsNo = @userCode '	  	
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@userCode','VARCHAR(50)',@userCode)
END	  

IF 	 @fullName<>''
BEGIN
		if(@fullNameMatch=0)
				SET @sql +=' AND g.GoodsName like ''%''+@fullName+''%'' '
		else if (@userCodeMatch=1)
			SET @sql +=' AND g.GoodsName = ''%''+@fullName+''%'' '
			
	 
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@fullName','VARCHAR(100)',@fullName)
	  	
END

IF 	 @Spec<>''
BEGIN
		if(@SpecMatch=0)
			SET @sql +=' AND g.Spec like  ''%''+@Spec+''%'' '
		else if  (@SpecMatch=1)
			SET @sql +=' AND g.Spec = @Spec '
			
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Spec','VARCHAR(50)',@Spec)
	  	
END

IF 	 @Model<>''
BEGIN

		if(@ModelMatch=0)
			SET @sql +=' AND g.Model like ''%''+@Model+''%'' '
		else if (@ModelMatch=1)
			SET @sql +=' AND g.Model = @Model '	
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Model','VARCHAR(50)',@Model)	  	
END


IF 	 @Place<>''
BEGIN

		if(@PlaceMatch=0)
			SET @sql +=' AND g.Place like ''%''+@Place+''%'' '
		else if (@PlaceMatch=1)
			SET @sql +=' AND g.Place = @Place '
	  
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Place','VARCHAR(50)',@Place)
END

IF 	 @Name<>''
BEGIN

		if(@NameMatch=0)
			SET @sql +=' AND g.GoodsAbbName like ''%''+@Name+''%'' '
		else if (@NameMatch=1)
			SET @sql +=' AND g.GoodsAbbName = @Name  '
	  
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Name','VARCHAR(50)',@Name)
END

IF 	 @Brand<>''
BEGIN

		if(@BrandMatch=0)
			SET @sql +=' AND g.Brand like ''%''+@Brand+''%'' '
		else if (@BrandMatch=1)
			SET @sql +=' AND g.Brand = @Brand  '
	  
		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Brand','VARCHAR(50)',@Brand)
END

IF 	 @BarCode<>''
BEGIN	  
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BarCode','VARCHAR(100)',@BarCode)
END


  
	  	
--IF @GoodsTypeID>0
--BEGIN
--		SET	@sql+=' AND g.GoodsTypeID=@GoodsTypeID '
--		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@GoodsTypeID','int',@GoodsTypeID)
--END

		INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)


IF @showStopped=0
BEGIN
		SET	@sql+=' AND g.stt=1'
END


SET @sql +=') '

EXEC UP_OT_Paging @sql,@TVP,@pageNo,@pageSize,'BtypeCode,GoodsNo','','',1,0
end
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_ProduceModelList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_ProduceModelList]
GO
/****** Object:  StoredProcedure [UP_PD_ProduceModelList]    Script Date: 01/20/2015 15:41:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/1/20
-- Description:	 生产模版选择
-- =============================================
CREATE PROCEDURE [UP_PD_ProduceModelList](
     @Type INT = 0,  --1:选择查询  --2:拆装回回填查询
     @PageNo INT = 0,
     @PageSize INT = 0,
     @SearchStr VARCHAR(4000) = '',
     @MaxRowCount INT = 0,
     @IndexWhsID INT = 0,
     @DetailWhsID INT = 0,
     @BillNoStr VARCHAR(MAX) = ''
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @DetailRowCount INT = 0,@feildsql VARCHAR(max)='',@joinsql VARCHAR(max)=''


	
	IF @Type = 1
		BEGIN
			SET @Sql = ';WITH PagingData AS (SELECT bill.*, g.GoodsNo, g.GoodsName FROM PD_ProduceModelBill bill INNER JOIN BD_Goods g ON bill.GoodsID = g.GoodsID WHERE 1 = 1 '
			IF @SearchStr <> ''
				SET @Sql += ' AND (bill.ModelName LIKE ''%' + @SearchStr + '%'' 
								OR g.GoodsName LIKE ''%' + @SearchStr + '%'') '  
			
			SET @Sql += '), DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A CROSS JOIN
											  (SELECT ROW_NUMBER() OVER(ORDER BY BillNo) AS ROWID,* FROM PagingData) B
									 WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
						 SELECT * FROM DATA'		 
		END
	IF @Type = 2
		BEGIN
			SELECT @joinsql+= CASE WHEN SourceType=1 THEN ' ' 
				WHEN SourceType=2 AND SOURCE=1 THEN ' LEFT JOIN BD_Goods G'+CAST(CustItemID AS VARCHAR)+' ON G'+CAST(CustItemID AS VARCHAR)+'.GoodsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
				WHEN SourceType=2 AND SOURCE=2 THEN ' LEFT JOIN BD_BType B'+CAST(CustItemID AS VARCHAR)+' ON B'+CAST(CustItemID AS VARCHAR)+'.BTypeID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
				WHEN SourceType=2 AND SOURCE=3 THEN ' LEFT JOIN BD_Whs W'+CAST(CustItemID AS VARCHAR)+' ON W'+CAST(CustItemID AS VARCHAR)+'.WhsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
				WHEN SourceType=2 AND SOURCE=4 THEN ' LEFT JOIN BD_Dept D'+CAST(CustItemID AS VARCHAR)+' ON D'+CAST(CustItemID AS VARCHAR)+'.DeptID=C.CustVal'+CAST(CustItemID AS VARCHAR)  
				WHEN SourceType=2 AND SOURCE=5 THEN ' LEFT JOIN BD_Employee E'+CAST(CustItemID AS VARCHAR)+' ON E'+CAST(CustItemID AS VARCHAR)+'.ElyID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
				WHEN SourceType=3 THEN ' LEFT JOIN BD_Custom C'+CAST(CustItemID AS VARCHAR) +' ON C'+CAST(CustItemID AS VARCHAR) +'.CustID=C.CustVal'+CAST(CustItemID AS VARCHAR)     
				END,
				@feildsql += CASE WHEN SourceType=1 THEN ' ,C.CustVal'+CAST(CustItemID AS VARCHAR)     
				WHEN SourceType=2 AND SOURCE=1 THEN ' ,G'+CAST(CustItemID AS VARCHAR)+'.GoodsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
				WHEN SourceType=2 AND SOURCE=2 THEN ' ,B'+CAST(CustItemID AS VARCHAR)+'.BTypeName AS CustVal'+CAST(CustItemID AS VARCHAR)   
				WHEN SourceType=2 AND SOURCE=3 THEN ' ,W'+CAST(CustItemID AS VARCHAR)+'.WhsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
				WHEN SourceType=2 AND SOURCE=4 THEN ' ,D'+CAST(CustItemID AS VARCHAR)+'.DeptName AS CustVal'+CAST(CustItemID AS VARCHAR)  
				WHEN SourceType=2 AND SOURCE=5 THEN ' ,E'+CAST(CustItemID AS VARCHAR)+'.ElyName AS CustVal'+CAST(CustItemID AS VARCHAR)   
				WHEN SourceType=3 THEN ',C'+CAST(CustItemID AS VARCHAR) +'.CustName AS CustVal'+CAST(CustItemID AS VARCHAR)     
				END
			FROM dbo.BD_Goods_CustomItem 
		
	        SELECT @DetailRowCount = COUNT(1) FROM PD_ProduceModelDetail detail INNER JOIN dbo.UF_OT_Split_Int(@BillNoStr, ',') _BillNo ON _BillNo.typeid = detail.BillNo
	        IF @DetailRowCount > @MaxRowCount
				SET @Sql = 'SELECT 1'
	        ELSE
				SET @Sql = 'SELECT bill.BillNo, bill.GoodsID, 1 AS BSQty, 1 AS Qty, bill.Ppt1ID, bill.Ppt2ID, bill.AssemblyCost,
								   goods.GoodsNo, goods.GoodsName, goods.Spec, goods.Model, goods.IsSerial, 
								   price1.UnitID, price1.Unit, price1.Convfactor, price1.BarCode,
								   price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1, price1.Convfactor AS Convfactor1,
								   price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, price2.Convfactor AS Convfactor2,
								   price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3, price3.Convfactor AS Convfactor3,
								   ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name, whspt.WhsID, whspt.WhsPtID, whspt.WhsPtName,goods.DateType,Goods.CostMethod,
								   ISNULL(stock.Price, 0) AS GoodsCostPrice, dWhs.WhsPtID AS DftWhsPtID, dWhspt.WhsPtName AS DftWhsPtName'+
								   @feildsql+' 
							FROM PD_ProduceModelBill bill
								 INNER JOIN dbo.UF_OT_Split_Int(@BillNoStr, '','') _BillNo ON _BillNo.typeid = bill.BillNo
								 INNER JOIN BD_Goods goods ON bill.GoodsID = goods.GoodsID
								 LEFT JOIN  BD_Goods_DftWhs dWhs ON dWhs.GoodsID = bill.GoodsID AND dWhs.WhsID = @IndexWhsID
								 LEFT JOIN  BD_Goods_Price price1 ON price1.GoodsID = bill.GoodsID AND price1.UnitID = 1 
								 LEFT JOIN  BD_Goods_Price price2 ON price2.GoodsID = bill.GoodsID AND price2.UnitID = 2
								 LEFT JOIN  BD_Goods_Price price3 ON price3.GoodsID = bill.GoodsID AND price3.UnitID = 3
								 LEFT JOIN  BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = bill.Ppt1ID
								 LEFT JOIN  BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = bill.Ppt2ID
								 INNER JOIN BD_Whs_Position whspt ON whspt.WhsID = @IndexWhsID AND whspt.WhsPtType = 1
								 LEFT JOIN BD_Whs_Position dWhspt ON dWhspt.WhsID = @IndexWhsID AND dWhspt.WhsPtID = dWhs.WhsPtID
								 LEFT JOIN  PD_GoodsStock stock ON stock.WhsID = @IndexWhsID AND stock.GoodsID = bill.GoodsID
								 LEFT JOIN BD_Goods_CustomVal c ON bill.goodsid=c.BaseID '+@joinsql+' 
							ORDER BY bill.BillNo
								 
							 SELECT detail.BillNo, detail.GoodsID, detail.Qty AS BSQty, detail.Qty, detail.Ppt1ID, detail.Ppt2ID, 
									goods.GoodsNo, goods.GoodsName, goods.Spec, goods.Model, goods.IsSerial, 0 AS AssemblyCost,
									price1.UnitID, price1.Unit, price1.Convfactor, price1.BarCode,
									price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1, price1.Convfactor AS Convfactor1,
									price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, price2.Convfactor AS Convfactor2,
									price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3, price3.Convfactor AS Convfactor3,
									ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name, whspt.WhsID, whspt.WhsPtID, whspt.WhsPtName,goods.DateType,Goods.CostMethod,
									ISNULL(stock.Price, 0) AS GoodsCostPrice, dWhs.WhsPtID AS DftWhsPtID, dWhspt.WhsPtName AS DftWhsPtName'+
								   @feildsql+'  
									FROM PD_ProduceModelDetail detail
								 INNER JOIN dbo.UF_OT_Split_Int(@BillNoStr, '','') _BillNo ON _BillNo.typeid = detail.BillNo
								 INNER JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
								 LEFT JOIN  BD_Goods_DftWhs dWhs ON dWhs.GoodsID = detail.GoodsID AND dWhs.WhsID = @DetailWhsID
								 LEFT JOIN  BD_Goods_Price price1 ON price1.GoodsID = detail.GoodsID AND price1.UnitID = 1 
								 LEFT JOIN  BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID AND price2.UnitID = 2
								 LEFT JOIN  BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID AND price3.UnitID = 3
								 LEFT JOIN  BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
								 LEFT JOIN  BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
								 INNER JOIN BD_Whs_Position whspt ON whspt.WhsID = @DetailWhsID AND whspt.WhsPtType = 1
								 LEFT JOIN BD_Whs_Position dWhspt ON dWhspt.WhsID = @DetailWhsID AND dWhspt.WhsPtID = dWhs.WhsPtID
								 LEFT JOIN  PD_GoodsStock stock ON stock.WhsID = @DetailWhsID AND stock.GoodsID = detail.GoodsID
								 LEFT JOIN BD_Goods_CustomVal c ON detail.goodsid=c.BaseID '+@joinsql+' 
							ORDER BY detail.BillNo'
		END
						 
    EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillNoStr VARCHAR(MAX), @IndexWhsID INT, @DetailWhsID INT', @PageNo, @PageSize, @BillNoStr, @IndexWhsID, @DetailWhsID
	
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryAllotBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryAllotBillData
GO
/****** Object:  StoredProcedure [UP_PD_QueryAllotBillData]    Script Date: 06/16/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		hanlin
-- Create date:  2014/6/16
-- Description:	 查询调拨单单数据
-- =============================================
CREATE PROCEDURE [UP_PD_QueryAllotBillData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS
BEGIN
IF EXISTS(SELECT 1 FROM PD_AllotBill WHERE BillNo=@BillNo)
BEGIN
	SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			301 AS BillType,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.InWhsID,
			wi.WhsName AS InWhsName ,
			p.OutWhsID,
			wo.WhsName AS OutWhsName ,
			Summary,
			Description,
			BillQty,
			Total,
			IsDraft,
			Red,
			InspectTag,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			p.AuditStatus
	FROM PD_AllotBill p
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs wi ON wi.WhsID=p.InWhsID
	INNER JOIN BD_Whs wo ON wo.WhsID=p.OutWhsID
	WHERE BillNo=@BillNo
	
	SELECT  P.DID,
			P.GoodsID,
			p.ReqDID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			g.Spec,
			p.InWhsPtID,
			wpi.WhsPtName AS InWhsPtName,
			p.InWhsID,
			p.OutWhsPtID,
			wpo.WhsPtName AS OutWhsPtName,
			p.OutWhsID,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			AllotPrice AS CostPrice,
			CostPrice AS GoodsCostPrice,
			Qty,
			BSQty,
			InspectQty/CASE p.UnitID WHEN 3 THEN ISNULL(gp3.Convfactor,1) WHEN 2 THEN ISNULL(gp2.Convfactor,1) ELSE 1 END AS InspectQty,
			GoodsCostTotal,
			p.Remark,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,	
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			op.BillCode	,
			p.VerifyQty	,
			CASE WHEN p.Qty=p.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
			g.IsSerial,
			p.BatchNumber,
			p.ProductDate,
			p.EndDate,p.InPutPrice,g.DateType,g.CostMethod,p.IsSelectBatch				
	FROM PD_AllotDetail p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wpi ON p.InWhsPtID=wpi.WhsPtID
	INNER JOIN BD_Whs_Position wpo ON p.OutWhsPtID=wpo.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN 
	(
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail D 
		INNER JOIN PD_AllotReqBill b ON d.BillNo = b.BillNo
		UNION ALL
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail_His D
		INNER JOIN PD_AllotReqBill_His b ON d.BillNo = b.BillNo
	) op ON op.DID= p.ReqDID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID=p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_AllotSerial ps Inner Join PD_AllotDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
END
ELSE
BEGIN
		SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			301 AS BillType,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.InWhsID,
			wi.WhsName AS InWhsName ,
			p.OutWhsID,
			wo.WhsName AS OutWhsName ,
			Summary,
			Description,
			BillQty,
			Total,
			IsDraft,
			Red,
			InspectTag,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			p.AuditStatus
	FROM PD_AllotBill_his p
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs wi ON wi.WhsID=p.InWhsID
	INNER JOIN BD_Whs wo ON wo.WhsID=p.OutWhsID
	WHERE BillNo=@BillNo
	
	SELECT  P.DID,
			p.GoodsID,
			p.ReqDID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			g.Spec,
			p.InWhsPtID,
			wpi.WhsPtName AS InWhsPtName,
			p.InWhsID,
			p.OutWhsPtID,
			wpo.WhsPtName AS OutWhsPtName,
			p.OutWhsID,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			AllotPrice AS CostPrice,
			CostPrice AS GoodsCostPrice,
			Qty,
			BSQty,
			InspectQty/CASE p.UnitID WHEN 3 THEN ISNULL(gp3.Convfactor,1) WHEN 2 THEN ISNULL(gp2.Convfactor,1) ELSE 1 END AS InspectQty,
			GoodsCostTotal,
			p.Remark,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,	
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			op.BillCode	,
			p.VerifyQty	,
			CASE WHEN p.Qty=p.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
			g.IsSerial,
			p.BatchNumber,
			p.ProductDate,
			p.EndDate,p.InPutPrice,g.DateType,g.CostMethod				
	FROM PD_AllotDetail_his p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wpi ON p.InWhsPtID=wpi.WhsPtID
	INNER JOIN BD_Whs_Position wpo ON p.OutWhsPtID=wpo.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN 
	(
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail D 
		INNER JOIN PD_AllotReqBill b ON d.BillNo = b.BillNo
		UNION ALL
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail_His D
		INNER JOIN PD_AllotReqBill_His b ON d.BillNo = b.BillNo
	) op ON op.DID= p.ReqDID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID=p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_AllotSerial_His ps Inner Join PD_AllotDetail_his pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
END
	
END
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-12-23
	描述：调拨申请单明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryAllotDetails]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@DID Int = 0,
	@ShowSerial INT = 0,    -- 是否显示序列号
	@OperatorID INT 
)

AS
SET NOCOUNT ON

Declare @Sql Nvarchar(max)='',@BillSql Nvarchar(max)='',@SqlCreateTable VARCHAR(max)='',@sqlOut Nvarchar(Max)='',@LimitSqlIN NVARCHAR(max)='',@LimitSqlOut NVARCHAR(max)='',@KtypeLimit int,
		-- 序列号相关字段信息
		@SeriesCol1 NVARCHAR(MAX)='',@SeriesCol2 NVARCHAR(MAX)='',@SeriesColEnd NVARCHAR(MAX)='', 
		@301 NVARCHAR(MAX) = '',@301_His NVARCHAR(MAX) = '',
		@309 NVARCHAR(MAX) = '',@309_His NVARCHAR(MAX) = '',@InOutExchangeStrO varchar(max)=' '
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSqlIN += ' Inner Join @LimitKType LW On LW.TypeID =i.InWhsID ' 	
	Set @LimitSqlOut += ' Inner Join @LimitKType LW On LW.TypeID =i.OutWhsID ' 	
End	

-- 是否显示序列号
IF @ShowSerial = 1
BEGIN
	SET @SeriesCol1 += ',Serial.Serial[seriesnum],Serial.CostPrice[seriesnumcost],Serial.Remark[seriesnumremark] '
	SET @SeriesCol2 += ',Serial.Serial[seriesnum],Serial.AllotPrice[seriesnumcost],Serial.Remark[seriesnumremark] '
	SET @SeriesColEnd += ',seriesnum,seriesnumcost,seriesnumremark '
	SET @301 += ' LEFT JOIN PD_AllotSerial Serial ON BD.DID = Serial.BillDID '
	SET @301_His += ' LEFT JOIN PD_AllotSerial_His Serial ON BD.DID = Serial.BillDID '
	SET @309 += ' LEFT JOIN PD_AllotSerial Serial ON BD.DID = Serial.BillDID '
	SET @309_His += ' LEFT JOIN PD_AllotSerial_His Serial ON BD.DID = Serial.BillDID ' 
END


Select @BillSql += ' SELECT  30101 AS BillTypeID,  DID,PosTime,GoodsID  '+@SeriesCol1+'
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @301 + @LimitSqlOut +' where 
		 IsDraft=0 AND I.BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  30102 AS BillTypeID,  DID,PosTime,GoodsID '+@SeriesCol1+'
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @301  + @LimitSqlIN +' where 
		 IsDraft=0 AND I.BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  30901 AS BillTypeID,  DID,PosTime,GoodsID '+@SeriesCol1+'
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @309  + @LimitSqlOut +' where 
		 IsDraft=0 AND I.BillTypeID = 309  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  30902 AS BillTypeID,  DID,PosTime,GoodsID '+@SeriesCol2+'
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' + @309  + @LimitSqlIN +' where 
		 IsDraft=0 AND I.BillTypeID = 309  And Red = 0 And ReqDID = @DID
	 '
select @BillSql+= '
	UNION ALL
		SELECT  30101 AS BillTypeID,  DID,PosTime,GoodsID '+@SeriesCol1+'
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @301_His + @LimitSqlOut +' where 
		 IsDraft=0 AND I.BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  30102 AS BillTypeID,  DID,PosTime,GoodsID '+@SeriesCol1+'
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @301_His + @LimitSqlIN +' where 
		 IsDraft=0 AND I.BillTypeID = 301  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  30901 AS BillTypeID,  DID,PosTime,GoodsID '+@SeriesCol1+'
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @309_His + @LimitSqlOut +' where 
		 IsDraft=0 AND I.BillTypeID = 309  And Red = 0 And ReqDID = @DID
	UNION ALL 
		SELECT  30902 AS BillTypeID,  DID,PosTime,GoodsID '+@SeriesCol1+'
		FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo ' + @309_His + @LimitSqlIN +' where 
		 IsDraft=0 AND I.BillTypeID = 309  And Red = 0 And ReqDID = @DID
		'
select @sqlOut += '  SELECT  A.*,  301 as BillTypeIDS,'''+'同价调拨单(出库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.OutWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as DiscPrice,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal	 
		FROM  #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo where A.BillTypeID = 30101 '
select @sqlOut += ' UNION ALL 
		SELECT  A.*,  301 as BillTypeIDS,'''+'同价调拨单(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.InWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as DiscPrice,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal	 
		FROM #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo where A.BillTypeID = 30102 '
Select @sqlOut += ' UNION ALL 
		SELECT  A.*,  309 as BillTypeIDS,'''+'变价调拨单(出库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.OutWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as DiscPrice,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal	 
		FROM  #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo where A.BillTypeID = 30901 '
select @sqlOut += ' UNION ALL 
		SELECT  A.*,  309 as BillTypeIDS,'''+'变价调拨单(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.InWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,Cast(BD.AllotTotal as decimal(20,8))/BD.BSQty As CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty,
		Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,BD.AllotPrice as DiscPrice,BD.AllotPrice as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.AllotTotal * -1 Else Bd.AllotTotal end as Total
		,Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as DiscTotal	 
		FROM #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo where A.BillTypeID = 30902  '
select @sqlOut += ' UNION ALL 
			SELECT  A.*,  301 as BillTypeIDS,'''+'同价调拨单(出库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.OutWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as DiscPrice,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal	 
			FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo where A.BillTypeID = 30101  '
select @sqlOut += ' UNION ALL 
			SELECT  A.*,  301 as BillTypeIDS,'''+'同价调拨单(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.InWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as DiscPrice,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal	 
			FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo where A.BillTypeID = 30102 '
select @sqlOut += ' UNION ALL 
			SELECT  A.*,  309 as BillTypeIDS,'''+'变价调拨单(出库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.OutWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as DiscPrice,Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal	 
			FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo where A.BillTypeID = 30901  '
select @sqlOut += ' UNION ALL 
			SELECT  A.*,  309 as BillTypeIDS,'''+'变价调拨单(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.InWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,Cast(BD.AllotPrice as decimal(20,8))/BD.BSQty As CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty,
		Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,0 as BTypeID,BD.AllotPrice as DiscPrice,BD.AllotPrice as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.AllotTotal * -1 Else Bd.AllotTotal end as Total
		,Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as DiscTotal	 
			FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo where A.BillTypeID = 30902  '
SELECT @sql= @SqlCreateTable + '
;WITH Bill AS 
('	+@BillSql+'
),
 PagingData AS
 (
	select BillTypeID,DID,CONVERT(varchar(100), PosTime, 120) AS PosTime,bill.GoodsID,G.GoodsNo,G.GoodsName
	       ,G.Spec, G.Model, G.Brand, G.GoodsAbbName  '+@SeriesColEnd+'
		from Bill bill  Inner JOIN BD_GOODS G on bill.GoodsID = G.GoodsID  ),DATA AS (
		SELECT *   
		FROM (SELECT COUNT(1) AS ''' +'ROWCOUNT' +''' 
				FROM PagingData) A
			   CROSS JOIN
			   (
			   select ROW_NUMBER() OVER( ORDER BY PosTime ASC, GoodsNo ASC) AS ROWID,*
						FROM PagingData 
				) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
 )
 select * into #InOutTemp from DATA
 '
 set @sql +='	
	select data.*,WhsNO,WhsName,DeptCode,DeptName,E.ElyCode,E.ElyName as ElyName,EC.ElyName as CreatorName,EP.ElyName as PostName,Gpc.Unit,BSGpc.Unit as BSUnit, Gpc.BarCode
		,GP1.Value as Ppt1Name,GP2.Value as Ppt2Name ,BTypeCode,BTypeName'
set @sql += ' from ( '+@sqlOut+' ) data
		Inner Join BD_Whs W On Data.WhsID = W.WhsID
		Left JOIN BD_Dept D ON Data.DeptID = D.DeptID  
		LEFT JOIN BD_Employee E ON Data.ElyID = E.ElyID 
		LEFT JOIN BD_Employee EC ON Data.Creator = EC.ElyID 
		LEFT JOIN BD_Employee EP ON Data.PosElyID = EP.ElyID 
		Inner Join BD_Goods_Price Gpc On Data.UnitID = Gpc.UnitID and Data.GoodsID = Gpc.GoodsID 
		Inner Join BD_Goods_Price BSGpc On Data.BsUnitID = BSGpc.UnitID and Data.GoodsID = BSGpc.GoodsID 
		Left Join BD_Goods_Ppt1 GP1 ON Data.Ppt1ID = GP1.Ppt1ID 
		Left Join BD_Goods_Ppt2 GP2 ON Data.Ppt2ID = GP2.Ppt2ID 
		Left JOIN BD_Btype B ON Data.BtypeID = B.BtypeID  ORDER BY ROWID drop table #InOutTemp 
		'
--IF @sql IS NULL OR @sql=''
--BEGIN
--	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
--	RETURN 
--END
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
Exec sp_executesql @Sql,N'@PageNo Int,@PageSize Int,@DID Int,@OperatorID Int,@ShowSerial Int',@PageNo,@PageSize,@DID,@OperatorID,@ShowSerial

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryAllotDifBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryAllotDifBillData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李文博
-- Create date:  2014/12/12
-- Description:	 查询变价调拨单单数据
-- =============================================
CREATE PROCEDURE [UP_PD_QueryAllotDifBillData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS
BEGIN
IF EXISTS(SELECT 1 FROM PD_AllotBill WHERE BillNo=@BillNo)
BEGIN
	SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			309 AS BillType,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.InWhsID,
			wi.WhsName AS InWhsName ,
			p.OutWhsID,
			wo.WhsName AS OutWhsName ,
			Summary,
			Description,
			BillQty,
			Total,
			IsDraft,
			Red,
			InspectTag,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			p.AuditStatus
	FROM PD_AllotBill p
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs wi ON wi.WhsID=p.InWhsID
	INNER JOIN BD_Whs wo ON wo.WhsID=p.OutWhsID
	WHERE BillNo=@BillNo
	
	SELECT  P.DID,
			P.GoodsID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			g.Spec,
			p.InWhsPtID,
			wpi.WhsPtName AS InWhsPtName,
			p.InWhsID,
			p.OutWhsPtID,
			wpo.WhsPtName AS OutWhsPtName,
			p.OutWhsID,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			ROUND(CostPrice*p.Convfactor,8) AS CostPrice,
			CostPrice AS GoodsCostPrice,
			Qty,
			BSQty,
			InspectQty/CASE p.UnitID WHEN 3 THEN ISNULL(gp3.Convfactor,1) WHEN 2 THEN ISNULL(gp2.Convfactor,1) ELSE 1 END AS InspectQty,
			GoodsCostTotal,
			p.Remark,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,	
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			p.ReqDID,
			p.AllotPrice,
			p.AllotTotal,
			op.BillCode	,
			p.VerifyQty	,
			CASE WHEN p.Qty=p.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
			g.IsSerial,
			p.BatchNumber,
			p.ProductDate,
			p.EndDate,p.InPutPrice,g.DateType,g.CostMethod,p.IsSelectBatch				
	FROM PD_AllotDetail p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wpi ON p.InWhsPtID=wpi.WhsPtID
	INNER JOIN BD_Whs_Position wpo ON p.OutWhsPtID=wpo.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN 
	(
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail D 
		INNER JOIN PD_AllotReqBill b ON d.BillNo = b.BillNo
		UNION ALL
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail_His D
		INNER JOIN PD_AllotReqBill_His b ON d.BillNo = b.BillNo
	) op ON op.DID= p.ReqDID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID=p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_AllotSerial ps Inner Join PD_AllotDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
END
ELSE
BEGIN
		SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			309 AS BillType,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.InWhsID,
			wi.WhsName AS InWhsName ,
			p.OutWhsID,
			wo.WhsName AS OutWhsName ,
			Summary,
			Description,
			BillQty,
			Total,
			IsDraft,
			Red,
			InspectTag,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			p.AuditStatus
	FROM PD_AllotBill_his p
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs wi ON wi.WhsID=p.InWhsID
	INNER JOIN BD_Whs wo ON wo.WhsID=p.OutWhsID
	WHERE BillNo=@BillNo
	
	SELECT  p.DID,
			p.GoodsID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			g.Spec,
			p.InWhsPtID,
			wpi.WhsPtName AS InWhsPtName,
			p.InWhsID,
			p.OutWhsPtID,
			wpo.WhsPtName AS OutWhsPtName,
			p.OutWhsID,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			ROUND(CostPrice*p.Convfactor,8) AS CostPrice,
			CostPrice AS GoodsCostPrice,
			Qty,
			BSQty,
			InspectQty/CASE p.UnitID WHEN 3 THEN ISNULL(gp3.Convfactor,1) WHEN 2 THEN ISNULL(gp2.Convfactor,1) ELSE 1 END AS InspectQty,
			GoodsCostTotal,
			p.Remark,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,	
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			p.ReqDID,
			p.AllotPrice,
			p.AllotTotal,
			op.BillCode	,
			p.VerifyQty	,
			CASE WHEN p.Qty=p.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
			g.IsSerial,
			p.BatchNumber,
			p.ProductDate,
			p.EndDate,p.InPutPrice,g.DateType,g.CostMethod				
	FROM PD_AllotDetail_His p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wpi ON p.InWhsPtID=wpi.WhsPtID
	INNER JOIN BD_Whs_Position wpo ON p.OutWhsPtID=wpo.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN 
	(
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail D 
		INNER JOIN PD_AllotReqBill b ON d.BillNo = b.BillNo
		UNION ALL
		SELECT b.BillCode,D.DID 
		FROM PD_AllotReqDetail_His D
		INNER JOIN PD_AllotReqBill_His b ON d.BillNo = b.BillNo
	) op ON op.DID= p.ReqDID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID=p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_AllotSerial_His ps Inner Join PD_AllotDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
END
	
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryAllotReqBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryAllotReqBillData
GO
/****** Object:  StoredProcedure [UP_PD_QueryAllotBillData]    Script Date: 06/16/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李文博
-- Create date:  2014/12/8
-- Description:	 查询调拨申请单数据
-- Update:增加IsDraft字段检索（确认生效状态）
-- =============================================
CREATE PROCEDURE [UP_PD_QueryAllotReqBillData]
(
	@BillNo INT = 0
) 
AS
BEGIN
SET NOCOUNT ON;
	DECLARE @SqlMain NVARCHAR(4000), @SqlDetail NVARCHAR(4000), 
	        @MainTable NVARCHAR(40) = 'PD_AllotReqBill', @DetailTable NVARCHAR(40) = 'PD_AllotReqDetail'
	IF NOT EXISTS (SELECT 1 FROM PD_AllotReqBill WHERE BillNo = @BillNo)
		BEGIN
			SET @MainTable += '_His'
			SET @DetailTable += '_His'
		END
	SET @SqlMain = 'SELECT ord.BillNo, ord.BillCode, ord.BillDate, ord.DlvDate, ord.DeptID, ord.ElyID, 
						   ord.InWhsID, ord.OutWhsID, ord.BillQty, creator.ElyName AS CreatorName, ord.CreateTime, 
						   ord.Summary, ord.Description, ord.StopTag, ord.Creator AS CreatorID, inwhs.WhsName AS InWhsName, ord.IsDraft,
						   outwhs.WhsName AS OutWhsName, dept.DeptName, ely.ElyName, ord.AuditStatus 
						   FROM ' + @MainTable + ' ord
						   LEFT JOIN BD_Whs inwhs ON ord.InWhsID = inwhs.WhsID
						   LEFT JOIN BD_Whs outwhs ON ord.OutWhsID = outwhs.WhsID
						   LEFT JOIN BD_Dept dept ON ord.DeptID = dept.DeptID
						   LEFT JOIN BD_Employee ely ON ord.ElyID = ely.ElyID
						   LEFT JOIN BD_Employee creator ON ord.Creator = creator.ElyID
					 WHERE ord.BillNo = @BillNo'  --查询主表
						
	EXEC sp_executesql @SqlMain, N'@BillNo INT', @BillNo
     
     SET @SqlDetail = 'SELECT detail.DID, detail.BillNo, detail.BarCode, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, 
							detail.InWhsID, detail.InWhsPtID, detail.OutWhsID, detail.OutWhsPtID, detail.UnitID, detail.Convfactor,  
							detail.Qty, detail.BSQty, detail.ComQty, detail.StopTag, detail.Remark, goods.GoodsNo, 
							goods.GoodsName, goods.Spec, goods.Model, price.Unit, ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name, 
							(SELECT COUNT(1) FROM PD_AllotDetail d 
											   INNER JOIN PD_AllotBill b ON d.BillNo = b.BillNo
											   WHERE d.ReqDID = detail.DID AND b.Red = 0) AS SelectQty,
							(SELECT COUNT(1) FROM PD_AllotDetail_His d 
											   INNER JOIN PD_AllotBill_His b ON d.BillNo = b.BillNo
											   WHERE d.ReqDID = detail.DID AND b.Red = 0) AS HisSelectQty,
							price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1,
							case when price1.Convfactor IS null then 1 else price1.Convfactor end  AS Convfactor1,
							price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, 
							case when price2.Convfactor IS null then 1 else price2.Convfactor end  AS Convfactor2,
							price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3, 
							case when price3.Convfactor IS null then 1 else price3.Convfactor end  AS Convfactor3      
							FROM ' + @DetailTable + ' detail
							LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
							LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID
							LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
							LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
							LEFT JOIN BD_Goods_Price price1 ON price1.GoodsID = detail.GoodsID
							LEFT JOIN BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID And price2.UnitID = 2
							LEFT JOIN BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID And price3.UnitID = 3
					  WHERE detail.BillNo = @BillNo AND price.UnitID = detail.UnitID
							AND price1.UnitID = 1
					   ORDER BY detail.DID'  --查询明细
						
	EXEC sp_executesql @SqlDetail, N'@BillNo INT', @BillNo	
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryAssemblyBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryAssemblyBillData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-01-20
	描述：查询生产拆装单数据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryAssemblyBillData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS

DECLARE @TableIndex NVARCHAR(100) = '', @TableDetail NVARCHAR(100) = '',@TableSerial NVarChar(100)=''
DECLARE @IndexSql NVARCHAR(MAX) = '', @OutDetailSql NVARCHAR(MAX) = '', @InDetailSql NVARCHAR(MAX) = '', @OutSerialSql NVARCHAR(MAX) = '', @InSerialSql NVARCHAR(MAX) = ''

IF EXISTS(SELECT 1 FROM PD_AssemblyBill_His WHERE BillNo = @BillNo)
BEGIN
	SET @TableIndex = ' PD_AssemblyBill_His '
	SET @TableDetail = ' PD_AssemblyDetail_His '
	SET @TableSerial = ' PD_AssemblySerial_His '
END ELSE
BEGIN
	SET @TableIndex = ' PD_AssemblyBill '
	SET @TableDetail = ' PD_AssemblyDetail '
	SET @TableSerial = ' PD_AssemblySerial '
END

--单据索引
SET @IndexSql = '
SELECT	  TOP 1
		  BillCode ,
		  BillDate ,
		  BillNo,
		  I.DeptID ,
		  D.DeptName,
		  I.ElyID ,
		  E.ElyName,
		  I.OutWhsID,
		  k1.WhsName AS OutWhsName,
		  I.InWhsID,
		  k2.WhsName AS InWhsName,
		  OutBillQty,
		  OutTotal,
		  InBillQty,
		  InTotal,
		  Summary ,
		  [Description] ,
		  Red ,
		  IsDraft,
		  AssemblyCalcCost,
		  AssemblyType,
		  I.Creator AS CreatorID,
		  e1.ElyName AS CreatorName,
		  e2.ElyName AS PosName,
		  I.AuditStatus
FROM '+ @TableIndex +' I
INNER JOIN BD_Employee E ON I.ElyID = E.ElyID
INNER JOIN BD_Dept D ON E.DeptId = D.DeptId
LEFT  JOIN BD_Employee e1 ON I.Creator=e1.ElyID
LEFT  JOIN BD_Employee e2 ON I.PosElyID=e2.ElyID
INNER JOIN BD_Whs k1 ON I.OutWhsID = k1.WhsID
INNER JOIN BD_Whs k2 ON I.InWhsID = k2.WhsID
WHERE BillNo= @BillNo '

--出库明细
SET @OutDetailSql = '
SELECT	BillNo ,
		I.DID,
        I.GoodsID ,
        G.GoodsNo,
		G.GoodsName,
		I.BarCode,
		G.Model,
		G.Spec,
        I.Ppt1ID,
		p1.Value AS Ppt1Name,
		I.Ppt2ID,
		p2.Value AS Ppt2Name,
        I.WhsID ,
        I.WhsPtID ,
        wp.WhsPtName,
        I.UnitID ,
		gp.Unit,
        I.Convfactor ,
        Qty ,
        BSQty ,
        CostPrice ,
        I.CostPrice * I.Convfactor AS Price ,
        GoodsCostTotal ,
        I.Remark ,
        I.GroupID,
        I.AssemblyCost,
        gp1.Convfactor Convfactor1,
		CASE WHEN gp2.Convfactor IS NULL THEN 1 ELSE gp2.Convfactor END Convfactor2,	
		CASE WHEN gp3.Convfactor IS NULL THEN 1 ELSE gp3.Convfactor END Convfactor3,	
		gp1.Unit Unit1,
		gp2.Unit Unit2,
		gp3.Unit Unit3,
		gp1.BarCode BarCode1,
		gp2.BarCode BarCode2,
		gp3.BarCode BarCode3,
		I.CostPrice,
		I.CostPrice as GoodsCostPrice,
		I.GoodsCostTotal,
		G.IsSerial,I.BatchNumber,I.ProductDate,I.EndDate,I.InPutPrice,G.CostMethod,I.IsSelectBatch	
FROM '+ @TableDetail +' I
INNER JOIN BD_Goods G ON I.GoodsID=G.GoodsID
LEFT JOIN BD_Goods_Ppt1 p1 ON I.Ppt1ID = p1.Ppt1ID 
LEFT JOIN BD_Goods_Ppt2 p2 ON I.Ppt2ID = p2.Ppt2ID
INNER JOIN BD_Whs_Position wp ON I.WhsPtID=wp.WhsPtID
INNER JOIN BD_Goods_Price gp ON I.GoodsID = gp.GoodsID AND I.UnitID = gp.UnitID
LEFT JOIN BD_Goods_Price gp1 ON I.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
LEFT JOIN BD_Goods_Price gp2 ON I.GoodsID=gp2.GoodsID AND gp2.UnitID=2
LEFT JOIN BD_Goods_Price gp3 ON I.GoodsID=gp3.GoodsID AND gp3.UnitID=3
WHERE BillNo=@BillNo AND DetailType = 2
'

--入库明细
SET @InDetailSql = '
SELECT	BillNo ,
		I.DID,
        I.GoodsID ,
        G.GoodsNo,
		G.GoodsName,
		I.BarCode,
		G.Model,
		G.Spec,
        I.Ppt1ID,
		p1.Value AS Ppt1Name,
		I.Ppt2ID,
		p2.Value AS Ppt2Name,
        I.WhsID ,
        I.WhsPtID ,
        wp.WhsPtName,
        I.UnitID ,
		gp.Unit,
        I.Convfactor ,
        Qty ,
        BSQty ,
        CostPrice ,
        Price ,
        GoodsCostTotal ,
        I.Remark ,
        I.GroupID,
        I.AssemblyCost,
        gp1.Convfactor Convfactor1,
		CASE WHEN gp2.Convfactor IS NULL THEN 1 ELSE gp2.Convfactor END Convfactor2,	
		CASE WHEN gp3.Convfactor IS NULL THEN 1 ELSE gp3.Convfactor END Convfactor3,	
		gp1.Unit Unit1,
		gp2.Unit Unit2,
		gp3.Unit Unit3,
		gp1.BarCode BarCode1,
		gp2.BarCode BarCode2,
		gp3.BarCode BarCode3,	
		G.IsSerial,I.BatchNumber,I.ProductDate,I.EndDate,I.InPutPrice,G.DateType,G.ValidDays,G.CostMethod		
FROM '+ @TableDetail +' I
INNER JOIN BD_Goods G ON I.GoodsID=G.GoodsID
LEFT JOIN BD_Goods_Ppt1 p1 ON I.Ppt1ID = p1.Ppt1ID 
LEFT JOIN BD_Goods_Ppt2 p2 ON I.Ppt2ID = p2.Ppt2ID
INNER JOIN BD_Whs_Position wp ON I.WhsPtID=wp.WhsPtID
INNER JOIN BD_Goods_Price gp ON I.GoodsID = gp.GoodsID AND I.UnitID = gp.UnitID
LEFT JOIN BD_Goods_Price gp1 ON I.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
LEFT JOIN BD_Goods_Price gp2 ON I.GoodsID=gp2.GoodsID AND gp2.UnitID=2
LEFT JOIN BD_Goods_Price gp3 ON I.GoodsID=gp3.GoodsID AND gp3.UnitID=3
WHERE BillNo=@BillNo AND DetailType = 1
'

 -- 查询单据明细SN
	Set @OutSerialSql = ' select Serial,BillDID,ps.Remark from '+@TableSerial+ ' ps Inner Join '+@TableDetail+' pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo AND DetailType = 2 '
	Set @InSerialSql = ' select Serial,BillDID,ps.Remark from '+@TableSerial+ ' ps Inner Join '+@TableDetail+' pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo AND DetailType = 1 '

exec sp_executesql @IndexSql , N'@BillNo INT', @BillNo
exec sp_executesql @OutDetailSql , N'@BillNo INT', @BillNo
exec sp_executesql @InDetailSql, N'@BillNo INT', @BillNo
exec sp_executesql @OutSerialSql, N'@BillNo INT', @BillNo
exec sp_executesql @InSerialSql, N'@BillNo INT', @BillNo
GO




/****** Object:  StoredProcedure [UP_PD_QueryBIDSum]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBIDSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBIDSum]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBIDSum]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：采购单据开票情况查询(明细)Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBIDSum]
(
	@BillNo BIGINT=0,				--单据编号
	@BillTypeID INT=101				--单据类型
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@Sql0 NVARCHAR(MAX)='',@Sql1 NVARCHAR(MAX)='',@Sql2 NVARCHAR(MAX)='',@TableName VARCHAR(20)='',@HisStr VARCHAR(20)='_His'
IF EXISTS (SELECT 1 FROM MF_PchInvoiceDetail dtl WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql1='
		SELECT dtl.PchBillNo,dtl.PchDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_PchInvoiceDetail dtl
		WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY PchBillNo,PchDID,BillType '
IF EXISTS (SELECT 1 FROM MF_PchInvoiceDetail_His dtl WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql2='
		SELECT dtl.PchBillNo,dtl.PchDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_PchInvoiceDetail_His dtl
		WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY PchBillNo,PchDID,BillType '
IF @Sql1<>'' AND @Sql2<>''
	SET @Sql0 = @Sql1 +'
		UNION ALL ' + @Sql2
ELSE IF @Sql1<>'' AND @Sql2='' SET @Sql0 = @Sql1
ELSE IF @Sql1='' AND @Sql2<>'' SET @Sql0 = @Sql2
IF @BillTypeID = 101
BEGIN
	SET @TableName = 'PD_PchDetail'
	IF EXISTS (SELECT 1 FROM PD_PchDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='SET NOCOUNT ON; 
SELECT SUM(ISNULL(pidtl.InvoiceTotal,0))[InvoiceTotal],SUM(ISNULL(dtl.TaxTotal,0))-SUM(ISNULL(pidtl.InvoiceTotal,0))[NoInvoiceTotal] 
FROM '+@TableName+@HisStr+' dtl 
LEFT JOIN ( '+@Sql0+'
) AS pidtl ON PchBillNo = dtl.BillNo AND pidtl.PchDID = dtl.DID AND BillType=@BillTypeID 
WHERE dtl.BillNo=@BillNo '
END
ELSE
BEGIN
	SET @TableName = 'PD_PchRetDetail'
	IF EXISTS (SELECT 1 FROM PD_PchRetDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='SET NOCOUNT ON; 
SELECT SUM(ISNULL(pidtl.InvoiceTotal,0))[InvoiceTotal],SUM(ISNULL(dtl.TaxTotal,0))*-1-SUM(ISNULL(pidtl.InvoiceTotal,0))[NoInvoiceTotal] 
FROM '+@TableName+@HisStr+' dtl 
LEFT JOIN ( '+@Sql0+'
) AS pidtl ON PchBillNo = dtl.BillNo AND pidtl.PchDID = dtl.DID AND BillType=@BillTypeID 
WHERE dtl.BillNo=@BillNo '
END

--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillNo BIGINT,@BillTypeID INT',@BillNo,@BillTypeID

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：单据往来对账查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBillWLDZ]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BTypeID Int=0,
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@ShowDZ INT=0,
	@RedFlag Int = 0,
	@isHistory INT=0				--是否包含历史数据
	
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;

DECLARE @sql nvarchar(MAX)='',@SqlSell VARCHAR(max)='',@SqlSellLogist VARCHAR(max)='',@sqlHis nvarchar(MAX)='',@SqlSellHis VARCHAR(max)='',@SqlSellLogistHis VARCHAR(max)=''
		,@RowCount int=0,@SqlTable VARCHAR(max)='',@SqlGoods nvarchar(max),@SqlRed varchar(100)='',@RedStr varchar(100)='',@RedStr1 varchar(100)='',
		@SqlCreateTable varchar(max)='',@SqlBaseTable varchar(max)='',@SqlBuy varchar(Max)='',@SqlBuyLogist varchar(Max)='',@SqlBuyHis varchar(Max)='',@SqlBuyLogistHis varchar(Max)=''
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlBaseTable+=' INNER JOIN @DType D ON I.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlBaseTable+=' INNER JOIN @EType E ON I.ElyID=E.TypeID ' 
END	
if(@RedFlag = 0) 
	Select @SqlRed = ' And Red = 0 '
else
Begin
	Select @RedStr = ',Red '
	Select @RedStr1 = ',A.Red '
End
Select @RowCount = (@PageNo-1) * @PageSize	

	
SELECT @sql+='
UNION ALL 
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
		'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime,Summary,Description ,I.BillNo' + @RedStr
		+case When BillTypeID IN (101,102,201,202) then ',I.WhsID ' Else ' ,'''' as WhsID ' END
	+' FROM '+BillTable+' I ' + @SqlBaseTable 
	+' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
FROM PD_BillType b
WHERE CanPost=1 And BillTypeID in (102,401,402,404,405,501,502,503,504)

select @SqlBuy += 'UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
			'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.Freight' + @RedStr
			+',I.WhsID FROM '+BillTable+' I ' + @SqlBaseTable 
		+' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	FROM PD_BillType b
	WHERE CanPost=1 And BillTypeID = 101
select @SqlBuyLogist += '
SELECT  101 AS BillTypeID,
		'''+'采购入库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID,I.Freight,I.DeptID,I.ElyID '+@RedStr 
		+ ' FROM PD_PchBill I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID  ' 

SELECT @sqlSell+='
UNION ALL 
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
		'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo' + @RedStr
		+case When BillTypeID IN (101,102,201,202) then ',I.WhsID ' Else ' ,'''' as WhsID ' END
	+' FROM '+BillTable+' I ' + @SqlBaseTable 
	+' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
FROM PD_BillType b
WHERE CanPost=1 And BillTypeID in (201,202)
Select @SqlSellLogist += '
SELECT  201 AS BillTypeID,
		'''+'销售出库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID '+@RedStr 
		+ ' FROM PD_SellBill I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID  ' 
		
IF @isHistory=1
Begin
	SELECT @sqlHis+='
UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
			'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime,Summary,Description ,I.BillNo' + @RedStr
			+case When BillTypeID IN (101,102,201,202) then ',I.WhsID ' Else ' ,'''' as WhsID ' END
		+' FROM '+BillTable+'_His I ' + @SqlBaseTable 
		+' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID '
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	FROM PD_BillType b
	WHERE CanPost=1 And BillTypeID in (102,401,402,404,405,501,502,503,504)

select @SqlBuyHis += 'UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
			'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.Freight' + @RedStr
			+',I.WhsID FROM '+BillTable+'_His I ' + @SqlBaseTable 
		+' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	FROM PD_BillType b
	WHERE CanPost=1 And BillTypeID = 101
select @SqlBuyLogistHis += '
SELECT  101 AS BillTypeID,
		'''+'采购入库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID,I.Freight,I.DeptID,I.ElyID '+@RedStr 
		+ ' FROM PD_PchBill_His I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID  ' 


	SELECT @SqlSellHis+='
UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
			'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo' + @RedStr
			+case When BillTypeID IN (101,102,201,202) then ',I.WhsID ' Else ' ,'''' as WhsID ' END
		+' FROM '+BillTable+'_His I ' + @SqlBaseTable 
		+' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	FROM PD_BillType b
	WHERE CanPost=1 And BillTypeID in (201,202)
	Select @SqlSellLogistHis += '
	SELECT  201 AS BillTypeID,
			'''+'销售出库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID '+@RedStr 
			+ ' FROM PD_SellBill_His I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID ' 
End

SELECT @sql=@SqlCreateTable+@SqlTable + '
;WITH Bill AS 
('	+STUFF(@sql,1,12,'')+'
),BuyBill as
(' +STUFF(@SqlBuy,1,12,'')+
'),BuyLogistBill as
(' + @SqlBuyLogist +
'),SellBill as
(' +STUFF(@sqlSell,1,12,'')+
'),SellLogistBill as
(' + @SqlSellLogist +
')'
IF @isHistory=1
Begin
	select @sql+=',BillHis AS 
	('	+STUFF(@sqlHis,1,12,'')+'
	),BuyBillHis as
	(' +STUFF(@SqlBuyHis,1,12,'')+
	'),BuyLogistBillHis as
	(' + @SqlBuyLogistHis +
	'),SellBillHis as
	(' +STUFF(@SqlSellHis,1,12,'')+
	'),SellLogistBillHis as
	(' + @SqlSellLogistHis +
	')'
End
select @sql+=',AllData as
( Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal,L.JTotal,L.BillDate,L.[Order] '+@RedStr1+'
	from Bill A Left Join PD_ListTable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo
	where FinanceID not in(33,37,20)
	Union ALL
  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,case when FinanceID = 35 then (L.JTotal-' + case when @RedFlag=0 then 'A.Freight' else '(case when A.Red = 2 then A.Freight*-1 else A.Freight end )' end + ') else L.JTotal end as JTotal,L.BillDate,L.[Order]'+@RedStr1+'
	from BuyBill A Left Join PD_ListTable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,20)
	Union ALL
  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,L.JTotal,L.BillDate,L.[Order]'+@RedStr1+'
	from BuyLogistBill A Left Join PD_ListTable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID 
	where FinanceID not in(37,33)
	Union ALL
  Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,A.DeptID,A.ElyID,WhsID,30 as FinanceID,0 as DTotal ,' + Case when @RedFlag=0 then 'A.Freight' Else 'Case When A.Red = 2 then A.Freight*-1 else A.Freight End ' end + ' as JTotal,A.BillDate,20 as [Order]'+@RedStr1+'
	from BuyLogistBill A 
	Union ALL
  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,L.JTotal,L.BillDate,L.[Order]'+@RedStr1+'
	from sellbill A Left Join PD_ListTable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,11,35)
	Union ALL
  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,L.JTotal,L.BillDate,L.[Order]'+@RedStr1+'
	from SellLogistBill A Left Join PD_ListTable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID 
	where FinanceID not in(37,33) '
	IF @isHistory=1
	Begin	
		select @sql+= 'Union all
	  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal,L.JTotal,L.BillDate,L.[Order] '+@RedStr1+'
		from BillHis A Left Join PD_ListTable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo
		where FinanceID not in(33,37,20)
		Union ALL
	  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,case when FinanceID = 35 then (L.JTotal-L.JTotal-' + case when @RedFlag=0 then 'A.Freight' else '(case when A.Red = 2 then A.Freight*-1 else A.Freight end )' end + ') else L.JTotal end as JTotal,L.BillDate,L.[Order]'+@RedStr1+'
		from BuyBillHis A Left Join PD_ListTable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
		where FinanceID not in(33,37,20)
		Union ALL
	  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,L.JTotal,L.BillDate,L.[Order]'+@RedStr1+'
		from BuyLogistBillHis A Left Join PD_ListTable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID 
		where FinanceID not in(37,33)
		Union ALL
	  Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,A.DeptID,A.ElyID,WhsID,30 as FinanceID,0 as DTotal ,' + Case when @RedFlag=0 then 'A.Freight' Else 'Case When A.Red = 2 then A.Freight*-1 else A.Freight End ' end + ' as JTotal,A.BillDate,20 as [Order]'+@RedStr1+'
		from BuyLogistBillHis A 
		Union ALL
	  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,L.JTotal,L.BillDate,L.[Order]'+@RedStr1+'
		from sellbillHis A Left Join PD_ListTable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
		where FinanceID not in(33,37,11,35)
		Union ALL
	  Select A.BillTypeID,L.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,L.FinanceID,L.DTotal ,L.JTotal,L.BillDate,L.[Order]'+@RedStr1+'
		from SellLogistBillHis A Left Join PD_ListTable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID 
		where FinanceID not in(37,33) '
	End
select @sql+='),page as
(
	select row_number() over (order by Createtime,Postime,[Order]) as rowNum,* from AllData
),BackTotal as
(
	select BillNo,BillTypeID,35 as FinanceID,DTotal ,Jtotal from pd_listtable where FinanceID = 20 
	Union All
	select BillNo,BillTypeID,35 as FinanceID,DTotal ,Jtotal from pd_listtable_His where FinanceID = 20 
),pageTotal as
(
	Select isNUll(sum(IsNull(A.DTotal,0)+isnull(G.DTotal,0))-sum(isnull(A.JTotal,0)+isnull(G.jtotal,0)),0) as beforTotal from  page A left join BackTotal G on A.FinanceID=G.FinanceID and A.BillNo = G.BillNo and A.BillTypeID = G.BillTypeID where rowNum <= @RowCount
),
pageData as 
(
	SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM AllData) A
	CROSS JOIN
	(
	Select rowNum,A.BillTypeID,A.BillNO,BillName,BillCode,Createtime,Postime,BillDate,Summary,Description ,A.BtypeID,A.DeptID,A.ElyID,A.WhsID,A.FinanceID,A.DTotal+isnull(G.DTotal,0) as DTotal,A.JTotal+isnull(G.jtotal,0) as JTotal
		,b.BTypeCode,b.BTypeName,d.DeptCode,d.DeptName,e.ElyCode,e.ElyName,w.WhsNO,W.WhsName,A.[Order],Case When A.BillTypeID in (102,202) and F.FinanceNO = 1243 then '''' Else F.FinanceNO End as FinanceNO,Case When A.BillTypeID in (102,202) and F.FinanceNO = 1243 then ''' + '退货金额' +''' Else f.FinanceName end as FinanceName ' + @RedStr1+'
	from  page A Left Join BD_Btype B on A.BTypeID=b.BTypeID
			Left Join BD_Dept D on A.DeptID=D.DeptID
			Left Join BD_Employee E on A.ElyID=E.ElyID
			Left Join BD_Whs W on A.WhsID=W.WhsID
			Left Join BD_Finance F on A.FinanceID=F.FinanceID
			left join BackTotal G on A.FinanceID=G.FinanceID and A.BillNo = G.BillNo and A.BillTypeID = G.BillTypeID
	where rowNum > @RowCount And rowNum <= @RowCount + @PageSize --And F.FinanceID <> 20
	) B
)
select * from pageData,pageTotal  order by rowNum
'
--select @total as total
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

------------------添加参数---------------------------------------

--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
exec sp_executesql @sql,N'@PageNo Int,@PageSize Int,@BeginDate Date,@EndDate Date,@BTypeID VarChar(MAX),@DeptID VarChar(MAX),@ElyID VarChar(MAX),@RowCount Int',@PageNo,@PageSize,@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID,@RowCount

GO



/****** Object:  StoredProcedure [UP_PD_QueryBISum]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBISum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBISum]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBISum]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：采购单据开票情况查询Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBISum]
(
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@BTypeID VARCHAR(1000)='',		--往来单位
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@BillCode VARCHAR(50)='',		--单据编号
	@BillType INT=9,				--单据类型
	@InvoiceState INT=9,			--开票状态 9=全部,2=已开票,0=未开票,1=部分开票
	@GoodsNoMatch INT = 0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',		--商品编号
	@GoodsNameMatch INT = 0,		--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',	--商品名称
	@SummaryMatch INT = 0,			--摘要配置模式:0=包含,1=等于
	@Summary VARCHAR(100) = '',		--摘要
	@DescriptionMatch INT = 0,		--说明配置模式:0=包含,1=等于
	@Description VARCHAR(100) = '',	--说明
	@PriceStart decimal(20,8),      --单价范围开始
	@PriceEnd  decimal(20,8),       --单价范围结束
	@TotalStart decimal(20,8),      --金额范围开始
	@TotalEnd  decimal(20,8),       --金额范围结束
	@IsShowRed INT=0,				--是否包含红冲数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql_PB VARCHAR(460)='',@Sql_PB_His VARCHAR(460)='',@Sql_PRB VARCHAR(460)='',@Sql_PRB_His VARCHAR(460)=''
		,@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@BtypeLimit INT=0 ,@SqlDetailParam NVARCHAR(MAX)='',@SqlDetailJoin NVARCHAR(MAX)=''
		,@SqlDetailPB NVARCHAR(MAX)='',@SqlDetailPRB NVARCHAR(MAX)='',@SqlDetailPB_His NVARCHAR(MAX)='',@SqlDetailPRB_His NVARCHAR(MAX)=''

IF @BTypeID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BTypeID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
		INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
IF @DeptID <> ''
	SET @SqlJoin +='
		INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '

SET @SqlParam = '
		WHERE b.IsDraft=0 '
IF @IsShowRed = 0
	SET @SqlParam += '
		AND b.Red=0 '
IF @BillCode <> ''
	SET @SqlParam +='
		AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
		AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
-- 摘要
IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 0
		SET @SqlParam += 'AND b.Summary Like ''%''+@Summary+''%'' '  
	IF @SummaryMatch = 1
		SET @SqlParam += 'AND b.Summary = @Summary '  
END
-- 说明
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 0
		SET @SqlParam += 'AND b.Description Like ''%''+@Description+''%'' '  
	IF @DescriptionMatch = 1
		SET @SqlParam += 'AND b.Description = @Description '  
END
IF @GoodsName <> '' OR @GoodsNo <> ''
BEGIN
	SET @SqlDetailJoin += ' INNER JOIN BD_Goods _goods ON _goods.GoodsID = dtl.GoodsID '
END
-- 商品名称
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsNo Like ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsNo = @GoodsNo '  
END
-- 商品名称
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsName Like ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsName = @GoodsName '  
END
-- 商品单价从--到
IF @PriceEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Price BETWEEN @PriceStart AND @PriceEnd '
END
-- 商品金额从--到
IF @TotalEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Total BETWEEN @TotalStart AND @TotalEnd '
END
IF @GoodsName <> '' OR @GoodsNo <> '' OR @PriceEnd <> 0 OR @TotalEnd <> 0
BEGIN
	SET @SqlDetailPB += '  AND EXISTS (SELECT 1 FROM PD_PchDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailPRB += '  AND EXISTS (SELECT 1 FROM PD_PchRetDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailPB_His += '  AND EXISTS (SELECT 1 FROM PD_PchDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailPRB_His += '  AND EXISTS (SELECT 1 FROM PD_PchRetDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
END
IF @InvoiceState <> 9
BEGIN
	IF @InvoiceState = 2
		SET @SqlParam +='
	AND ABS(b.InvoiceTotal)>=b.Total '
	IF @InvoiceState = 0
		SET @SqlParam +='
	AND b.InvoiceTotal=0 '
	IF @InvoiceState = 1
		SET @SqlParam +='
	AND b.InvoiceTotal<>0 AND ABS(b.InvoiceTotal)<b.Total '
END
SET @SqlParam +=' AND IsInvoice = 1 '  --只查询是否开票为是的单据
SET @Sql_PB += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_PchBill b '
SET @Sql_PRB += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_PchRetBill b '
SET @Sql_PB_His += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_PchBill_His b '
SET @Sql_PRB_His += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_PchRetBill_His b '
IF @IsHistory = 1
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_PB + @SqlJoin + @SqlParam + @SqlDetailPB + '
	UNION ALL ' + @Sql_PB_His + @SqlJoin + @SqlParam + @SqlDetailPB_His
	ELSE IF @BillType = 2
		SET @Sql = @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB + '
	UNION ALL ' + @Sql_PRB_His + @SqlJoin + @SqlParam + @SqlDetailPRB_His
	ELSE
		SET @Sql = @Sql_PB + @SqlJoin + @SqlParam + @SqlDetailPB + '
	UNION ALL ' + @Sql_PB_His + @SqlJoin + @SqlParam + @SqlDetailPB_His + '
	UNION ALL ' + @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB + '
	UNION ALL ' + @Sql_PRB_His + @SqlJoin + @SqlParam + @SqlDetailPRB_His
END
ELSE
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_PB + @SqlJoin + @SqlParam + @SqlDetailPB
	ELSE IF @BillType = 2
		SET @Sql = @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB
	ELSE
		SET @Sql = @Sql_PB  + @SqlJoin + @SqlParam + @SqlDetailPB + '
	UNION ALL ' + @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB
END

SET @Sql = 'SET NOCOUNT ON; 
;WITH BillData AS( ' + @Sql + '
)'
SET @Sql += 'SELECT ISNULL(SUM(Total),0)[Total],ISNULL(SUM(InvoiceTotal),0)[InvoiceTotal],ISNULL(SUM(NoInvoiceTotal),0)[NoInvoiceTotal] FROM BillData '

IF @BtypeLimit = 0 
	SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
	
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END

EXEC SP_EXECUTESQL @Sql,N'@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@BillCode VARCHAR(50),@BillType INT=9,@OperatorID INT,
						  @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),@SummaryMatch INT, @Summary VARCHAR(100), @DescriptionMatch INT, @Description VARCHAR(100),
						  @PriceStart DECIMAL(20,8),@PriceEnd DECIMAL(20,8), @TotalStart DECIMAL(20,8), @TotalEnd DECIMAL(20,8)',
						  @BillStartDate,@BillEndDate,@BTypeID,@DeptID,@ElyID,@BillCode,@BillType,@OperatorID,
						  @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName, @SummaryMatch, @Summary, @DescriptionMatch, @Description,
						  @PriceStart, @PriceEnd, @TotalStart, @TotalEnd

END

GO






/****** Object:  StoredProcedure [UP_PD_QueryBODTLSum]    Script Date: 06/28/2014 10:25:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBODTLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBODTLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBODTLSum]    Script Date: 06/28/2014 10:25:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-06-28
	描述：销售订单管理(明细)Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBODTLSum]
(
	@BillNo BIGINT=0,
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@StopTag INT=9,					--中止状态
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@SqlParam NVARCHAR(MAX)
		,@HisStr VARCHAR(20)='_His'
IF EXISTS (SELECT 1 FROM PD_PchOrdBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''
SET @Sql='SELECT ISNULL(SUM(dtl.TaxTotal),0)[Total],ISNULL(SUM(dtl.ComTotal),0)[DHTotal] 
	FROM PD_PchOrdDetail'+@HisStr+' dtl '
/*权限使用公用方法*/
IF( dbo.UF_BD_IsAllKtypeLimit(@OperatorID)=0 )
	SET @Sql += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=dtl.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @Sql +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=dtl.WhsID '
	END
END
*/
IF @GoodsID <> ''
	SET @Sql +='INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID ' 
IF @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
BEGIN
	SET @Sql += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
END	

--IF @BarCode <> ''
--BEGIN 
--	SET @Sql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID  and pri.UnitID = dtl.UnitID  '
--END
SET @Sql +='WHERE dtl.BillNo=@BillNo '
IF @StopTag <> 9
	SET @Sql +='AND dtl.StopTag=@StopTag '
--商品型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @Sql += N' AND goods.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @Sql += N' AND goods.Model = @Model ' 
END   
--商品简名    
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @Sql += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @Sql += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
END       
--商品品牌
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @Sql += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @Sql += N' AND goods.Brand = @Brand ' 
END
--商品规格    
IF @Spec <> ''        
BEGIN 
   IF @SpecMatch = 0
	   SET @Sql += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @Sql += N' AND goods.Spec = @Spec '  
END
--商品条码
IF @BarCode <> ''      
BEGIN 
   SET @Sql += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = dtl.GoodsID '
   IF @BarCodeMatch = 0
	   SET @Sql += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @Sql += N' AND pri.BarCode = @BarCode ' 
   SET @Sql += ' ) '
END
--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillNo BIGINT,@GoodsID VARCHAR(1000),@StopTag INT,@OperatorID INT, @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',@BillNo,@GoodsID,@StopTag,@OperatorID, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch

GO






/****** Object:  StoredProcedure [UP_PD_QueryBOLSum]    Script Date: 07/03/2014 10:25:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBOLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBOLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBOLSum]    Script Date: 07/03/2014 10:25:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-03
	描述：采购订单管理Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBOLSum]
(
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@DlvStartDate VARCHAR(50)='',	--交货日期查询开始时间
	@DlvEndDate VARCHAR(50)='',		--交货日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@BTypeID VARCHAR(1000) = '',	--往来单位
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@WhsID VARCHAR(1000) = '',		--仓库
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@Stt VARCHAR(50)='',			--订单状态
	@IsDraft INT=9,                 --生效状态
	@StopTag INT=9,					--中止状态
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@BtypeAddr VARCHAR(max)='',		--往来单位地址
	@BtypePhone VARCHAR(max)=''		--往来单位编号
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql1 NVARCHAR(MAX)='',@Sql2 NVARCHAR(MAX)='',@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)=''
		,@Sql1_His NVARCHAR(MAX)='',@Sql2_His NVARCHAR(MAX)='',@BtypeLimit INT=0,@KtypeLimit INT=0 

SET @Sql1='SELECT b.BillNo,CASE WHEN b.StopTag=1 THEN 2 
			WHEN NOT EXISTS(SELECT 1 FROM PD_PchOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty<BSQty) THEN 2 
			WHEN EXISTS(SELECT 1 FROM PD_PchOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty>0) THEN 1
			ELSE 0 END AS Stt 
			FROM PD_PchOrdBill b '
			
IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql1 = @Sql1 + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '	
			
SET @Sql1_His='UNION ALL 
			SELECT b.BillNo,2[Stt] 
			FROM PD_PchOrdBill_His b '
			
IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql1_His = @Sql1_His + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '	
			
SET @Sql2='SELECT b.BillNo,b.Total,p.ComTotal[DHTotal] 
			FROM PD_PchOrdBill b 
			INNER JOIN PD_PchOrdDetail p ON p.BillNo=b.BillNo '
			
IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql2 = @Sql2 + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '	
			
SET @Sql2_His='UNION ALL 
			SELECT b.BillNo,b.Total,p.ComTotal[DHTotal] 
			FROM PD_PchOrdBill_His b 
			INNER JOIN PD_PchOrdDetail_His p ON p.BillNo=b.BillNo '
			
IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql2_His = @Sql2_His + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '	

IF @BTypeID <> ''
   SET @SqlJoin +='INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BtypeID '
IF @DeptID <> ''
   SET @SqlJoin +='INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
   SET @SqlJoin +='INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @WhsID <> ''
   SET @SqlJoin +='INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = b.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
		INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SqlJoin += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=b.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=b.BTypeID '
	END
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=b.WhsID '
	END
END
*/
SET @SqlParam = 'WHERE 1=1 '
IF @BillCode <> ''
	SET @SqlParam +='AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @DlvStartDate <> ''
	SET @SqlParam +='AND b.DlvDate BETWEEN @DlvStartDate AND @DlvEndDate '
IF @Description <> ''
	SET @SqlParam +='AND b.Description Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='AND b.Summary Like ''%''+@Summary+''%'' '
IF @StopTag <> 9
	SET @SqlParam +='AND b.StopTag=@StopTag '
-- 生效状态
IF @IsDraft <> 9
BEGIN
	SET @SqlParam +='AND b.IsDraft=@IsDraft '
	--SET @SqlSumParam ='WHERE p.IsDraft=@IsDraft '
END	
--IF @GoodsID <> ''
--BEGIN
--	SET @SqlParam_His = @SqlParam + 'AND EXISTS (SELECT 1 FROM PD_PchOrdDetail_His dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--	SET @SqlParam +='AND EXISTS (SELECT 1 FROM PD_PchOrdDetail dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--END
DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
--商品型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @ClauseParam += N' AND goods.Model = @Model ' 
END     
--商品简名  
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @ClauseParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
   END    
--商品品牌   
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
END    
IF @Spec <> ''       --商品规格 
BEGIN 
   IF @SpecMatch = 0
	   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @ClauseParam += N' AND goods.Spec = @Spec '  
END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
IF @BarCode <> ''      --商品条码
BEGIN 
   IF @BarCodeMatch = 0
	   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID '
END    

IF @GoodsID <> '' OR @ClauseParam <> ''
BEGIN
	IF @GoodsID <> ''
		SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
	SET @SqlParam_His = @SqlParam + '
		AND EXISTS (SELECT 1 FROM PD_AllotReqDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
	SET @SqlParam += '
		AND EXISTS (SELECT 1 FROM PD_AllotReqDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
END
ELSE
	SET @SqlParam_His = @SqlParam
	
IF @IsHistory = 0 
	IF @Stt <> '' AND @Stt <> '0,1,2'
		SET @Sql += ';WITH SttData AS ( '+@Sql1 + @SqlJoin + @SqlParam + ') ,dData AS ('+ @Sql2 + 'INNER JOIN SttData sd ON sd.BillNo=b.BillNo INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt ) '
	ELSE
		SET @Sql += ';WITH dData AS ( '+@Sql2 + @SqlJoin + @SqlParam + ') '
ELSE
	IF @Stt <> '' AND @Stt <> '0,1,2'
		SET @Sql += ';WITH SttData AS ( '+@Sql1 + @SqlJoin + @SqlParam + @Sql1_His + @SqlJoin + @SqlParam_His 
					+ ') ,dData AS ('+ @Sql2 + 'INNER JOIN SttData sd ON sd.BillNo=b.BillNo INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt '
									+ @Sql2_His + 'INNER JOIN SttData sd ON sd.BillNo=b.BillNo INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt ) '
	ELSE
		SET @Sql += ';WITH dData AS ( '+@Sql2 + @SqlJoin + @SqlParam + @Sql2_His + @SqlJoin + @SqlParam_His + ') '
		
SET @Sql += ',Data AS (
	SELECT BillNo,SUM(Total)/COUNT(BillNo)[Total],SUM(DHTotal)[DHTotal] FROM dData 
	GROUP BY BillNo ) '

SET @Sql += 'SELECT ISNULL(SUM(Total),0)[Total],ISNULL(SUM(DHTotal),0)[DHTotal] FROM Data '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT 0[Total],0[DHTotal] '
--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@DlvStartDate VARCHAR(50),@DlvEndDate VARCHAR(50),@BillCode VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@Stt VARCHAR(50),@IsDraft INT,@StopTag INT,@OperatorID INT, @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',@BillStartDate,@BillEndDate,@DlvStartDate,@DlvEndDate,@BillCode,@BTypeID,@DeptID,@ElyID,@WhsID,@GoodsID,@Description,@Summary,@Stt,@IsDraft,@StopTag,@OperatorID, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch

END

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryBuyBackBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryBuyBackBillData
GO
/****** Object:  StoredProcedure [UP_PD_QueryBuyBackBillData]    Script Date: 06/16/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2014-06-17
	描述：查询采购退货单数据
	update sunzhiyuan 增加多账户查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyBackBillData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS

DECLARE @TableIndex NVARCHAR(100) = '', @TableDetail NVARCHAR(100) = '',@TableSerial NVARCHAR(100) = ''
DECLARE @IndexSql NVARCHAR(MAX) = '', @DetailSql NVARCHAR(MAX) = '',@SerialSql NVARCHAR(MAX) = ''


IF EXISTS(SELECT 1 FROM PD_PchRetBill_His WHERE BillNo = @BillNo)	
BEGIN
	SET @TableIndex = 'PD_PchRetBill_His'
	SET @TableDetail = 'PD_PchRetDetail_His'
	SET @TableSerial = 'PD_PchRetSerial_His'
END ELSE
BEGIN
	SET @TableIndex = 'PD_PchRetBill'
	SET @TableDetail = 'PD_PchRetDetail'
	SET @TableSerial = 'PD_PchRetSerial'
END

SET @IndexSql ='
	DECLARE @IsAccounts INT = 0
	IF EXISTS(SELECT 1 FROM PD_MulAccounts WHERE BillTypeID = 102 AND BillNo = @BillNo)
		SELECT @IsAccounts = 1

	SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			101 AS BillType,
			p.BTypeID,
			b.BTypeName,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.WhsID,
			w.WhsName,
			Summary,
			Description,
			BillQty,
			BTDTotal,
			PaidTotal,
			Total,
			Privilege,
			(Total - Privilege) AS AfterPrivilege,
			CASE @IsAccounts WHEN 0 THEN p.FinanceID ELSE -100 end as FinanceID,
			CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '''+'【多账户】'+''' end as FinanceName,
			PayRecTotal,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			IsDraft,
			AuditStatus,
			Red,@IsAccounts as IsAccounts,
			p.IsInvoice,
			p.BeforeAPTotal,
			ISNULL(P.BeforeAPTotal,0)+(ISNULL(P.total,0)-ISNULL(P.Privilege,0)-ISNULL(P.PayRecTotal,0)) AS CurAPTotal

	FROM '+ @TableIndex +' p
	INNER JOIN BD_Btype b ON p.BtypeID = b.BTypeID
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs w ON w.WhsID=p.WhsID
	LEFT JOIN BD_Finance f ON p.FinanceID=f.FinanceID
	WHERE BillNo=@BillNo
'	
SET @DetailSql = '
	SELECT  p.DID,
			p.GoodsID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			g.Spec,
			p.WhsPtID,
			p.WhsID,
			wp.WhsPtName,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			Price,
			Qty,
			BSQty,
			Total,
			Discount,
			DiscPrice,
			DiscTotal,
			Tax,
			TaxRate,
			TaxPrice,
			TaxTotal,
			cast(p.Gift AS BIT) Gift,
			p.Remark,
			P.CostPrice,
			P.CostPrice as GoodsCostPrice,
			P.GoodsCostTotal,
			p.BatchNumber,p.ProductDate,p.EndDate,p.PchDID,op.BillCode,p.InPutPrice,g.DateType,g.CostMethod,
			p.PriceID,
			gp1.Convfactor Convfactor1,
			CASE WHEN gp2.Convfactor IS NULL THEN 1 ELSE gp2.Convfactor END Convfactor2,	
			CASE WHEN gp3.Convfactor IS NULL THEN 1 ELSE gp3.Convfactor END Convfactor3,	
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3,
			gp1.BarCode BarCode1,
			gp2.BarCode BarCode2,
			gp3.BarCode BarCode3,
			g.IsSerial,p.IsSelectBatch	,
			p.goodsno AS BtypeGoodsNo,
			g.Brand,
			g.KG		
	FROM '+ @TableDetail +' p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID
	LEFT JOIN 
			(
				SELECT BillCode,DID 
				FROM PD_PchDetail D
				INNER JOIN PD_PchBill b ON d.BillNo = b.BillNo
				UNION ALL
				SELECT BillCode,DID 
				FROM PD_PchDetail_His D
				INNER JOIN PD_PchBill_His b ON d.BillNo = b.BillNo
			) op ON op.DID= p.PCHDID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 102 and BillNo = @BillNo
 '

Select @SerialSql=' select Serial,BillDID,ps.Remark from '+@TableSerial+' ps Inner Join ' +@TableDetail+ ' pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo '
	
exec sp_executesql @IndexSql , N'@BillNo INT', @BillNo
exec sp_executesql @DetailSql , N'@BillNo INT', @BillNo
exec sp_executesql @SerialSql , N'@BillNo INT', @BillNo
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryBuyBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryBuyBillData
GO
/****** Object:  StoredProcedure [UP_PD_QueryBuyBillData]    Script Date: 06/16/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		hanlin
-- Create date:  2014/6/16
-- Description:	 查询采购入库单数据
-- update sunzhiyuan 多账户查询
-- update sunzhiyuan 增加AuditStatus字段检索（审核状态）
-- =============================================
CREATE PROCEDURE [UP_PD_QueryBuyBillData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS
BEGIN
	DECLARE @IsAccounts INT = 0
	IF EXISTS(SELECT 1 FROM PD_MulAccounts WHERE BillTypeID = 101 AND BillNo = @BillNo)
		SELECT @IsAccounts = 1
	
	IF EXISTS(SELECT 1 FROM PD_PchBill WHERE BillNo=@billNO)
	BEGIN
	SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			101 AS BillType,
			p.BTypeID,
			b.BTypeName,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.WhsID,
			w.WhsName,
			Summary,
			Description,
			BillQty,
			BTDTotal,
			PaidTotal,
			Total,
			Privilege,
			CASE @IsAccounts WHEN 0 THEN p.FinanceID ELSE -100 end as FinanceID,
			CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '【多账户】' end as FinanceName,
			--p.FinanceID,
			--f.FinanceName,
			PayRecTotal,
			Total - Privilege AS AfterPrivilege,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			Red,
			IsDraft,
			FreightFinanceID,
			f2.FinanceName AS FreightFinanceName,
			Freight,
			FreightTotal,
			LogistBtypeID,
			b2.BTypeName AS LogistBtypeName,@IsAccounts as IsAccounts,
			p.AuditStatus,
			p.IsInvoice,
			P.BeforeAPTotal,
			ISNULL(P.BeforeAPTotal,0)+(ISNULL(P.total,0)-ISNULL(P.Privilege,0)-ISNULL(P.PayRecTotal,0)) AS CurAPTotal
	FROM PD_PchBill p
	INNER JOIN BD_Btype b ON p.BtypeID = b.BTypeID
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs w ON w.WhsID=p.WhsID
	LEFT JOIN BD_Finance f ON p.FinanceID=f.FinanceID
	LEFT JOIN BD_Finance f2 ON p.FreightFinanceID=f2.FinanceID
	LEFT JOIN BD_Btype b2 ON p.LogistBtypeID = b2.BTypeID
	WHERE BillNo=@BillNo
		
	SELECT  p.DID,
			p.GoodsID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			p.OrdDID,
			g.Spec,
			p.WhsPtID,
			p.WhsID,
			wp.WhsPtName,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			Price,
			Qty,
			BSQty,
			Total,
			Discount,
			DiscPrice,
			DiscTotal,
			Tax,
			TaxRate,
			TaxPrice,
			TaxTotal,
			CAST(Gift AS BIT) AS Gift ,
			p.Remark,
			p.BatchNumber,p.ProductDate,p.EndDate,p.InPutPrice,g.DateType,g.ValidDays,g.CostMethod,
			p.Freight,
			p.InPrice,
			p.InTotal,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,	
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3,
			op.BillCode	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			p.PriceID,
			p.VerifyQty	,
			CASE WHEN p.Qty=p.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
			g.IsSerial	,
			p.goodsno AS BtypeGoodsNo,
			g.Brand,
			g.KG	
	FROM PD_PchDetail p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN 
	(
		SELECT BillCode,DID
		FROM PD_PchOrdDetail D
		INNER JOIN PD_PchOrdBill b ON d.BillNo = b.BillNo
		UNION ALL
		SELECT BillCode,DID
		FROM PD_PchOrdDetail_His D
		INNER JOIN PD_PchOrdBill_His b ON d.BillNo = b.BillNo
	) op ON op.DID= p.OrdDID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	-- 查询多账户信息
	SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 101 and BillNo = @BillNo
	
	-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_PchSerial ps Inner Join PD_PchDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
	
	-- 历史数据
	ELSE
	BEGIN
	SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			101 AS BillType,
			p.BTypeID,
			b.BTypeName,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.WhsID,
			w.WhsName,
			Summary,
			Description,
			BillQty,
			BTDTotal,
			PaidTotal,
			Total,
			Privilege,
			CASE @IsAccounts WHEN 0 THEN p.FinanceID ELSE -100 end as FinanceID,
			CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '【多账户】' end as FinanceName,
			--p.FinanceID,
			--f.FinanceName,
			PayRecTotal,
			Total - Privilege AS AfterPrivilege,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			Red,
			IsDraft,
			FreightFinanceID,
			f2.FinanceName AS FreightFinanceName,
			Freight,
			FreightTotal,
			LogistBtypeID,
			b2.BTypeName AS LogistBtypeName,@IsAccounts as IsAccounts,
			p.IsInvoice	
	FROM PD_PchBill_his p
	INNER JOIN BD_Btype b ON p.BtypeID = b.BTypeID
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs w ON w.WhsID=p.WhsID
	LEFT JOIN BD_Finance f ON p.FinanceID=f.FinanceID
	LEFT JOIN BD_Finance f2 ON p.FreightFinanceID=f2.FinanceID
	LEFT JOIN BD_Btype b2 ON p.LogistBtypeID = b2.BTypeID
	WHERE BillNo=@BillNo
	
	SELECT  p.DID,
			p.GoodsID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			p.OrdDID,
			g.Spec,
			p.WhsPtID,
			p.WhsID,
			wp.WhsPtName,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			Price,
			Qty,
			BSQty,
			Total,
			Discount,
			DiscPrice,
			DiscTotal,
			Tax,
			TaxRate,
			TaxPrice,
			TaxTotal,
			CAST(Gift AS BIT) AS Gift ,
			p.Remark,
			p.BatchNumber,p.ProductDate,p.EndDate,p.InPutPrice,g.DateType,g.ValidDays,g.CostMethod,
			p.Freight,
			p.InPrice,
			p.InTotal,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,	
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3,
			op.BillCode	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			p.PriceID,
			p.VerifyQty	,			
			CASE WHEN p.Qty=p.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
			g.IsSerial	,
			p.goodsno AS BtypeGoodsNo,
			g.Brand,
			g.KG	
	FROM PD_PchDetail_his p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN 
	(
		SELECT BillCode,DID 
		FROM PD_PchOrdDetail D
		INNER JOIN PD_PchOrdBill b ON d.BillNo = b.BillNo
		UNION ALL
		SELECT BillCode,DID 
		FROM PD_PchOrdDetail_His D
		INNER JOIN PD_PchOrdBill_His b ON d.BillNo = b.BillNo
	) op ON op.DID= p.OrdDID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo
	
	-- 查询多账户信息
	SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 101 and BillNo = @BillNo
	
	-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_PchSerial_His ps Inner Join PD_PchDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	END

END
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询采购明细
	××××××××××××××××××
	修改：sunzhiyuan
	日期：2015-3-26
	修改描述：24行：增加@DateType（时间类型）参数；
			 161行：判断时间类型
					修改参数@BeginDate、@EndDate为DateTime类型
			 72行：取消归档数据判断
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyDetails]
(
	@PageNo INT=0,                          --页码
	@PageSize INT=0,                        --分页数
	@DateType INT=0,                        --单据日期类型 0 业务日期 1 制单日期 2 过账日期
	@BeginDate DATETIME,                    --单据开始日期
	@EndDate DATETIME,                      --单据结束日期
	@BuyBillIn Int = 1,                     --采购入库单勾选状态
	@BuyBillOut Int = 1,                    --采购退货单勾选状态
	@BTypeID VARCHAR(max)='',               --往来单位
	@DeptID VARCHAR(max)='',                --部门
	@ElyID VARCHAR(max)='',                 --经手人
	@CreatorID VARCHAR(max)='',             --制单人
	@WhsID VARCHAR(max)='',
	@BillCode VARCHAR(100)='',
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100)='',
	@UserCodeMatch INT=0,
	@UserCode VARCHAR(100)='',
	@FullNameMatch INT=0,
	@Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	@Ppt1 VARCHAR(100)='',
	@Ppt1Match INT=0,
	@Ppt2 VARCHAR(100)='',
	@Ppt2Match INT=0,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=0,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=0,
	@Remark VARCHAR(100)='',
	@RemarkMatch INT=0,
	@GiftFlag INT=0,
	@OrderType1 Varchar(100)='CreateTime',				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额
	@OrderSeq1 Int=1,  --排序类型 1=升序，2=降序
	@OrderType2 Varchar(100)='GoodsNo',				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额			
	@OrderSeq2 Int=1,  --排序类型 1=升序，2=降序
	@AuQtyFlag INT= 0,
	@IsRedFlag Int = 0,
	@OperatorID INT,
	@ClassID1 Int = 0,		--汇总条件一，ID
	@ClassType1 Int = 0,	--汇总条件一类型 1为商品汇总，2为往来单位汇总，3为仓库汇总，4为地区汇总，5为部门汇总，6为职员汇总
	@ClaseFlag1 Int = 0,	--汇总条件一分类 0为非分类，1为分类汇总
	@ClassID2 Int = 0,		--汇总条件二，ID
	@ClassType2 Int = 0,	--汇总条件二类型 1为商品汇总，2为往来单位汇总，3为仓库汇总，4为地区汇总，5为部门汇总，6为职员汇总
	@ClaseFlag2 Int = 0	,	--汇总条件二分类 0为非分类，1为分类汇总
	@isHistory INT=0,				--是否包含历史数据
	@ClickFlag Int =0
)

AS
SET NOCOUNT ON
	-- 如果单据日期类型为业务日期 则检查是否存在归档数据
	IF @DateType = 0
	BEGIN
		DECLARE @re int 
		execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
		if( @re=1 )return @re;
	END
set @OrderType1 = isnull(@OrderType1,'')	
set @OrderType2 = isnull(@OrderType2,'')
if((@OrderType1='' or @OrderType1 = null) and (@OrderType2='' or @OrderType2 = null))
Begin
	Set @OrderType1='CreateTime'
End

DECLARE @Sql nvarchar(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlMatch varchar(max)=''
		,@SqlWhs nvarchar(max)='',@SqlDept nvarchar(max)='',@SqlEly nvarchar(max)='',@SqlPost nvarchar(max)='',@SqlUnit nvarchar(2000)='',
		@SqlUnit1 nvarchar(1000)='',@SqlUnit2 nvarchar(1000)='',@SqlUnit3 nvarchar(1000)='',@SqlBtype nvarchar(max)='',
		@SqlCreator nvarchar(max)='',@SqlIn nvarchar(Max)='',@SqlOut nVarchar(max)='',@OrderName nvarchar(100)='',
		@OrderColumn varchar(max)='',@OrderTable varchar(max)='',@GoodsTable varchar(max)='',@GoodsMath varchar(max)='', 
		@SqlGoods Nvarchar(1000)='',@SqlPpt1 nvarchar(1000)='',@SqlPpt2 nvarchar(1000)='', @LimitKtypeSql NVARCHAR(MAX) = '', @LimitBtypeSql NVARCHAR(MAX) = '',
		@RedStr varchar(100)='',@Red varchar(100)=''
		,@SqlClass1 varchar(500)='',@SqlClass2 varchar(500)='',@SqlBSUnit nvarchar(1000)='',@SqlBase varchar(max)='',@SqlAuUnit nvarchar(Max)='',
		@buyStr varchar(max)=' bill.BillNo,DID',@buyRetStr varchar(max)=' bill.BillNo,DID'
		,@pageDataStr varchar(max)=' BillNo,BillTypeID,DiD',@OutStr varchar(max)='',@outRetStr varchar(max)=''
		,@SqlInStr varchar(max)='',@SqlOutStr varchar(max)='',@outSql varchar(max)='',@BtypeLimit INT=0,@KtypeLimit INT=0
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
End
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
Select @SqlCreateTable+= ' Declare @GoodsTypeID Int,@BtypeTypeID Int,@WhsTypeID int,@AreaTypeID Int,@DeptID Int,@CreateID Int
		if @ClassID1 <> 0
		Begin			
			if(@ClassType1 = 1 and @ClaseFlag1 = 1)
				Select @GoodsTypeID = @ClassID1
			if(@ClassType1 = 2 and @ClaseFlag1 = 1)
				Select @BtypeTypeID = @ClassID1
			if(@ClassType1 = 3 and @ClaseFlag1 = 1)
				Select @WhsTypeID = @ClassID1
			if(@ClassType1 = 4)
				Select @AreaTypeID = @ClassID1
			if(@ClassType1 = 5)
				Select @DeptID = @ClassID1
			if(@ClassType1 = 7)
				Select @CreateID = @ClassID1
		END
		if @ClassID2 <> 0
		Begin
			if(@ClassType2 = 1 and @ClaseFlag2 = 1)
				Select @GoodsTypeID = @ClassID2
			if(@ClassType2 = 2 and @ClaseFlag2 = 1)
				Select @BtypeTypeID = @ClassID2
			if(@ClassType2 = 3 and @ClaseFlag2 = 1)
				Select @WhsTypeID = @ClassID2
			if(@ClassType2 = 4)
				Select @AreaTypeID = @ClassID2
			if(@ClassType2 = 5)
				Select @DeptID = @ClassID2
			if(@ClassType2 = 7)
				Select @CreateID = @ClassID2
		END '
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID1,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON bill.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON bill.ElyID=E.TypeID ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' INNER JOIN @CreateEType CE ON bill.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	SET @SqlTable+=' INNER JOIN @KType W ON bill.WhsID=W.TypeID ' 
END	

-- 判断单据时间类型
if @DateType = 0
	set @SqlDTStr = 'detail.BillDate'
IF @DateType=1
	SET @SqlDTStr='bill.CreateTime'	
IF @DateType=2
	SET @SqlDTStr='bill.PosTime'
if(@Summary <> '')
	Set @SqlMatch += ' And Summary ' + case @SummaryMatch when 0 then ' Like ''%''+@Summary+''%''' Else ' =@Summary ' End
if(@Description <> '')
	Set @SqlMatch += ' And Description ' + case @DescriptionMatch when 0 then ' Like ''%''+@Description+''%''' Else ' =@Description ' END
if(@Remark <> '')
	Set @SqlMatch += ' And Remark ' + case @RemarkMatch when 0 then ' Like ''%''+@Remark+''%''' Else ' =@Remark ' END
if(@BillCode <> '')
	Set @SqlMatch += ' And BillCode ' + case @BillCodeMatch when 0 then ' Like ''%''+@BillCode+''%''' Else ' =@BillCode ' END	
if(@FullName <> '' or @UserCode <> '' or @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> '')
Begin
	if(@FullName <> '')
		Set @GoodsMath += ' And G.GoodsName ' + case @FullNameMatch when 0 then ' Like ''%''+@FullName+''%''' Else ' =@FullName ' END
	if(@UserCode <> '')
		Set @GoodsMath += ' And G.GoodsNo ' + case @UserCodeMatch when 0 then ' Like ''%''+@UserCode+''%''' Else ' =@UserCode ' END
	--商品型号
	IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @GoodsMath += N' AND G.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @GoodsMath += N' AND G.Model = @Model ' 
	END   
	--商品简名    
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @GoodsMath += N' AND G.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @GoodsMath += N' AND G.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @GoodsMath += N' AND G.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @GoodsMath += N' AND G.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
	   IF @SpecMatch = 0
		   SET @GoodsMath += N' AND G.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @GoodsMath += N' AND G.Spec = @Spec '  
	END
	
	Select @GoodsTable += ' And exists(select 1 from BD_GOODS G Where detail.GoodsID = G.GoodsID '+@GoodsMath+')'
End
--商品条码
IF @BarCode <> ''      
BEGIN 
   SET @SqlTable+=' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID and pri.UnitID = 1 '
   
   SET @GoodsTable += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = detail.GoodsID '
	   IF @BarCodeMatch = 0
		   SET @GoodsTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @GoodsTable += N' AND pri.BarCode = @BarCode ' 
	   SET @GoodsTable += ' ) '
   
   --IF @BarCodeMatch = 0
	  -- SET @SqlMatch += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   --ELSE IF @BarCodeMatch = 1
	  -- SET @SqlMatch += N' AND pri.BarCode = @BarCode ' 
END
if(@Ppt1 <> '' or (@ClickFlag = 1 and  @Ppt1Match = 1))
BEGIN
	Set @GoodsMath = ' And GP1.Value ' + case @Ppt1Match when 0 then ' Like ''%''+@Ppt1+''%''' Else ' =@Ppt1 ' END
	Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt1 GP1 Where detail.Ppt1ID = GP1.Ppt1ID '+@GoodsMath+')'
END
if(@Ppt2 <> '' or (@ClickFlag = 1 and  @Ppt2Match = 1))
BEGIN
	Set @GoodsMath = ' And GP2.Value ' + case @Ppt2Match when 0 then ' Like ''%''+@Ppt2+''%''' Else ' =@Ppt2 ' END	
	Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt2 GP2 Where detail.Ppt2ID = GP2.Ppt2ID '+@GoodsMath+')'
END
if(@IsRedFlag = 0)
Begin
	Set @Red = ' And Red = 0 '
End
Else
	Set @RedStr = ',Red'
--按排序条件拼接首次需要查询的数据
if(@OrderType1 <> '')
Begin
	Select @buyStr += Case when @OrderType1 in ('BTypeCode','BTypeName') then ',BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',detail.GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',bill.'+@OrderType1
							else ',detail.'+@OrderType1 end
	Select @buyRetStr += Case when @OrderType1 in ('BTypeCode','BTypeName') then ',BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',detail.GoodsID'
							When @OrderType1 in ('Qty','Total','DiscTotal','CostPrice') then ',detail.'+@OrderType1+'*-1'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',bill.'+@OrderType1
							else ',detail.'+@OrderType1 end
	Select @pageDataStr += Case When @OrderType1 in ('BTypeCode','BTypeName') then ',bill.BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',bill.GoodsID'
							When @OrderType1 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
							When @OrderType1 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
							When @OrderType1 = 'BillTypeID' then '' 
							Else ','+@OrderType1 End
End
if(@OrderType2 <> '')
Begin
	Select @buyStr += Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',BTypeID ' End 
							When @OrderType2 in ('GoodsNo','GoodsName')  then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',detail.GoodsID' end
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',bill.'+@OrderType2
							else ',detail.'+@OrderType2 end

	Select @buyRetStr += Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',BTypeID ' End 
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',detail.GoodsID' end
							When @OrderType2 in ('Qty','Total','DiscTotal','CostPrice') then ',detail.'+@OrderType2+'*-1'
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',bill.'+@OrderType2
							else ',detail.'+@OrderType2 end

	Select @pageDataStr += Case When @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',bill.BTypeID ' End
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',bill.GoodsID' end 
							When @OrderType2 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
							When @OrderType2 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
							When @OrderType2 = 'BillTypeID' then '' 
							Else ','+@OrderType2 End	
End	
--拼接查询字段
Select @OutStr +=',bill.BillDate,BillCode,bill.BTypeID,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,detail.GoodsID,detail.Discount
	,Case When Bill.Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty,detail.Price
	,Case When Bill.Red = 2 then detail.Total * -1 Else detail.Total End as Total,detail.DiscPrice
	,Case when Bill.Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal,detail.CostPrice
	,Case When Bill.Red = 2 then detail.GoodsCostTotal * -1 Else detail.GoodsCostTotal End as GoodsCostTotal
	,Case When Bill.Red = 2 then detail.Freight*-1 Else detail.Freight End as Freight ,detail.InPrice
	,Case When Bill.Red = 2 Then detail.InTotal*-1 Else detail.InTotal End as  InTotal'
Select @OutRetStr +=',bill.BillDate,BillCode,bill.BTypeID,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,detail.GoodsID,detail.Discount
  ,Case When Bill.Red = 2 then detail.Qty Else detail.Qty*-1 End as Qty,detail.Price
  ,Case When Bill.Red = 2 Then detail.Total Else detail.Total*-1 End as Total,detail.DiscPrice
  ,Case When Bill.Red = 2 Then detail.DiscTotal Else detail.DiscTotal*-1 End as  DiscTotal,detail.CostPrice
  ,Case When Bill.Red = 2 Then detail.GoodsCostTotal Else detail.GoodsCostTotal*-1 End as GoodsCostTotal
  ,0 as Freight, detail.CostPrice as InPrice
  ,Case When Bill.Red = 2 Then detail.GoodsCostTotal Else detail.GoodsCostTotal*-1 End as  InTotal '
select @OutStr = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@OutStr,',bill.BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@OutStr,',detail.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@OutStr,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@OutStr,',bill.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@OutStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@OutStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@OutStr,',detail.Price','') 
					When @OrderType1 = 'Total' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Total * -1 Else detail.Total End as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@OutStr,',detail.Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@OutStr,',detail.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@OutStr,',Case when Bill.Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal','') 
					Else @OutStr end
select @OutStr = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@OutStr,',bill.BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@OutStr,',detail.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@OutStr,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@OutStr,',bill.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@OutStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@OutStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@OutStr,',detail.Price','') 
					When @OrderType2 = 'Total' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Total * -1 Else detail.Total End as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@OutStr,',detail.Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@OutStr,',detail.DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@OutStr,',Case when Bill.Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal','') 
					Else @OutStr end
select @OutRetStr = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@OutRetStr,',bill.BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@OutRetStr,',detail.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@OutRetStr,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@OutRetStr,',bill.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 then detail.Qty Else detail.Qty*-1 End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@OutRetStr,',detail.Price','') 
					When @OrderType1 = 'Total' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.Total Else detail.Total*-1 End as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@OutRetStr,',detail.Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@OutRetStr,',detail.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.DiscTotal Else detail.DiscTotal*-1 End as  DiscTotal','') 
					Else @OutRetStr end
select @OutRetStr = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@OutRetStr,',bill.BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@OutRetStr,',detail.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@OutRetStr,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@OutRetStr,',bill.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 then detail.Qty Else detail.Qty*-1 End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@OutRetStr,',detail.Price','') 
					When @OrderType2 = 'Total' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.Total Else detail.Total*-1 End as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@OutRetStr,',detail.Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@OutRetStr,',detail.DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.DiscTotal Else detail.DiscTotal*-1 End as  DiscTotal','') 
					Else @OutRetStr end
IF @ClassID1 <> 0
Begin
	SET @SqlClass1 +=' DECLARE @CTb1  as Table(typeid int) INSERT INTO @CTb1(typeid) '
	Set @SqlCreateTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass1 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass1 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then ' And detail.GoodsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on detail.GoodsID = C1.TypeID' end 
											when 2 then case @ClaseFlag1 when 0 then ' And bill.BtypeID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.BtypeID = C1.TypeID' end
											when 3 then case @ClaseFlag1 when 0 then ' And bill.WhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.WhsID = C1.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb1 C1 on BB.AreaID = C1.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb1 C1 on EE.DeptId = C1.TypeID'
											when 6 then ' And bill.ElyID = @ClassID1 ' 
											When 7 then ' And bill.Creator = @ClassID1' end 	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType1 = 4 and @ClassID1 = 0 
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END

IF @ClassID2 <> 0
Begin
	SET @SqlClass2 +=' DECLARE @CTb2  as Table(typeid int) INSERT INTO @CTb2(typeid) '
	Set @SqlCreateTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass2 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass2 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then ' And detail.GoodsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on detail.GoodsID = C2.TypeID' end 
											when 2 then case @ClaseFlag2 when 0 then ' And bill.BtypeID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.BtypeID = C2.TypeID' end
											when 3 then case @ClaseFlag2 when 0 then ' And bill.WhsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.WhsID = C2.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb2 C2 on BB.AreaID = C2.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb2 C2 on EE.DeptId = C2.TypeID'
											when 6 then ' And bill.ElyID = @ClassID2 '  
											When 7 then ' And bill.Creator = @ClassID2' end 	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType2 = 4 and @ClassID2 = 0
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END

--拼接主表查询字段语句					
select  @SqlIn += ' select 101 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyStr+@RedStr
		+',detail.UnitID from PD_PchBill bill INNER JOIN PD_PchDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
select @SqlOut += ' select 102 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyRetStr+@RedStr
		+',detail.UnitID  from PD_PchRetBill bill INNER JOIN PD_PchRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
--拼接排序后语句字段
Select @SqlInStr += ' Select A.*,'''+'采购入库单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,Summary,Description,detail.Remark ' +@OutStr
		+' from #tempTable A Inner Join PD_PchBill bill On a.BillNo = bill.BillNo INNER JOIN PD_PchDetail detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 101 '
Select @SqlOutStr += ' Select A.*,'''+'采购退货单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 Then detail.BSQty Else detail.BSQty*-1 End as BSQty,Summary,Description,detail.Remark ' +@OutRetStr
		+' from #tempTable A Inner Join PD_PchRetBill bill On a.BillNo = bill.BillNo INNER JOIN PD_PchRetDetail detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 102 '
if(@IsRedFlag <> 0)
Begin
	select  @SqlIn += '
		Union All
		select 101 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyStr+@RedStr
		+',detail.UnitID  from PD_PchBill bill INNER JOIN PD_PchDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable	
	select  @SqlIn += '
		Union All
		 select 101 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyRetStr+@RedStr  
		+',detail.UnitID  from PD_PchBill bill INNER JOIN PD_PchDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 102 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyRetStr+@RedStr  
		+',detail.UnitID  from PD_PchRetBill bill INNER JOIN PD_PchRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 102 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyStr+@RedStr  
		+',detail.UnitID  from PD_PchRetBill bill INNER JOIN PD_PchRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
End

IF @isHistory=1
Begin
	select  @SqlIn += '
		UNION ALL
	 select 101 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyStr+@RedStr  
		+',detail.UnitID  from PD_PchBill_His bill INNER JOIN PD_PchDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0 '  + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End +
		 +@SqlMatch + @GoodsTable
	select @SqlOut += '
		UNION ALL
	 select 102 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyRetStr+@RedStr  
		+',detail.UnitID  from PD_PchRetBill_His bill INNER JOIN PD_PchRetDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End +
		+@SqlMatch + @GoodsTable
	--拼接排序后语句字段
Select @SqlInStr += ' 
		UNION ALL
		Select A.*,'''+'采购入库单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,Summary,Description,detail.Remark ' + @OutStr
		+' from #tempTable A Inner Join PD_PchBill_His bill On a.BillNo = bill.BillNo INNER JOIN PD_PchDetail_His detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 101 '
Select @SqlOutStr += ' 
		UNION ALL
		Select A.*,'''+'采购退货单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 Then detail.BSQty Else detail.BSQty*-1 End as BSQty,Summary,Description,detail.Remark ' +@OutRetStr
		+' from #tempTable A Inner Join PD_PchRetBill_His bill On a.BillNo = bill.BillNo INNER JOIN PD_PchRetDetail_His detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 102 '
  if(@IsRedFlag <> 0)
  Begin
	select  @SqlIn += '
		Union All
		select 101 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyStr+@RedStr    
		+',detail.UnitID  from PD_PchBill_His bill INNER JOIN PD_PchDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable	
	select  @SqlIn += '
		Union All
		 select 101 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyRetStr+@RedStr 
		+',detail.UnitID  from PD_PchBill_His bill INNER JOIN PD_PchDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 102 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyRetStr+@RedStr   
		+',detail.UnitID  from PD_PchRetBill_His bill INNER JOIN PD_PchRetDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 102 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@buyStr+@RedStr    
		+',detail.UnitID  from PD_PchRetBill_His bill INNER JOIN PD_PchRetDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
  End
End
if (@BuyBillIn = 1)  
begin  
	if(@BuyBillOut = 1)  
	Begin
		Select @Sql += @SqlIn+ ' UNION ALL ' ;  
		Select @outSql += @SqlInStr+ ' UNION ALL ' ;  
	End
	else  
	Begin
		Select @Sql += @SqlIn ;  
		Select @outSql += @SqlInStr ;  
	End
end  
if (@BuyBillOut = 1)  
Begin
	Select @Sql += @SqlOut; 
	Select @outSql += @SqlOutStr;  
End
if (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
Begin
	Set @OrderColumn += ',BT.BTypeCode,BT.BTypeName '
	Set @OrderTable +=' LEFT JOIN BD_Btype BT ON bill.BTypeID = BT.BTypeID '
END 
if (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
Begin
	Set @OrderColumn += ',G.GoodsNo,G.GoodsName,G.Model,G.GoodsAbbName,G.Brand,G.Spec,pri.BarCode ,bill.BtypeGoodsNo'
	Set @OrderTable +=' Inner JOIN BD_GOODS G on bill.GoodsID = G.GoodsID '
	Set @OrderTable +=' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = bill.GoodsID and pri.UnitID = bill.UnitiD '
END  

SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
),
 PagingData AS
 (
	select '+@pageDataStr+@OrderColumn+@RedStr+'  
		from Bill bill '+@OrderTable
 set @sql +=' )
'

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

---排序字段
IF @OrderType1 <> ''
BEGIN
	IF @OrderSeq1 = 1 SET @OrderName = @OrderType1+' ASC' ELSE SET @OrderName = @OrderType1 +' DESC'
END
IF @OrderType2 <> ''
BEGIN
	IF @OrderName <> '' SET @OrderName +=', '
	IF @OrderSeq2 = 1 SET @OrderName += @OrderType2+' ASC' ELSE SET @OrderName += @OrderType2 +' DESC'
END	

------------------添加参数---------------------------------------
if Not (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
Begin	
	Select @SqlBtype+= ' Inner JOIN BD_Btype B ON Data.BtypeID = B.BtypeID '
	Select @SqlBase +=' ,B.BTypeCode,B.BTypeName '
End
if Not (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
Begin
	Select @SqlGoods+= ' Inner JOIN BD_Goods G ON Data.GoodsID = G.GoodsID '
	Select @SqlGoods+=' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = Data.GoodsID and pri.UnitID = Data.UnitID '
	Select @SqlBase +=' ,G.GoodsNo,G.GoodsName,G.Model,G.GoodsAbbName,G.Brand,G.Spec,pri.BarCode,bill.BtypeGoodsNo  '
End
if(@AuQtyFlag <> 0)
begin
	Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP1 on Data.GoodsID=BGP1.GoodsID And BGP1.UnitID=1 '
	Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP2 on Data.GoodsID=BGP2.GoodsID And BGP2.UnitID = 2'
	Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP3 on Data.GoodsID=BGP3.GoodsID And BGP3.UnitID = 3'
	Select @SqlBase += ' ,BGP1.Unit as Unit1,BGP1.Convfactor as Convfactor1 '
	Select @SqlBase += ' ,BGP2.Unit as Unit2,case when BGP2.Convfactor IS NULL then 1 else BGP2.Convfactor end as Convfactor2'
	Select @SqlBase += ' ,BGP3.Unit as Unit3,case when BGP3.Convfactor IS NULL then 1 else BGP3.Convfactor end as Convfactor3'
end

SELECT @sql += ',DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderName+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	select * into #tempTable from DATA
	--select * from DATA
	'
select @sql +=' select Data.*,WhsNO,WhsName,DeptCode,DeptName,E.ElyCode,E.ElyName as ElyName,EC.ElyName as Creator,EP.ElyName as PostName,Gpc.Unit,BSGpc.Unit as BSUnit
	,GP1.Value as Ppt1Name,GP2.Value as Ppt2Name '+@SqlBase+'
	 from ('+@outSql+') Data  
	Inner Join BD_Whs W On Data.WhsID = W.WhsID
	Left JOIN BD_Dept D ON Data.DeptID = D.DeptID  
	LEFT JOIN BD_Employee E ON Data.ElyID = E.ElyID 
	LEFT JOIN BD_Employee EC ON Data.CreatorID = EC.ElyID 
	LEFT JOIN BD_Employee EP ON Data.PosElyID = EP.ElyID 
	Inner Join BD_Goods_Price Gpc On Data.UnitID = Gpc.UnitID and Data.GoodsID = Gpc.GoodsID 
	Inner Join BD_Goods_Price BSGpc On Data.BSUnitID = BSGpc.UnitID and Data.GoodsID = BSGpc.GoodsID 
	Left Join BD_Goods_Ppt1 GP1 ON Data.Ppt1ID = GP1.Ppt1ID 
	Left Join BD_Goods_Ppt2 GP2 ON Data.Ppt2ID = GP2.Ppt2ID 
	' + @SqlBtype + @SqlGoods + @SqlAuUnit
select @sql += ' ORDER BY ROWID '
Select @sql += ' drop table #tempTable '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
exec sp_executesql @Sql,N'@PageNo Int,@PageSize Int,@DateType Int,@BeginDate DateTime,@EndDate DateTime,@OperatorID Int,@ClassID1 Int,@ClassType1 Int,@ClaseFlag1 Int,
			@ClassID2 Int,@ClassType2 Int,@ClaseFlag2 Int,@BTypeID VarChar(MAX),@DeptID1 VarChar(MAX)
			,@ElyID VarChar(MAX),@CreatorID varchar(MAx),@WhsID VarChar(MAX),@BillCode VarChar(MAX),@FullName VarChar(100),@UserCode VarChar(50),@Ppt1 VarChar(100),@Ppt2 VarChar(100)
			,@Summary VarChar(256),@Description VarChar(100),@Remark VarChar(256)
			,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT'
			,@PageNo,@PageSize,@DateType,@BeginDate,@EndDate,@OperatorID,@ClassID1,@ClassType1,@ClaseFlag1,@ClassID2,@ClassType2,@ClaseFlag2,
			@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@BillCode,@FullName,
			@UserCode,@Ppt1,@Ppt2,@Summary,@Description,@Remark ,
			@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch 

GO



/****** Object:  StoredProcedure [UP_PD_QueryBuyInvoice]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBuyInvoice]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBuyInvoice]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBuyInvoice]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：采购单据开票情况查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyInvoice]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@BTypeID VARCHAR(1000)='',		--往来单位
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@BillCode VARCHAR(50)='',		--单据编号
	@BillType INT=9,				--单据类型 9=全部,1=采购入库单,2=采购退货单
	@InvoiceState INT=9,			--开票状态 9=全部,2=已开票,0=未开票,1=部分开票
	@GoodsNoMatch INT = 0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',		--商品编号
	@GoodsNameMatch INT = 0,		--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',	--商品名称
	@SummaryMatch INT = 0,			--摘要配置模式:0=包含,1=等于
	@Summary VARCHAR(100) = '',		--摘要
	@DescriptionMatch INT = 0,		--说明配置模式:0=包含,1=等于
	@Description VARCHAR(100) = '',	--说明
	@PriceStart decimal(20,8),      --单价范围开始
	@PriceEnd  decimal(20,8),       --单价范围结束
	@TotalStart decimal(20,8),      --金额范围开始
	@TotalEnd  decimal(20,8),       --金额范围结束
	@IsShowRed INT=0,				--是否包含红冲数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@ClickFlag INT=0				--是否跳转
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql_PB VARCHAR(450)='',@Sql_PB_His VARCHAR(450)='',@Sql_PRB VARCHAR(450)='',@Sql_PRB_His VARCHAR(450)=''
		,@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@BtypeLimit INT=0 ,@SqlDetailParam NVARCHAR(MAX)='',@SqlDetailJoin NVARCHAR(MAX)=''
		,@SqlDetailPB NVARCHAR(MAX)='',@SqlDetailPRB NVARCHAR(MAX)='',@SqlDetailPB_His NVARCHAR(MAX)='',@SqlDetailPRB_His NVARCHAR(MAX)=''

IF @BTypeID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BTypeID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
IF @DeptID <> ''
	SET @SqlJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '

SET @SqlParam = '
	WHERE b.IsDraft=0 '
IF @IsShowRed = 0
	SET @SqlParam += '
	AND b.Red=0 '
IF @BillCode <> ''
	SET @SqlParam +='
	AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
	AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
-- 摘要
IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 0
		SET @SqlParam += 'AND b.Summary Like ''%''+@Summary+''%'' '  
	IF @SummaryMatch = 1
		SET @SqlParam += 'AND b.Summary = @Summary '  
END
-- 说明
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 0
		SET @SqlParam += 'AND b.Description Like ''%''+@Description+''%'' '  
	IF @DescriptionMatch = 1
		SET @SqlParam += 'AND b.Description = @Description '  
END
IF @GoodsName <> '' OR @GoodsNo <> ''
BEGIN
	SET @SqlDetailJoin += ' INNER JOIN BD_Goods _goods ON _goods.GoodsID = dtl.GoodsID '
END
-- 商品名称
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsNo Like ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsNo = @GoodsNo '  
END
-- 商品名称
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsName Like ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsName = @GoodsName '  
END
-- 商品单价从--到
IF @PriceEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Price BETWEEN @PriceStart AND @PriceEnd '
END
-- 商品金额从--到
IF @TotalEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Total BETWEEN @TotalStart AND @TotalEnd '
END
IF @GoodsName <> '' OR @GoodsNo <> '' OR @PriceEnd <> 0 OR @TotalEnd <> 0
BEGIN
	SET @SqlDetailPB += '  AND EXISTS (SELECT 1 FROM PD_PchDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailPRB += '  AND EXISTS (SELECT 1 FROM PD_PchRetDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailPB_His += '  AND EXISTS (SELECT 1 FROM PD_PchDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailPRB_His += '  AND EXISTS (SELECT 1 FROM PD_PchRetDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
END
IF @InvoiceState <> 9
BEGIN
	IF @InvoiceState = 2
		SET @SqlParam +='
	AND ABS(b.InvoiceTotal)>=b.Total '
	IF @InvoiceState = 0
		SET @SqlParam +='
	AND b.InvoiceTotal=0 '
	IF @InvoiceState = 1
		SET @SqlParam +='
	AND b.InvoiceTotal<>0 AND ABS(b.InvoiceTotal)<b.Total '
END
SET @SqlParam += ' AND IsInvoice = 1 '	 --只查询是否开票为是的单据
SET @Sql_PB += '
	SELECT 101[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_PchBill b '
SET @Sql_PRB += '
	SELECT 102[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_PchRetBill b '
SET @Sql_PB_His += '
	SELECT 101[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_PchBill_His b '
SET @Sql_PRB_His += '
	SELECT 102[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_PchRetBill_His b '
IF @IsHistory = 1
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_PB + @SqlJoin + @SqlParam + @SqlDetailPB + '
	UNION ALL ' + @Sql_PB_His + @SqlJoin + @SqlParam + @SqlDetailPB_His
	ELSE IF @BillType = 2
		SET @Sql = @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB + '
	UNION ALL ' + @Sql_PRB_His + @SqlJoin + @SqlParam + @SqlDetailPRB_His
	ELSE
		SET @Sql = @Sql_PB + @SqlJoin + @SqlParam + @SqlDetailPB + '
	UNION ALL ' + @Sql_PB_His + @SqlJoin + @SqlParam + @SqlDetailPB_His + '
	UNION ALL ' + @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB + '
	UNION ALL ' + @Sql_PRB_His + @SqlJoin + @SqlParam + @SqlDetailPRB_His
END
ELSE
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_PB + @SqlJoin + @SqlParam + @SqlDetailPB
	ELSE IF @BillType = 2
		SET @Sql = @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB
	ELSE
		SET @Sql = @Sql_PB  + @SqlJoin + @SqlParam + @SqlDetailPB + '
	UNION ALL ' + @Sql_PRB + @SqlJoin + @SqlParam + @SqlDetailPRB
END

SET @Sql = 'IF OBJECT_ID(''tempdb..#tempbo'',''U'') IS NOT NULL DROP TABLE #tempbo 
SET NOCOUNT ON; 
;WITH BillData AS( ' + @Sql + '
)'
SET @Sql += '
SELECT * INTO #tempbo 
FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillCode) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
WHERE B.ROWID>(@PageNo-1)*@PageSize AND B.ROWID<=@PageNo*@PageSize 
SELECT o.*,b1.BTypeName,d.DeptName,e.ElyName
	,CASE WHEN BillTypeID=101 THEN ''采购入库单'' ELSE ''采购退货单'' END[BillType]
	,CASE WHEN InvoiceMode=1 THEN ''按商品开票'' WHEN InvoiceMode=2 THEN ''按单据开票'' ELSE '''' END[InvoiceModeShow]
FROM #tempbo o 
INNER JOIN BD_Btype b1 ON b1.BTypeID = o.BTypeID 
INNER JOIN BD_Dept d ON d.DeptID = o.DeptID 
INNER JOIN BD_Employee e ON e.ElyID = o.ElyID 
ORDER BY o.ROWID 
DROP TABLE #tempbo '

IF @BtypeLimit = 0 
	SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
	
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END

EXEC SP_EXECUTESQL @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@BillCode VARCHAR(50),@OperatorID INT,
						  @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),@SummaryMatch INT, @Summary VARCHAR(100), @DescriptionMatch INT, @Description VARCHAR(100),
						  @PriceStart DECIMAL(20,8),@PriceEnd DECIMAL(20,8), @TotalStart DECIMAL(20,8), @TotalEnd DECIMAL(20,8)',
						  @PageNo,@PageSize,@BillStartDate,@BillEndDate,@BTypeID,@DeptID,@ElyID,@BillCode,@OperatorID,
						  @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName, @SummaryMatch, @Summary, @DescriptionMatch, @Description,
						  @PriceStart, @PriceEnd, @TotalStart, @TotalEnd

END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryBuyInvoiceData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryBuyInvoiceData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-02-13
	描述：查询采购发票数据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyInvoiceData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS

DECLARE @TableIndex NVARCHAR(100) = '', @TableDetail NVARCHAR(100) = '', @TableContent NVARCHAR(100) = '', @IsHis NVARCHAR(10) = ''
DECLARE @IndexSql NVARCHAR(MAX) = '', @DetailSql NVARCHAR(MAX) = '', @ListSql NVARCHAR(MAX) = '',  @InvoiceMode TINYINT = 1
DECLARE @PSql NVARCHAR(MAX) = '', @PRetSql NVARCHAR(MAX)= '', @P_HisSql NVARCHAR(MAX)= '', @PRet_HisSql NVARCHAR(MAX)=''



IF EXISTS(SELECT 1 FROM MF_PchInvoiceBill_His WHERE BillNo = @BillNo)
BEGIN
	SELECT @InvoiceMode = InvoiceMode FROM MF_PchInvoiceBill_His WHERE BillNo = @BillNo
	SET @IsHis = '_His '
END ELSE
BEGIN
	SELECT @InvoiceMode = InvoiceMode FROM MF_PchInvoiceBill WHERE BillNo = @BillNo
	SET @IsHis = ' '
END

SET @TableIndex = ' MF_PchInvoiceBill'+ @IsHis
SET @TableDetail = ' MF_PchInvoiceDetail' + @IsHis
SET @TableContent = ' MF_PchInvoiceContent' + @IsHis
	
--单据索引
SET @IndexSql = '
SELECT	  TOP 1
		  BillCode ,
		  BillDate ,
		  BillNo,
		  p.BTypeID ,
		  b.BTypeName,
		  p.DeptID ,
		  d.DeptName,
		  p.ElyID ,
		  e.ElyName,
		  InvoiceCode,
		  InvoiceType ,
          InvoiceMode ,
          InvoiceTotal ,
		  Summary ,
		  IsDraft,
		  [Description] ,
		  p.Creator AS CreatorID,
		  e1.ElyName AS CreatorName,
		  e2.ElyName AS PosName
FROM '+ @TableIndex +' p
INNER JOIN BD_Btype b ON p.BtypeID = b.BTypeID
INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
LEFT  JOIN BD_Employee e1 ON p.Creator=e1.ElyID
LEFT  JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
INNER JOIN BD_Dept d ON e.DeptId = d.DeptId
WHERE BillNo= @BillNo '

--单据明细
IF @InvoiceMode = 1
BEGIN
SET @PSql = '
	SELECT SD.BillNo ,				PchBillNo ,				SB.BillCode,	SB.BillDate,
           SB.Summary,		SB.Description,		SD.PchDID ,				PSD.GoodsID,	P.GoodsNo,				
           P.GoodsName,		PSD.Ppt1ID,			P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,	
           PSD.Qty,			PSD.Total,			PSD.Price,				PSD.UnitID,		GP.Unit,				
           SD.BillType ,	SD.InvoiceQty ,		SD.InvoiceTotal ,		
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty - ISNULL(PY.YInvoiceQty, 0)  AS NInvoiceQty,
           PSD.Total - ISNULL(PY.YInvoiceTotal, 0) AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchBill SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_PchDetail PSD ON SD.PchDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT PchDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal
				FROM '+ @TableDetail +' D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
					GROUP BY PchDID
				) PY ON PY.PchDID = SD.PchDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 101
'
SET @PRetSql='
	SELECT SD.BillNo ,							PchBillNo ,				SB.BillCode,	SB.BillDate,
           SB.Summary,			SB.Description,				SD.PchDID ,				PSD.GoodsID,	P.GoodsNo,
           P.GoodsName,			PSD.Ppt1ID,					P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,
           PSD.Qty*(-1) AS Qty,	PSD.Total *(-1) AS Total,	PSD.Price,				PSD.UnitID,		GP.Unit,
           SD.BillType ,		SD.InvoiceQty ,				SD.InvoiceTotal ,
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty*(-1) - ISNULL(PY.YInvoiceQty, 0) AS NInvoiceQty,
           PSD.Total*(-1) - ISNULL(PY.YInvoiceTotal, 0) AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchRetBill SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_PchRetDetail PSD ON SD.PchDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT PchDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal 
				FROM '+ @TableDetail +'  D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
				GROUP BY PchDID
				) PY ON PY.PchDID = SD.PchDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 102
'

SET @P_HisSql = '
	SELECT SD.BillNo ,				PchBillNo ,				SB.BillCode,	SB.BillDate,
           SB.Summary,		SB.Description,		SD.PchDID ,				PSD.GoodsID,	P.GoodsNo,				
           P.GoodsName,		PSD.Ppt1ID,			P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,	
           PSD.Qty,			PSD.Total,			PSD.Price,				PSD.UnitID,		GP.Unit,				
           SD.BillType ,	SD.InvoiceQty ,		SD.InvoiceTotal ,		
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty - ISNULL(PY.YInvoiceQty, 0)  AS NInvoiceQty,
           PSD.Total - ISNULL(PY.YInvoiceTotal, 0) AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchBill_His SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_PchDetail_His PSD ON SD.PchDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT PchDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal
				FROM '+ @TableDetail +' D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
					GROUP BY PchDID
				) PY ON PY.PchDID = SD.PchDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 101
'
SET @PRet_HisSql ='
	SELECT SD.BillNo ,							PchBillNo ,				SB.BillCode,	SB.BillDate,
           SB.Summary,			SB.Description,				SD.PchDID ,				PSD.GoodsID,	P.GoodsNo,
           P.GoodsName,			PSD.Ppt1ID,					P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,
           PSD.Qty*(-1) AS Qty,	PSD.Total *(-1) AS Total,	PSD.Price,				PSD.UnitID,		GP.Unit,
           SD.BillType ,		SD.InvoiceQty ,				SD.InvoiceTotal ,
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty*(-1) - ISNULL(PY.YInvoiceQty, 0) AS NInvoiceQty,
           PSD.Total*(-1) - ISNULL(PY.YInvoiceTotal, 0) AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchRetBill_His SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_PchRetDetail_His PSD ON SD.PchDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT PchDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal 
				FROM '+ @TableDetail +'  D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
				GROUP BY PchDID
				) PY ON PY.PchDID = SD.PchDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 102
'
	SET @DetailSql =  @PSql +' UNION ALL '+ @PRetSql +' UNION ALL '+@P_HisSql +' UNION ALL '+ @PRet_HisSql
END ELSE
IF @InvoiceMode = 2
BEGIN
	SET @DetailSql = '
		SELECT BillNo ,
           BillDate ,
           GoodsMsg ,
           InvoiceTotal ,
           Remark
    FROM '+ @TableContent +' WHERE BillNo = @BillNo
	'
	
	SET @ListSql = '
	SELECT SD.BillNo ,
           SB.BillDate ,
           PchBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           PchDID ,
           SD.BillType ,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchBill SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 101
	UNION ALL
	SELECT SD.BillNo ,
           SB.BillDate ,
           PchBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           PchDID ,
           SD.BillType ,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total*(-1) AS Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total*(-1) - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchRetBill SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 102
	UNION ALL
	SELECT SD.BillNo ,
           SB.BillDate ,
           PchBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           PchDID ,
           SD.BillType ,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchBill_His SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 101
	UNION ALL
	SELECT SD.BillNo ,
           SB.BillDate ,
           PchBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           PchDID ,
           SD.BillType ,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total*(-1) AS Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total*(-1) - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_PchRetBill_His SB ON SD.PchBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 102
	'
END ELSE
IF @InvoiceMode = 3
BEGIN
	SET @DetailSql = '
	SELECT BillNo ,
           BillDate ,
           GoodsMsg ,
           InvoiceTotal ,
           Remark
    FROM '+ @TableContent +' WHERE BillNo = @BillNo
	'
END
--print(@DetailSql)
exec sp_executesql @IndexSql , N'@BillNo INT', @BillNo
exec sp_executesql @DetailSql , N'@BillNo INT', @BillNo
exec sp_executesql @ListSql, N'@BillNo INT', @BillNo
GO




/****** Object:  StoredProcedure [UP_PD_QueryBuyInvoiceDetail]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBuyInvoiceDetail]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBuyInvoiceDetail]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBuyInvoiceDetail]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：采购单据开票情况查询(明细)
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyInvoiceDetail]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillNo BIGINT=0,				--单据编号
	@BillTypeID INT=101				--单据类型
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@Sql0 NVARCHAR(MAX)='',@Sql1 NVARCHAR(MAX)='',@Sql2 NVARCHAR(MAX)='',@TableName VARCHAR(20)='',@HisStr VARCHAR(20)='_His'
		,@Sqla NVARCHAR(MAX),@Sqlb NVARCHAR(MAX),@Sqlc NVARCHAR(MAX),@Sqld NVARCHAR(MAX)
IF EXISTS (SELECT 1 FROM MF_PchInvoiceDetail dtl WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql1='
		SELECT dtl.PchBillNo,dtl.PchDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_PchInvoiceDetail dtl
		WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY PchBillNo,PchDID,BillType '
IF EXISTS (SELECT 1 FROM MF_PchInvoiceDetail_His dtl WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql2='
		SELECT dtl.PchBillNo,dtl.PchDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_PchInvoiceDetail_His dtl
		WHERE dtl.PchBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_PchInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY PchBillNo,PchDID,BillType '
IF @Sql1<>'' AND @Sql2<>''
	SET @Sql0 = @Sql1 +'
		UNION ALL ' + @Sql2
ELSE IF @Sql1<>'' AND @Sql2='' SET @Sql0 = @Sql1
ELSE IF @Sql1='' AND @Sql2<>'' SET @Sql0 = @Sql2
IF @BillTypeID = 101
BEGIN
	SET @TableName = 'PD_PchDetail'
	IF EXISTS (SELECT 1 FROM PD_PchDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='
;WITH PagingData AS 
( 
	SELECT dtl.DID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,dtl.Qty,dtl.UnitID,dtl.TaxTotal,pidtl.InvoiceQty,dtl.Qty-pidtl.InvoiceQty[NoInvoiceQty],pidtl.InvoiceTotal,dtl.TaxTotal-ISNULL(pidtl.InvoiceTotal,0)[NoInvoiceTotal],dtl.Remark 
	FROM '+@TableName+@HisStr+' dtl 
	LEFT JOIN ( '+@Sql0+'
	) AS pidtl ON PchBillNo = dtl.BillNo AND pidtl.PchDID = dtl.DID AND BillType=@BillTypeID 
	WHERE dtl.BillNo=@BillNo 
) '
END
ELSE
BEGIN
	SET @TableName = 'PD_PchRetDetail'
	IF EXISTS (SELECT 1 FROM PD_PchRetDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='
;WITH PagingData AS 
( 
	SELECT dtl.DID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,dtl.Qty*-1[Qty],dtl.UnitID,dtl.TaxTotal*-1[TaxTotal],pidtl.InvoiceQty,dtl.Qty*-1-pidtl.InvoiceQty[NoInvoiceQty],pidtl.InvoiceTotal,dtl.TaxTotal*-1-ISNULL(pidtl.InvoiceTotal,0)[NoInvoiceTotal],dtl.Remark 
	FROM '+@TableName+@HisStr+' dtl 
	LEFT JOIN ( '+@Sql0+'
	) AS pidtl ON PchBillNo = dtl.BillNo AND pidtl.PchDID = dtl.DID AND BillType=@BillTypeID 
	WHERE dtl.BillNo=@BillNo 
) '
END

/***********定义要关联的基础资料sql***********/
SET @Sqla=N'SELECT GoodsID[G1ID],GoodsNo,GoodsName,Spec,Model FROM BD_Goods'
SET @Sqlb=N'SELECT Ppt1ID[P1ID],Value[Ppt1Name] FROM BD_Goods_Ppt1'
SET @Sqlc=N'SELECT Ppt2ID[P2ID],Value[Ppt2Name] FROM BD_Goods_Ppt2'
SET @Sqld=N'SELECT GoodsID[G2ID],UnitID[UID],Unit FROM BD_Goods_Price'

DECLARE @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillNo','BIGINT',@BillNo)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillTypeID','INT',@BillTypeID)

/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsID=_DATA_a.G1ID',@Sqla)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_b','Data.Ppt1ID=_DATA_b.P1ID',@Sqlb)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_c','Data.Ppt2ID=_DATA_c.P2ID',@Sqlc)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_d','Data.GoodsID=_DATA_d.G2ID AND Data.UnitID=_DATA_d.UID',@Sqld)

EXEC UP_OT_Paging @Sql,@TVP,@PageNo,@PageSize,'DID','','',1,0

GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询采购明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyInvoiceStatistical]
(
	@PageNo INT=0,
	@PageSize INT=0,
	--@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillType Int=0,  --单据类型
	@BTypeID VARCHAR(max)='',
	@OrderType1 Varchar(100)='BTypeCode',	--排序条件
	@OrderSeq1 Int=1,  --排序类型 1=升序，2=降序
	@IsManual INT=0,  --是否勾选手工开票单独列示
	@IsRedFlag INT=0,				--是否包含红冲单据数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID Int=0
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;
set @OrderType1 = isnull(@OrderType1,'')	
if(@OrderType1='')
Begin
	Set @OrderType1='BTypeCode'
End

DECLARE @Sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',
		@OrderName nvarchar(100)='', @LimitBtypeSql NVARCHAR(MAX) = '',@OutStr varchar(max)='',@outRetStr varchar(max)=''
		,@outSql varchar(max)='',@BtypeLimit INT=0,@RedStr varchar(100)=''
		,@InvoiceSql varchar(max)='',@InvoiceModeSql varchar(max)='',@InvoiceOutModeSql varchar(Max)=''
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
--SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
--IF @KtypeLimit = 1
--Begin
--	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
--	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
--End
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
if @IsRedFlag = 0
	select @RedStr = ' And Red=0 '
select @RedStr += ' And IsInvoice = 1 ' --只查询是否开票为是的单据
---------------计算单据金额列信息----------------
Select @OutStr +=' select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
Select @outRetStr +=' select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchRetBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
select @InvoiceSql += ' select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_PchInvoiceBill bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0 group by BTypeID'
if @IsHistory = 1
begin
	Select @OutStr +='
		Union All
		 select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	Select @outRetStr +=' 
		Union All
		select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_PchRetBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	select @InvoiceSql += '
		Union All
	 select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_PchInvoiceBill_His bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0  group by BTypeID'
end
if @BillType = 0
	Select @Sql += @OutStr + ' Union All ' + @outRetStr
else if @BillType =1
	Select @Sql += @OutStr 
else
	Select @Sql += @outRetStr 
-----------拼接排序条件-----------------
select @OrderName += @OrderType1 + Case when @OrderSeq1 = 2 then ' Desc ' else ' ' end
-----------不同的显示方式计算未结金额和超额金额-----------
if @IsManual = 1 
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal2,SUM(UserTotal1) as UserTotal2,sum(Total) - sum(BillTotal1) as NoInvoiceTotal '
	Select @InvoiceOutModeSql +=' data.BtypeID,Total,BillTotal2,UserTotal2,NoInvoiceTotal'
End
else
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal1,SUM(UserTotal1) as UserTotal1,
					sum(Total) - sum(BillTotal1) - SUM(UserTotal1) as NoInvoiceTotal,sum(BillTotal1) + SUM(UserTotal1)- sum(Total) as OutInvoiceTotal '
	Select @InvoiceOutModeSql +=' data.BtypeID,Total,BillTotal1,UserTotal1
								,case when total >= 0 then (case when NoInvoiceTotal<=0 then 0 else NoInvoiceTotal end) else (case when NoInvoiceTotal > 0 then 0 else NoInvoiceTotal end) end as NoInvoiceTotal
								,case When total >= 0 then (Case When OutInvoiceTotal <=0 then 0 else OutInvoiceTotal end) Else (Case When OutInvoiceTotal >= 0 then 0 else OutInvoiceTotal end) End as OutInvoiceTotal'
End

SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
),BillTotal as(
	Select BTypeID,sum(Total) as Total,sum(InvoiceTotal) as BillTotal1,0 as UserTotal1 from Bill Group By BTypeID
),InvoiceTotal as(
' +@InvoiceSql+ '
),AllData AS
 (
	select BTypeID,Total,BillTotal1,UserTotal1 from BillTotal
	Union All
	select BTypeID,Total,BillTotal1,UserTotal1 from InvoiceTotal
 ),PagingData AS(
	Select AD.BTypeID,B.BTypeCode,B.BTypeName,sum(Total) as Total '+@InvoiceModeSql+' 
	from AllData Ad Inner Join BD_Btype B on Ad.BTypeID = B.BtypeID Group By Ad.BTypeID,B.BtypeCode,B.BTypeName
 )
'


IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

------------------添加参数---------------------------------------

SELECT @sql += ',DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderName+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	'
select @sql +=' select [ROWCOUNT],ROWID,'+@InvoiceOutModeSql+',BTypeCode,BTypeName
	 from DATA data '
select @sql += ' ORDER BY ROWID '
IF @BtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Btype WHERE 1 <> 1'
DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 --PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
exec sp_executesql @Sql,N'@PageNo Int,@PageSize Int,@BeginDate Date,@EndDate Date,@OperatorID Int,@BTypeID VarChar(MAX)'
			,@PageNo,@PageSize,@BeginDate,@EndDate,@OperatorID,@BTypeID

GO



/****** Object:  StoredProcedure [UP_PD_QueryBuyOrdermDetailList]    Script Date: 07/01/2014 15:11:11 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBuyOrdermDetailList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBuyOrdermDetailList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBuyOrdermDetailList]    Script Date: 07/01/2014 15:11:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-01
	描述：采购订单管理(明细)
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyOrdermDetailList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillNo BIGINT=0,				--单据编号
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@StopTag INT=9,					--中止状态
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@Sqla NVARCHAR(MAX),@Sqlb NVARCHAR(MAX)
		,@Sqlc NVARCHAR(MAX),@Sqld NVARCHAR(MAX)
		,@HisStr VARCHAR(20)='_His',@KtypeLimit INT=0 
IF EXISTS (SELECT 1 FROM PD_PchOrdBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''

SET @Sql='
;WITH PagingData AS 
(
		SELECT DID,dtl.GoodsID,Ppt1ID,Ppt2ID,dtl.UnitID,dtl.ComQty[DHQty],Qty,dtl.Convfactor,TaxPrice[Price],TaxTotal[Total],dtl.ComTotal[DHTotal]
		,cast(dtl.Gift AS BIT) Gift
		,StopTag,CASE StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow]
		,dtl.Remark,dtl.goodsno as BtypeGoodsNo
		FROM PD_PchOrdDetail'+@HisStr+' dtl '
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1 --部份权限
	SET @Sql += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=dtl.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @Sql +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=dtl.WhsID '
	END
END
*/
IF @GoodsID <> ''
	SET @Sql +='
		INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID ' 
IF @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
BEGIN
	SET @Sql += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
END
--IF @BarCode <> ''
--BEGIN 
--	SET @Sql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID and pri.UnitID = dtl.UnitID '
--END
SET @Sql +='
		WHERE 1=1 '
IF @StopTag <> 9
	SET @Sql +='AND dtl.StopTag=@StopTag '

--商品型号	
IF @Model <> ''      
   BEGIN 
	   IF @ModelMatch = 0
		   SET @Sql += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @Sql += N' AND goods.Model = @Model ' 
   END  
--商品简名     
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @Sql += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @Sql += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
END     
--商品品牌  
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @Sql += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @Sql += N' AND goods.Brand = @Brand ' 
END  
--商品规格  
IF @Spec <> ''        
   BEGIN 
	   IF @SpecMatch = 0
		   SET @Sql += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @Sql += N' AND goods.Spec = @Spec '  
   END
--商品条码
IF @BarCode <> ''      
BEGIN 
	SET @Sql += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = dtl.GoodsID '
	IF @BarCodeMatch = 0
	   SET @Sql += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	ELSE IF @BarCodeMatch = 1
	   SET @Sql += N' AND pri.BarCode = @BarCode ' 
	SET @Sql += ' ) '
END 
	
SET @Sql +='AND dtl.BillNo=@BillNo 
) '

/***********定义要关联的基础资料sql***********/
SET @Sqla=N'SELECT GoodsID[G1ID],GoodsNo,GoodsName,Spec,Model,GoodsAbbName,Brand FROM BD_Goods'
SET @Sqlb=N'SELECT Ppt1ID[P1ID],Value[Ppt1Name] FROM BD_Goods_Ppt1'
SET @Sqlc=N'SELECT Ppt2ID[P2ID],Value[Ppt2Name] FROM BD_Goods_Ppt2'
SET @Sqld=N'SELECT GoodsID[G2ID],UnitID[UID],Unit,BarCode FROM BD_Goods_Price'

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillNo','BIGINT',@BillNo)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@GoodsID','VARCHAR(1000)',@GoodsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Model','VARCHAR(50)',@Model)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@ModelMatch','INT',@ModelMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@GoodsAbbName','VARCHAR(50)',@GoodsAbbName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@GoodsAbbNameMatch','INT',@GoodsAbbNameMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Brand','VARCHAR(50)',@Brand)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BrandMatch','INT',@BrandMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Spec','VARCHAR(50)',@Spec)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@SpecMatch','INT',@SpecMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BarCode','VARCHAR(100)',@BarCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BarCodeMatch','INT',@BarCodeMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@StopTag','INT',@StopTag)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@OperatorID','INT',@OperatorID)

/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsID=_DATA_a.G1ID',@Sqla)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_b','Data.Ppt1ID=_DATA_b.P1ID',@Sqlb)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_c','Data.Ppt2ID=_DATA_c.P2ID',@Sqlc)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_d','Data.GoodsID=_DATA_d.G2ID AND _DATA_d.UID = Data.UnitID ',@Sqld)

IF @KtypeLimit = 0 EXEC SP_EXECUTESQL N' SELECT * FROM BD_Area WHERE 1 <> 1'
ELSE 
EXEC UP_OT_Paging @Sql,@TVP,@PageNo,@PageSize,'DID','','',1,0

GO






/****** Object:  StoredProcedure [UP_PD_QueryBuyOrdermList]    Script Date: 06/16/2014 16:14:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBuyOrdermList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBuyOrdermList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBuyOrdermList]    Script Date: 06/16/2014 16:14:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-06-16
	描述：采购订单管理
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuyOrdermList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@DlvStartDate VARCHAR(50)='',	--交货日期查询开始时间
	@DlvEndDate VARCHAR(50)='',		--交货日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@BTypeID VARCHAR(1000)='',		--往来单位
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@WhsID VARCHAR(1000)='',		--仓库
	@GoodsID VARCHAR(1000)='',		--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@Stt VARCHAR(50)='',			--订单状态
	@StopTag INT=9,					--中止状态
	@IsDraft INT=9,                 --生效状态  ------update sunzhiyuan
	@AuditStatus VARCHAR(100)='',   --审核状态  ------update sunzhiyuan
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@BtypeAddr VARCHAR(max)='',		--往来单位地址
	@BtypePhone VARCHAR(max)=''		--往来单位编号
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX),@SqlHead VARCHAR(500),@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)='',@StrStt VARCHAR(500),@InnerStt VARCHAR(100),@SqlSum VARCHAR(1000),@SqlSumParam VARCHAR(100)='',@SqlSumHead VARCHAR(100),@SqlSumOther VARCHAR(200),@SqlSumHead_His VARCHAR(100),@SqlSumOther_His VARCHAR(200),@BtypeLimit INT=0,@KtypeLimit INT=0 
IF @BTypeID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BTypeID '
IF @DeptID <> ''
	SET @SqlJoin +='
		INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @WhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = b.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
		INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SqlJoin += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=b.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=b.BTypeID '
	END
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=b.WhsID '
	END
END
*/
SET @SqlParam = '
		WHERE 1=1 '
IF @BillCode <> ''
	SET @SqlParam +='AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @DlvStartDate <> ''
	SET @SqlParam +='AND b.DlvDate BETWEEN @DlvStartDate AND @DlvEndDate '
IF @Description <> ''
	SET @SqlParam +='AND b.[Description] Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='AND b.Summary Like ''%''+@Summary+''%'' '
IF @StopTag <> 9
BEGIN
	SET @SqlParam +='AND b.StopTag=@StopTag '
	SET @SqlSumParam ='WHERE p.StopTag=@StopTag '
END
-- 生效状态
IF @IsDraft <> 9
BEGIN
	SET @SqlParam +='AND b.IsDraft=@IsDraft '
	--SET @SqlSumParam ='WHERE p.IsDraft=@IsDraft '
END
-- 审核状态
IF @AuditStatus <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@AuditStatus, '','') _AuditStatus ON _AuditStatus.typeid = b.AuditStatus '
SET @SqlParam_His = @SqlParam
--IF @GoodsID <> ''
--BEGIN
--	SET @SqlParam_His += 'AND EXISTS (SELECT 1 FROM PD_PchOrdDetail_His dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--	SET @SqlParam += 'AND EXISTS (SELECT 1 FROM PD_PchOrdDetail dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--END
DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
--型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @ClauseParam += N' AND goods.Model = @Model ' 
END       
--简名
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @ClauseParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
END    
--品牌   
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
END    
--规格
IF @Spec <> ''        
BEGIN 
   IF @SpecMatch = 0
	   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @ClauseParam += N' AND goods.Spec = @Spec '  
END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
--条码
IF @BarCode <> ''      
BEGIN 
   IF @BarCodeMatch = 0
	   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID  '
END    


IF @GoodsID <> '' OR @ClauseParam <> ''
	BEGIN
		IF @GoodsID <> ''
			SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
		SET @SqlParam_His = @SqlParam + '
			AND EXISTS (SELECT 1 FROM PD_PchOrdDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
		SET @SqlParam += '
			AND EXISTS (SELECT 1 FROM PD_PchOrdDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
	END
ELSE
	SET @SqlParam_His = @SqlParam


SET @Sql = 'IF OBJECT_ID(''tempdb..#tempbo'',''U'') IS NOT NULL DROP TABLE #tempbo 
SET NOCOUNT ON; 
;WITH BillData AS( '
SET @SqlHead = '
		SELECT b.BillNo,BillDate,DlvDate,BillCode,StopTag,IsDraft,b.BTypeID,b.WhsID,ElyID,DeptID,BillQty,Total,[Description],Summary,AuditStatus '
SET @StrStt = '
			,CASE WHEN b.StopTag=1 THEN 2 
			WHEN NOT EXISTS(SELECT 1 FROM PD_PchOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty<BSQty) THEN 2 
			WHEN EXISTS(SELECT 1 FROM PD_PchOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty>0) THEN 1
			ELSE 0 END AS Stt '
SET @InnerStt = '
	INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = o.Stt '
SET @SqlSumHead = 'SELECT o.BillNo,SUM(p.ComQty/p.Convfactor)[DHQty],SUM(p.ComTotal)[DHTotal] '
SET @SqlSumOther = '
				FROM #tempbo o 
				INNER JOIN PD_PchOrdDetail p ON p.BillNo=o.BillNo '+@SqlSumParam+'GROUP BY o.BillNo '
SET @SqlSumHead_His = 'SELECT o.BillNo,SUM(p.ComQty/p.Convfactor)[DHQty],SUM(p.ComTotal)[DHTotal] '
SET @SqlSumOther_His = '
				FROM #tempbo o 
				INNER JOIN PD_PchOrdDetail_His p ON p.BillNo=o.BillNo '+@SqlSumParam+'GROUP BY o.BillNo '
	
IF @Stt <> '' AND @Stt <> '0,1,2'
BEGIN
	SET @Sql += '
	SELECT o.* FROM ( '
	IF @IsHistory = 0 
	BEGIN
		SET @Sql += @SqlHead + @StrStt + '
		FROM PD_PchOrdBill b ' + @SqlJoin + @SqlParam + ') AS o ' + @InnerStt + '
	) '
		SET @SqlSum = @SqlSumHead + @SqlSumOther
	END
	ELSE
	BEGIN
		SET @Sql += @SqlHead + @StrStt + '
		FROM PD_PchOrdBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + ',2[Stt] 
		FROM PD_PchOrdBill_His b ' + @SqlJoin + @SqlParam_His + '
	) AS o ' + @InnerStt + '
) '
		SET @SqlSum = @SqlSumHead + @SqlSumOther + '
				UNION ALL ' + @SqlSumHead_His + @SqlSumOther_His
	END
	SET @Sql += '
	SELECT * INTO #tempbo 
	FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillNo) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
	WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	SELECT o.*,s.DHQty,s.DHTotal,b.BtypeName,w.WhsName,e.ElyName,d.DeptName,CASE o.StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow]
	,CASE o.IsDraft WHEN 0 THEN ''已生效'' ELSE ''未生效'' END [IsDraftShow] 
	,CASE o.AuditStatus WHEN 0 THEN ''无审核流程'' 
						WHEN 1 THEN ''未达审核条件'' 
						WHEN 2 THEN ''原始单据'' 
						WHEN 3 THEN ''审核中'' 
						WHEN 4 THEN ''审核通过''
						ELSE ''审核不通过'' END AS AuditStatusShow
	FROM #tempbo o 
	INNER JOIN BD_Btype b ON b.BTypeID=o.BTypeID AND B.Tel LIKE ''%' + @BtypePhone+'%'' AND B.Adress LIKE ''%' + @BtypeAddr+'%''
	INNER JOIN BD_Whs w ON w.WhsID=o.WhsID 
	INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
	INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
	INNER JOIN (' + @SqlSum + ') s ON s.BillNo = o.BillNo 
	DROP TABLE #tempbo '
END
ELSE
BEGIN
	IF @IsHistory = 0 
	BEGIN
		SET @Sql += @SqlHead + '
		FROM PD_PchOrdBill b ' + @SqlJoin + @SqlParam + '
	) '
		SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,1)[Stt] ' + @SqlSumOther
	END
	ELSE
	BEGIN
		SET @Sql += @SqlHead + '
		FROM PD_PchOrdBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + '
		FROM PD_PchOrdBill_His b ' + @SqlJoin + @SqlParam_His + '
	) '
		SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,1)[Stt] ' + @SqlSumOther + '
				UNION ALL 
				' + @SqlSumHead_His + ',dbo.UF_PD_GetBillStt(o.BillNo,1)[Stt] ' + @SqlSumOther_His
	END
	SET @Sql += '
	SELECT * INTO #tempbo 
	FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillNo) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
	WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	SELECT o.*,s.Stt,s.DHQty,s.DHTotal,b.BtypeName,w.WhsName,e.ElyName,d.DeptName
		,CASE o.StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow]
		,CASE o.IsDraft WHEN 0 THEN ''已生效'' ELSE ''未生效'' END [IsDraftShow] 
	,CASE o.AuditStatus WHEN 0 THEN ''无审核流程'' 
						WHEN 1 THEN ''未达审核条件'' 
						WHEN 2 THEN ''原始单据'' 
						WHEN 3 THEN ''审核中'' 
						WHEN 4 THEN ''审核通过''
						ELSE ''审核不通过'' END AS AuditStatusShow
	FROM #tempbo o 
	INNER JOIN BD_Btype b ON b.BTypeID=o.BTypeID AND B.Tel LIKE ''%' + @BtypePhone+'%'' AND B.Adress LIKE ''%' + @BtypeAddr+'%''
	INNER JOIN BD_Whs w ON w.WhsID=o.WhsID 
	INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
	INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
	INNER JOIN (' + @SqlSum + ') s ON s.BillNo = o.BillNo 
	DROP TABLE #tempbo '
END
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--PRINT @Sql

EXEC SP_EXECUTESQL @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@DlvStartDate VARCHAR(50),@DlvEndDate VARCHAR(50),@BillCode VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@Stt VARCHAR(50),@StopTag INT=9,@IsDraft INT=9,@AuditStatus VARCHAR(100),@OperatorID INT, @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',@PageNo,@PageSize,@BillStartDate,@BillEndDate,@DlvStartDate,@DlvEndDate,@BillCode,@BTypeID,@DeptID,@ElyID,@WhsID,@GoodsID,@Description,@Summary,@Stt,@StopTag,@IsDraft,@AuditStatus,@OperatorID, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch


END


GO








/****** Object:  StoredProcedure [UP_PD_QueryBuySummaryList]    Script Date: 06/23/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryBuySummaryList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryBuySummaryList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryBuySummaryList]    Script Date: 06/23/2014 15:42:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-09-14
	描述：采购汇总统计
	××××××××××××××××××
	修改：sunzhiyuan
	日期：2015-3-31
	修改描述：63行：取消归档数据判断
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryBuySummaryList]
(			   
	@pageNo INT=1,					--页码
	@pageSize INT=10,				--分页数
	@BillDateType INT=1,			--单据日期类型:1=录单日期,2=制单日期,3=过账日期  对应BillDate,CreateTime,PosTime
	@BillStartDate DATETIME,		--单据开始日期
	@BillEndDate DATETIME,			--单据结束日期
	@BuyBillIn INT=1,				--采购入库单勾选状态
	@BuyBillOut INT=1,				--采购退货单勾选状态
	@BTypeID VARCHAR(1000) = '',	--往来单位
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@CreatorID VARCHAR(1000)='',    --制单人
	@WhsID VARCHAR(1000) = '',		--仓库
	@GoodsID VARCHAR(1000) = '',	--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(20) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(50) = '',	--商品名称
	---------------update sunzhiyuan 20150906--------------------
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	---------------update sunzhiyuan 20150906--------------------
	@SummaryMatch INT=0,			--摘要配置模式:0=包含,1=等于
	@Summary VARCHAR(256) = '',		--摘要
	@DescriptionMatch INT=0,		--说明配置模式:0=包含,1=等于
	@Description VARCHAR(100) = '', --说明
	@RemarkMatch INT=0,				--明细备注配置模式:0=包含,1=等于
	@Remark VARCHAR(100) = '',		--明细备注
	@GiftState INT=9,				--赠品状态：0=全部,1=是,2=否
	@CollectType1 INT=0,			--汇总条件一:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer1 INT=0,					--汇总层级一:0:空 1-5:XX分类层级 6:XX
	@CollectType2 INT=0,			--汇总条件二:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer2 INT=0,					--汇总层级二:0:空 1-5:XX分类层级 6:XX
	@OrderType1 INT=0,				--排序条件一:1=商品分类编码,2=商品分类名称,3=商品编码,4=商品名称,5=往来单位分类编码,6=往来单位分类名称,7=往来单位编码,8=往来单位名称,9=仓库分类编码,10=仓库分类名称,11=仓库编码,12=仓库名称,13=地区编码,14=地区名称,15=部门编码,16=部门名称,17=职员编码,18=职员名称,19=数量,20=采购均价,21=采购金额,22=赠品数量
	@OrderSeq1 INT=1,				--排序规则：1=升序，2=降序
	@OrderType2 INT=0,				--排序条件一:1=商品分类编码,2=商品分类名称,3=商品编码,4=商品名称,5=往来单位分类编码,6=往来单位分类名称,7=往来单位编码,8=往来单位名称,9=仓库分类编码,10=仓库分类名称,11=仓库编码,12=仓库名称,13=地区编码,14=地区名称,15=部门编码,16=部门名称,17=职员编码,18=职员名称,19=数量,20=采购均价,21=采购金额,22=赠品数量
	@OrderSeq2 INT=1,				--排序规则：1=升序，2=降序
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT = 0,			--操作员ID
	@IsContainDiscountTotal BIT = 0,       -- 是否包含优惠金额
	@SumOrNot INT = 1				--是否为合计形式
)
AS
SET NOCOUNT ON
BEGIN
	-- 当日期类型为业务日期的场合，做归档日期的范围判断
	IF @BillDateType = 1
	BEGIN
		DECLARE @Re INT 
		EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
		IF( @Re=1 )RETURN @Re;
	END

DECLARE @Sql NVARCHAR(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlOrder VARCHAR(100)=''
		,@SumData NVARCHAR(MAX),@VbSumHead VARCHAR(50)='',@SumHead NVARCHAR(MAX),@SumHeadFH NVARCHAR(MAX),@SumJoin NVARCHAR(MAX)='',@SumParam NVARCHAR(MAX),@VbSumG VARCHAR(300)=''
		,@Sql_PPB NVARCHAR(MAX),@Sql_PPB_His NVARCHAR(MAX),@Sql_PRB NVARCHAR(MAX),@Sql_PRB_His NVARCHAR(MAX)
		,@BillData NVARCHAR(MAX),@VbBDHead NVARCHAR(MAX)='',@BDHead NVARCHAR(MAX),@VbSumBDHead VARCHAR(50)='',@VbBDJoin VARCHAR(400)='',@CFBDJoin NVARCHAR(MAX)='',@VbSumBDG VARCHAR(300)=''
		,@AVGPrice NVARCHAR(MAX)
		,@bg1 VARCHAR(500),@bt1 VARCHAR(500),@bw1 VARCHAR(500),@ba1 VARCHAR(500),@bd1 VARCHAR(500)
		,@bg2 VARCHAR(500),@bt2 VARCHAR(500),@bw2 VARCHAR(500),@ba2 VARCHAR(500),@bd2 VARCHAR(500)
		,@BtypeLimit INT=0,@KtypeLimit INT=0 
DECLARE @DiscountCol NVARCHAR(MAX) = '',@DiscountColRet NVARCHAR(MAX) = '',@DiscountColGift NVARCHAR(MAX) = '',
		@DiscountGroupCol NVARCHAR(MAX) = '',
		@DiscountBaseCol NVARCHAR(MAX) = '',@SurceCol NVARCHAR(MAX) = '',@SurceGroupCol NVARCHAR(MAX) = '',
		@DiscountSumCol NVARCHAR(MAX) = ''
--INNER JOIN BEGIN
IF @BTypeID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _BType ON _BType.typeid = p.BTypeID '
IF @DeptID <> ''
BEGIN
	SET @SumJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=p.DeptID '
	--SET @Sql += 'DECLARE @TVP_Dept AS [TVP_Type] 
	--INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
	--SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
	--INNER JOIN BD_Dept cd ON cd.[Path] LIKE d.[Path] + ''%''
	--WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, '','') _Dept WHERE _Dept.typeid = d.DeptID) '
END
IF @ElyID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = p.ElyID '
IF @CreatorID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@CreatorID, '','') _PEly ON _PEly.typeid = p.Creator '
IF @WhsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = p.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SumJoin += '
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=p.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SumJoin += '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=p.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SumJoin +='
	INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=p.BTypeID '
	END
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SumJoin +='
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=p.WhsID '
	END
END
*/
IF @GoodsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID '
IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
	SET @SumJoin +=' 
	INNER JOIN BD_Goods g ON g.GoodsID=dtl.GoodsID '
IF @BarCode <> ''
BEGIN 
	SET @SumJoin += ' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID AND pri.UnitID = 1 '
END 
--INNER JOIN END

--条件BEGIN
IF @BillDateType=1
	SET @SqlDTStr='dtl.BillDate'
IF @BillDateType=2
	SET @SqlDTStr='p.CreateTime'	
IF @BillDateType=3
	SET @SqlDTStr='p.PosTime'	
SET @SumParam = '
	WHERE '+@SqlDTStr+' BETWEEN @BillStartDate AND @BillEndDate AND p.IsDraft=0 AND p.Red=0 '
IF @GiftState<>9 
	SET @SumParam += 'AND Gift=@GiftState '
IF @Summary <> ''
BEGIN
	IF @SummaryMatch=0 SET @SumParam += 'AND p.Summary LIKE ''%''+@Summary+''%'' '  
	IF @SummaryMatch=1 SET @SumParam += 'AND p.Summary=@Summary '  
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch=0 SET @SumParam += 'AND p.[Description] LIKE ''%''+@Description+''%'' '  
	IF @DescriptionMatch=1 SET @SumParam += 'AND p.[Description]=@Description '  
END
IF @Remark <> ''
BEGIN
	IF @RemarkMatch=0 SET @SumParam += 'AND dtl.Remark LIKE ''%''+@Remark+''%'' '   
	IF @RemarkMatch=1 SET @SumParam += 'AND dtl.Remark=@Remark '  
END
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0 SET @SumParam += 'AND g.GoodsNo LIKE ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch=1 SET @SumParam += 'AND g.GoodsNo=@GoodsNo '  
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0 SET @SumParam += 'AND g.GoodsName LIKE ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch=1 SET @SumParam += 'AND g.GoodsName=@GoodsName '  
END
--商品型号	
IF @Model <> ''      
   BEGIN 
	   IF @ModelMatch = 0
		   SET @SumParam += N' AND g.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @SumParam += N' AND g.Model = @Model ' 
   END  
--商品简名     
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @SumParam += N' AND g.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @SumParam += N' AND g.GoodsAbbName = @GoodsAbbName ' 
END     
--商品品牌  
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @SumParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @SumParam += N' AND g.Brand = @Brand ' 
END  
--商品规格  
IF @Spec <> ''        
   BEGIN 
	   IF @SpecMatch = 0
		   SET @SumParam += N' AND g.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @SumParam += N' AND g.Spec = @Spec '  
   END
--商品条码
IF @BarCode <> ''      
BEGIN 
	IF @BarCodeMatch = 0
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=dtl.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=dtl.GoodsID)'
END
--条件END

--
--商品分类
SET @bg1 = '
			SELECT pbs.BaseID,[_bg].GoodsID 
			FROM (
				SELECT GT.GoodsTypeID AS BaseID,T.GoodsTypeID FROM BD_Goods_Type GT 
				INNER JOIN BD_Goods_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) pbs
			INNER JOIN BD_Goods _bg ON [_bg].GoodsTypeID = pbs.GoodsTypeID '

--往来单位分类
SET @bt1 = '
			SELECT bbs.BaseID,[_bt].BTypeID 
			FROM (
				SELECT GT.BtypeTypeID AS BaseID,T.BtypeTypeID FROM BD_Btype_Type GT 
				INNER JOIN BD_Btype_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) bbs
			INNER JOIN BD_Btype _bt ON [_bt].BtypeTypeID = bbs.BtypeTypeID '

--仓库分类
SET @bw1 = '
			SELECT wbs.BaseID,[_bw].WhsID 
			FROM (
				SELECT GT.WhsTypeID AS BaseID,T.WhsTypeID FROM BD_Whs_Type GT 
				INNER JOIN BD_Whs_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) wbs
			INNER JOIN BD_Whs _bw ON [_bw].WhsTypeID = wbs.WhsTypeID '

--地区分类
SET @ba1 = '
			SELECT dbs.BaseID,_ba.AreaID 
			FROM (
				SELECT GT.AreaID AS BaseID,T.AreaID 
				FROM BD_Area GT 
				INNER JOIN BD_Area T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Area _ba ON [_ba].AreaID = dbs.AreaID '

--部门分类
SET @bd1 = '
			SELECT dbs.BaseID,_bd.DeptID 
			FROM (
				SELECT GT.DeptID AS BaseID,T.DeptID 
				FROM BD_Dept GT 
				INNER JOIN BD_Dept T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Dept _bd ON [_bd].DeptID = dbs.DeptID '
--

-----汇总层级一-----begin
IF @CollectType1 <> 0
BEGIN
	IF @CollectType1 = 1
	BEGIN
		SET @VbSumHead += ',dtl.GoodsID '
		SET @VbSumG += 'dtl.GoodsID '
		IF @Layer1 <> 6 --汇总层级:商品分类1-5
		BEGIN
			SET @VbBDHead += ',gt.TypeCode[Code1],gt.TypeName[Name1] '
			SET @VbSumBDHead += ',pbs.BaseID[ID1] '
			SET @VbSumBDG += 'pbs.BaseID '
			SET @VbBDJoin += '
		INNER JOIN BD_Goods_Type gt ON gt.GoodsTypeID=o.ID1 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bg1+'
		) pbs ON pbs.GoodsID = sd.GoodsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',g.GoodsNo[Code1],g.GoodsName[Name1],g.Model[Model1],g.GoodsAbbName[GoodsAbbName1],g.Brand[Brand1],g.Spec[Spec1],pri.BarCode[BarCode1]  '
			SET @VbSumBDHead += ',sd.GoodsID[ID1] '
			SET @VbSumBDG += 'sd.GoodsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID1 
	INNER JOIN BD_Goods_Price pri ON o.ID1 = pri.GoodsID AND pri.UnitID = 1 '
		END
	END
	IF @CollectType1 = 2
	BEGIN
		SET @VbSumHead += ',p.BTypeID '
		SET @VbSumG += 'p.BTypeID '
		IF @Layer1 <> 6 --汇总层级:往来单位分类1-5
		BEGIN
			SET @VbBDHead += ',bt.TypeCode[Code1],bt.TypeName[Name1] '
			SET @VbSumBDHead += ',bbs.BaseID[ID1] '
			SET @VbSumBDG += 'bbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_BType_Type bt ON bt.BTypeTypeID=o.ID1 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bt1+'
		) bbs ON bbs.BTypeID = sd.BTypeID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',b.BTypeCode[Code1],b.BTypeName[Name1] '
			SET @VbSumBDHead += ',sd.BTypeID[ID1] '
			SET @VbSumBDG += 'sd.BTypeID '
			SET @VbBDJoin += '
	INNER JOIN BD_BType b ON b.BTypeID=o.ID1 '
		END
	END
	IF @CollectType1 = 3
	BEGIN
		SET @VbSumHead += ',dtl.WhsID '
		SET @VbSumG += 'dtl.WhsID '
		IF @Layer1 <> 6 --汇总层级:仓库分类1-5
		BEGIN
			SET @VbBDHead += ',wt.TypeCode[Code1],wt.TypeName[Name1] '
			SET @VbSumBDHead += ',kbs.BaseID[ID1] '
			SET @VbSumBDG += 'kbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs_Type wt ON wt.WhsTypeID=o.ID1 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bw1+'
		) kbs ON kbs.WhsID = sd.WhsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',w.WhsNO[Code1],w.WhsName[Name1] '
			SET @VbSumBDHead += ',sd.WhsID[ID1] '
			SET @VbSumBDG += 'sd.WhsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs w ON w.WhsID=o.ID1 '
		END
	END
	IF @CollectType1 = 4
	BEGIN
		SET @VbSumHead += ',bt.AreaID '
		SET @SumJoin += '
	INNER JOIN BD_Btype bt ON bt.BTypeID = p.BTypeID '
		SET @VbSumG += 'bt.AreaID '
		SET @VbBDHead += ',a.AreaNO[Code1],a.AreaName[Name1] '
		SET @VbBDJoin += '
	INNER JOIN BD_Area a ON a.AreaID=o.ID1 '
		IF @Layer1<>5 
		BEGIN
			SET @VbSumBDHead += ',abs.BaseID[ID1] '
			SET @VbSumBDG += 'abs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@ba1+'
		) abs ON abs.AreaID = sd.AreaID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.AreaID[ID1] '
			SET @VbSumBDG += 'sd.AreaID '
		END
	END
	IF @CollectType1 = 5
	BEGIN
		SET @VbSumHead += ',p.DeptID '
		SET @VbSumG += 'p.DeptID '
		SET @VbBDHead += ',d.DeptCode[Code1],d.DeptName[Name1] '
		SET @VbBDJoin += '
	INNER JOIN BD_Dept d ON d.DeptID=o.ID1 '
		IF @Layer1<>5 
		BEGIN
			SET @VbSumBDHead += ',dbs.BaseID[ID1] '
			SET @VbSumBDG += 'dbs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@bd1+'
		) dbs ON dbs.DeptID = sd.DeptID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.DeptID[ID1] '
			SET @VbSumBDG += 'sd.DeptID '
		END
	END
	IF @CollectType1 = 6
	BEGIN
		SET @VbSumHead += ',p.ElyID '
		SET @VbSumG += 'p.ElyID '
		SET @VbBDHead += ',e.ElyCode[Code1],e.ElyName[Name1] '
		SET @VbSumBDHead += ',sd.ElyID[ID1] '
		SET @VbSumBDG += 'sd.ElyID '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee e ON e.ElyID=o.ID1 '
	END
	IF @CollectType1 = 7
	BEGIN
		SET @VbSumHead += ',p.Creator '
		SET @VbSumG += 'p.Creator '
		SET @VbBDHead += ',pe.ElyCode[Code1],pe.ElyName[Name1] '
		SET @VbSumBDHead += ',sd.Creator[ID1] '
		SET @VbSumBDG += 'sd.Creator '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee pe ON pe.ElyID=o.ID1 '
	END
END
-----汇总层级一-----END
--
--商品分类
SET @bg2 = '
			SELECT pbs.BaseID,[_bg].GoodsID 
			FROM (
				SELECT GT.GoodsTypeID AS BaseID,T.GoodsTypeID FROM BD_Goods_Type GT 
				INNER JOIN BD_Goods_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) pbs
			INNER JOIN BD_Goods _bg ON [_bg].GoodsTypeID = pbs.GoodsTypeID '

--往来单位分类
SET @bt2 = '
			SELECT bbs.BaseID,[_bt].BTypeID 
			FROM (
				SELECT GT.BtypeTypeID AS BaseID,T.BtypeTypeID FROM BD_Btype_Type GT 
				INNER JOIN BD_Btype_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) bbs
			INNER JOIN BD_Btype _bt ON [_bt].BtypeTypeID = bbs.BtypeTypeID '

--仓库分类
SET @bw2 = '
			SELECT wbs.BaseID,[_bw].WhsID 
			FROM (
				SELECT GT.WhsTypeID AS BaseID,T.WhsTypeID FROM BD_Whs_Type GT 
				INNER JOIN BD_Whs_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) wbs
			INNER JOIN BD_Whs _bw ON [_bw].WhsTypeID = wbs.WhsTypeID '

--地区分类
SET @ba2 = '
			SELECT dbs.BaseID,_ba.AreaID 
			FROM (
				SELECT GT.AreaID AS BaseID,T.AreaID 
				FROM BD_Area GT 
				INNER JOIN BD_Area T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Area _ba ON [_ba].AreaID = dbs.AreaID '

--部门分类
SET @bd2 = '
			SELECT dbs.BaseID,_bd.DeptID 
			FROM (
				SELECT GT.DeptID AS BaseID,T.DeptID 
				FROM BD_Dept GT 
				INNER JOIN BD_Dept T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Dept _bd ON [_bd].DeptID = dbs.DeptID '
--
-----汇总层级二-----BEGIN
IF @CollectType2 <> 0
BEGIN
	IF @CollectType2 = 1
	BEGIN
		SET @VbSumHead += ',dtl.GoodsID '
		SET @VbSumG += ',dtl.GoodsID '
		IF @Layer2 <> 6 --汇总层级:商品分类1-5
		BEGIN
			SET @VbBDHead += ',gt.TypeCode[Code2],gt.TypeName[Name2] '
			SET @VbSumBDHead += ',pbs.BaseID[ID2] '
			SET @VbSumBDG += ',pbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_Goods_Type gt ON gt.GoodsTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bg2+'
		) pbs ON pbs.GoodsID = sd.GoodsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',g.GoodsNo[Code2],g.GoodsName[Name2],g.Model[Model2],g.GoodsAbbName[GoodsAbbName2],g.Brand[Brand2],g.Spec[Spec2],pri.BarCode[BarCode2] '
			SET @VbSumBDHead += ',sd.GoodsID[ID2] '
			SET @VbSumBDG += ',sd.GoodsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID2 
	INNER JOIN BD_Goods_Price pri ON o.ID2 = pri.GoodsID AND pri.UnitID = 1 '
		END
	END
	IF @CollectType2 = 2
	BEGIN
		SET @VbSumHead += ',p.BTypeID '
		SET @VbSumG += ',p.BTypeID '
		IF @Layer2 <> 6 --汇总层级:往来单位分类1-5
		BEGIN
			SET @VbBDHead += ',bt.TypeCode[Code2],bt.TypeName[Name2] '
			SET @VbSumBDHead += ',bbs.BaseID[ID2] '
			SET @VbSumBDG += ',bbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_BType_Type bt ON bt.BTypeTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bt2+'
		) bbs ON bbs.BTypeID = sd.BTypeID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',b.BTypeCode[Code2],b.BTypeName[Name2] '
			SET @VbSumBDHead += ',sd.BTypeID[ID2] '
			SET @VbSumBDG += ',sd.BTypeID '
			SET @VbBDJoin += '
	INNER JOIN BD_BType b ON b.BTypeID=o.ID2 '
		END
	END
	IF @CollectType2 = 3
	BEGIN
		SET @VbSumHead += ',dtl.WhsID '
		SET @VbSumG += ',dtl.WhsID '
		IF @Layer2 <> 6 --汇总层级:仓库分类1-5
		BEGIN
			SET @VbBDHead += ',wt.TypeCode[Code2],wt.TypeName[Name2] '
			SET @VbSumBDHead += ',kbs.BaseID[ID2] '
			SET @VbSumBDG += ',kbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs_Type wt ON wt.WhsTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bw2+'
		) kbs ON kbs.WhsID = sd.WhsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',w.WhsNO[Code2],w.WhsName[Name2] '
			SET @VbSumBDHead += ',sd.WhsID[ID2] '
			SET @VbSumBDG += ',sd.WhsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs w ON w.WhsID=o.ID2 '
		END
	END
	IF @CollectType2 = 4
	BEGIN
		SET @VbSumHead += ',bt.AreaID '
		SET @SumJoin += '
	INNER JOIN BD_Btype bt ON bt.BTypeID = p.BTypeID '
		SET @VbSumG += ',bt.AreaID '
		SET @VbBDHead += ',a.AreaNO[Code2],a.AreaName[Name2] '
		SET @VbBDJoin += '
	INNER JOIN BD_Area a ON a.AreaID=o.ID2 '
		IF @Layer2<>5 
		BEGIN
			SET @VbSumBDHead += ',abs.BaseID[ID2] '
			SET @VbSumBDG += ',abs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@ba2+'
		) abs ON abs.AreaID = sd.AreaID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.AreaID[ID2] '
			SET @VbSumBDG += ',sd.AreaID '
		END
	END
	IF @CollectType2 = 5
	BEGIN
		SET @VbSumHead += ',p.DeptID '
		SET @VbSumG += ',p.DeptID '
		SET @VbBDHead += ',d.DeptCode[Code2],d.DeptName[Name2] '
		SET @VbBDJoin += '
	INNER JOIN BD_Dept d ON d.DeptID=o.ID2 '
		IF @Layer2<>5 
		BEGIN
			SET @VbSumBDHead += ',dbs.BaseID[ID2] '
			SET @VbSumBDG += ',dbs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@bd2+'
		) dbs ON dbs.DeptID = sd.DeptID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.DeptID[ID2] '
			SET @VbSumBDG += ',sd.DeptID '
		END
	END
	IF @CollectType2 = 6
	BEGIN
		SET @VbSumHead += ',p.ElyID '
		SET @VbSumG += ',p.ElyID '
		SET @VbBDHead += ',e.ElyCode[Code2],e.ElyName[Name2] '
		SET @VbSumBDHead += ',sd.ElyID[ID2] '
		SET @VbSumBDG += ',sd.ElyID '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee e ON e.ElyID=o.ID2 '
	END
	IF @CollectType2 = 7
	BEGIN
		SET @VbSumHead += ',p.Creator '
		SET @VbSumG += ',p.Creator '
		SET @VbBDHead += ',pe.ElyCode[Code2],pe.ElyName[Name2] '
		SET @VbSumBDHead += ',sd.Creator[ID2] '
		SET @VbSumBDG += ',sd.Creator '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee pe ON pe.ElyID=o.ID2 '
	END
END
-----汇总层级二-----END
IF @VbSumG <> ''
	SET @VbSumG = '
	GROUP BY ' + @VbSumG
IF @VbSumBDG <> ''
	SET @VbSumBDG = '
	GROUP BY ' + @VbSumBDG

--排序BEGIN
SET @SqlOrder=''
IF @OrderType1<>0
BEGIN
	IF (@CollectType1 = 1 AND @OrderType1 IN (1,3)) OR (@CollectType1 = 2 AND @OrderType1 IN (5,7)) OR (@CollectType1 = 3 AND @OrderType1 IN (9,11)) OR (@CollectType1 = 4 AND @OrderType1 = 13) OR (@CollectType1 = 5 AND @OrderType1 = 15) OR (@CollectType1 = 6 AND @OrderType1 = 17) OR (@CollectType1 = 7 AND @OrderType1 = 29)
		SET @SqlOrder += 'Code1'
	IF (@CollectType1 = 1 AND @OrderType1 IN (2,4)) OR (@CollectType1 = 2 AND @OrderType1 IN (6,8)) OR (@CollectType1 = 3 AND @OrderType1 IN (10,12)) OR (@CollectType1 = 4 AND @OrderType1 = 14) OR (@CollectType1 = 5 AND @OrderType1 = 16) OR (@CollectType1 = 6 AND @OrderType1 = 18) OR (@CollectType1 = 7 AND @OrderType1 = 30)
		SET @SqlOrder += 'Name1'
	IF (@CollectType2 = 1 AND @OrderType1 IN (1,3)) OR (@CollectType2 = 2 AND @OrderType1 IN (5,7)) OR (@CollectType2 = 3 AND @OrderType1 IN (9,11)) OR (@CollectType2 = 4 AND @OrderType1 = 13) OR (@CollectType2 = 5 AND @OrderType1 = 15) OR (@CollectType2 = 6 AND @OrderType1 = 17) OR (@CollectType2 = 7 AND @OrderType1 = 29)
		SET @SqlOrder += 'Code2'
	IF (@CollectType2 = 1 AND @OrderType1 IN (2,4)) OR (@CollectType2 = 2 AND @OrderType1 IN (6,8)) OR (@CollectType2 = 3 AND @OrderType1 IN (10,12)) OR (@CollectType2 = 4 AND @OrderType1 = 14) OR (@CollectType2 = 5 AND @OrderType1 = 16) OR (@CollectType2 = 6 AND @OrderType1 = 18) OR (@CollectType2 = 7 AND @OrderType1 = 30)
		SET @SqlOrder += 'Name2'
	IF @OrderType1=19 SET @SqlOrder+='BSQty' IF @OrderType1=20 SET @SqlOrder+='AVGPrice' IF @OrderType1=21 SET @SqlOrder+='BuyTotal' IF @OrderType1=22 SET @SqlOrder+='GiftQty' 
	IF @OrderSeq1=2 SET @SqlOrder+= ' DESC'
END
IF @OrderType2<>0
BEGIN
	IF (@CollectType1 = 1 AND @OrderType2 IN (1,3)) OR (@CollectType1 = 2 AND @OrderType2 IN (5,7)) OR (@CollectType1 = 3 AND @OrderType2 IN (9,11)) OR (@CollectType1 = 4 AND @OrderType2 = 13) OR (@CollectType1 = 5 AND @OrderType2 = 15) OR (@CollectType1 = 6 AND @OrderType2 = 17) OR (@CollectType1 = 7 AND @OrderType2 = 29)
		SET @SqlOrder += ',Code1'
	IF (@CollectType1 = 1 AND @OrderType2 IN (2,4)) OR (@CollectType1 = 2 AND @OrderType2 IN (6,8)) OR (@CollectType1 = 3 AND @OrderType2 IN (10,12)) OR (@CollectType1 = 4 AND @OrderType2 = 14) OR (@CollectType1 = 5 AND @OrderType2 = 16) OR (@CollectType1 = 6 AND @OrderType2 = 18) OR (@CollectType1 = 7 AND @OrderType2 = 30)
		SET @SqlOrder += ',Name1'
	IF (@CollectType2 = 1 AND @OrderType2 IN (1,3)) OR (@CollectType2 = 2 AND @OrderType2 IN (5,7)) OR (@CollectType2 = 3 AND @OrderType2 IN (9,11)) OR (@CollectType2 = 4 AND @OrderType2 = 13) OR (@CollectType2 = 5 AND @OrderType2 = 15) OR (@CollectType2 = 6 AND @OrderType2 = 17) OR (@CollectType2 = 7 AND @OrderType2 = 29)
		SET @SqlOrder += ',Code2'
	IF (@CollectType2 = 1 AND @OrderType2 IN (2,4)) OR (@CollectType2 = 2 AND @OrderType2 IN (6,8)) OR (@CollectType2 = 3 AND @OrderType2 IN (10,12)) OR (@CollectType2 = 4 AND @OrderType2 = 14) OR (@CollectType2 = 5 AND @OrderType2 = 16) OR (@CollectType2 = 6 AND @OrderType2 = 18) OR (@CollectType2 = 7 AND @OrderType2 = 30)
		SET @SqlOrder += ',Name2'
	IF @OrderType2=19 SET @SqlOrder+=',BSQty' IF @OrderType2=20 SET @SqlOrder+=',AVGPrice' IF @OrderType2=21 SET @SqlOrder+=',BuyTotal' IF @OrderType2=22 SET @SqlOrder+=',GiftQty'
	IF @OrderSeq2=2 SET @SqlOrder+= ' DESC'
END
IF @SqlOrder='' SET @SqlOrder='BSQty'
--排序END

-- 是否包含优惠金额
IF @IsContainDiscountTotal = 1
BEGIN
	SET @DiscountCol += ',Privilege AS DiscountTotal'
	SET @DiscountColRet += ',Privilege*-1 AS DiscountTotal'
	SET @DiscountColGift += ',0 AS DiscountTotal'
	SET @DiscountGroupCol += ',Privilege'
	SET @DiscountBaseCol += ',SUM(sd.DiscountTotal)[DiscountTotal]'
	SET @SurceCol += ',(o.BuyTotal-o.DiscountTotal)[BuyTotalByDiscount]'
	SET @DiscountSumCol += ',SUM(o.DiscountTotal)[DiscountTotal],SUM(o.BuyTotal-o.DiscountTotal)[BuyTotalByDiscount]'
END

SET @SumData=';WITH SumData AS('

SET @SumHead='SUM(dtl.BSQty)[BSQtyST],SUM(dtl.TaxTotal)[BuyTotalST],SUM(dtl.Freight)[FreightST],SUM(dtl.InTotal)[InTotalST]'
SET @SumHeadFH='SUM(dtl.BSQty)*-1[BSQtyST],SUM(dtl.TaxTotal)*-1[BuyTotalST],0[FreightST],SUM(dtl.GoodsCostTotal)*-1[InTotalST]'

IF NOT (@BuyBillIn<>0 AND @BuyBillOut<>0)
	SET @SumHeadFH='SUM(dtl.BSQty)[BSQtyST],SUM(dtl.TaxTotal)[BuyTotalST],0[FreightST],SUM(dtl.GoodsCostTotal)[InTotalST]'
SET @Sql_PPB='
	SELECT ' + @SumHead + @DiscountColGift +'
	,SUM(dtl.BSQty)[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchBill p 
	INNER JOIN PD_PchDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=1' + @VbSumG + '
	UNION ALL 
	SELECT ' + @SumHead + @DiscountCol +',0[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchBill p 
	INNER JOIN PD_PchDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=0' + @VbSumG + @DiscountGroupCol
SET @Sql_PPB_His='
	SELECT ' + @SumHead + @DiscountColGift +'
	,SUM(dtl.BSQty)[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchBill_His p 
	INNER JOIN PD_PchDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=1' + @VbSumG + '
	UNION ALL 
	SELECT ' + @SumHead + @DiscountCol +',0[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchBill_His p 
	INNER JOIN PD_PchDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=0' + @VbSumG + @DiscountGroupCol
SET @Sql_PRB='
	SELECT ' + @SumHeadFH + @DiscountColGift +'
	,SUM(dtl.BSQty)*-1[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchRetBill p 
	INNER JOIN PD_PchRetDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=1' + @VbSumG + '
	UNION ALL 
	SELECT ' + @SumHeadFH + @DiscountColRet +',0[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchRetBill p 
	INNER JOIN PD_PchRetDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=0' + @VbSumG + @DiscountGroupCol
SET @Sql_PRB_His='
	SELECT ' + @SumHeadFH + @DiscountColGift +'
	,SUM(dtl.BSQty)*-1[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchRetBill_His p 
	INNER JOIN PD_PchRetDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=1' + @VbSumG + '
	UNION ALL 
	SELECT ' + @SumHeadFH + @DiscountColRet +',0[GiftQtyST] ' + @VbSumHead + '
	FROM PD_PchRetBill_His p 
	INNER JOIN PD_PchRetDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + 'AND dtl.Gift=0' + @VbSumG + @DiscountGroupCol

IF @IsHistory = 0
BEGIN
	IF @BuyBillIn<>0 AND @BuyBillOut<>0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL '+@Sql_PRB+')'
	END
	IF @BuyBillIn<>0 AND @BuyBillOut=0
	BEGIN
		SET @SumData+=@Sql_PPB+')'
	END
	IF @BuyBillIn=0 AND @BuyBillOut<>0
	BEGIN
		SET @SumData+=@Sql_PRB+')'
	END
END
ELSE
BEGIN
	IF @BuyBillIn<>0 AND @BuyBillOut<>0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL '+@Sql_PRB+'
	UNION ALL'+@Sql_PPB_His+'
	UNION ALL '+@Sql_PRB_His+')'
	END
	IF @BuyBillIn<>0 AND @BuyBillOut=0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL'+@Sql_PPB_His+')'
	END
	IF @BuyBillIn=0 AND @BuyBillOut<>0
	BEGIN
		SET @SumData+=@Sql_PRB+'
	UNION ALL'+@Sql_PRB_His+')'
	END
END

SET @BillData = '
,BillData AS( 
	SELECT o.*'
	
SET @BDHead='SUM(sd.BSQtyST)[BSQty],SUM(sd.BuyTotalST)[BuyTotal],SUM(sd.GiftQtyST)[GiftQty],SUM(sd.FreightST)[Freight],SUM(sd.InTotalST)[InTotal] '

SET @AVGPrice = '
	,CASE WHEN o.BSQty=0 THEN NULL ELSE ABS(CAST( CAST(o.BuyTotal AS FLOAT)/o.BSQty AS DECIMAL(20,8) )) END [AVGPrice] '
IF @OrderType1 = 20 OR @OrderType2 = 20 SET @VbBDHead += @AVGPrice
SET @BillData += @VbBDHead + '
	FROM ( 
		SELECT ' + @BDHead + @VbSumBDHead + @DiscountBaseCol +'
		FROM SumData sd ' + @CFBDJoin + @VbSumBDG + '
	) o ' + @VbBDJoin + '
)'

IF @SumOrNot = 0
BEGIN

	SET @Sql += 'SET NOCOUNT ON;
	' + @SumData + @BillData + '
	,PageData as(
		SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ' + @SqlOrder + ') AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData) AS B
		WHERE ROWID>(@pageNo-1)*@pageSize 
		AND ROWID<=@pageNo*@pageSize 
	)

	SELECT o.*'+ @SurceCol +',CASE WHEN o.BSQty=0 THEN NULL ELSE ABS(CAST( CAST(o.InTotal AS FLOAT)/o.BSQty AS DECIMAL(20,8) )) END [InPrice] '
	IF @OrderType1 <> 20 AND @OrderType2 <> 20
		SET @Sql +='
		,CASE WHEN o.BSQty=0 THEN NULL ELSE ABS(CAST( CAST(o.BuyTotal AS FLOAT)/o.BSQty AS DECIMAL(20,8) )) END [AVGPrice] '
	IF (@CollectType1=1 AND @Layer1=6) OR (@CollectType2=1 AND @Layer2=6)
		SET @Sql += '
		,gp1.Unit[Unit]
		,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3]
		,gp1.Convfactor[Convfactor1],ISNULL(gp2.Convfactor,1)[Convfactor2],ISNULL(gp3.Convfactor,1)[Convfactor3] '
	SET @Sql += '
		FROM PageData o '
	IF @CollectType1=1 AND @Layer1=6
		SET @Sql += '
		LEFT JOIN BD_Goods_Price gp1 ON gp1.GoodsID=o.ID1 AND gp1.UnitID=1 
		LEFT JOIN BD_Goods_Price gp2 ON gp2.GoodsID=o.ID1 AND gp2.UnitID=2 
		LEFT JOIN BD_Goods_Price gp3 ON gp3.GoodsID=o.ID1 AND gp3.UnitID=3 '
	IF @CollectType2=1 AND @Layer2=6
		SET @Sql += '
		LEFT JOIN BD_Goods_Price gp1 ON gp1.GoodsID=o.ID2 AND gp1.UnitID=1 
		LEFT JOIN BD_Goods_Price gp2 ON gp2.GoodsID=o.ID2 AND gp2.UnitID=2 
		LEFT JOIN BD_Goods_Price gp3 ON gp3.GoodsID=o.ID2 AND gp3.UnitID=3 '
	SET @Sql += '
		ORDER BY ROWID '
End
IF @SumOrNot = 1
BEGIN
	SET @Sql += 'SET NOCOUNT ON;
	' + @SumData + @BillData + '
	,PageData as(
		SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ' + @SqlOrder + ') AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData) AS B
		--WHERE ROWID>(@pageNo-1)*@pageSize 
		--AND ROWID<=@pageNo*@pageSize 
	)
	SELECT SUM(o.BSQty)[BSQty],SUM(o.BuyTotal)[BuyTotal],SUM(o.GiftQty)[GiftQty],SUM(o.Freight)[Freight],SUM(o.InTotal)[InTotal]'+ @DiscountSumCol +' FROM PageData o '
END
	
	
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

DECLARE @curPos INT = 1 , @count INT = 1
WHILE (@curPos < len(@Sql))
BEGIN
	PRINT substring(@Sql, @curPos, @curPos + 3999)
	SET @curPos += 3999 + 1
	SET @count += 1
END  
--print @Sql
EXEC SP_EXECUTESQL @Sql,N'@pageNo INT,@pageSize INT,@BillDateType INT,@BillStartDate DATETIME,@BillEndDate DATETIME
,@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@CreatorID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000)
,@GoodsNo VARCHAR(20),@GoodsName VARCHAR(50),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@GiftState INT
,@CollectType1 INT,@Layer1 INT,@CollectType2 INT,@Layer2 INT,@OperatorID INT,@SumOrNot INT
,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT'
,@pageNo,@pageSize,@BillDateType,@BillStartDate,@BillEndDate
,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@GoodsID,@GoodsNo,@GoodsName,@Summary,@Description,@Remark,@GiftState
,@CollectType1,@Layer1,@CollectType2,@Layer2,@OperatorID,@SumOrNot
, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
END


GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryCXDetailList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryCXDetailList]
GO
/****** Object:  StoredProcedure [UP_PD_QueryCXDetailList]    Script Date: 02/11/2015 16:12:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/2/11
-- Description:	 单据商品明细
-- =============================================
CREATE PROCEDURE UP_PD_QueryCXDetailList(
     @BillNo INT = 0, --单据ID
     @BillType INT = 0, --单据类型（采购入库单:101 采购退货单:102 销售出库单:201 销售退货单:202）
	 @GoodsNo VARCHAR(50) = '', --商品编号
	 @GoodsName VARCHAR(100) = '',  --商品名称
	 @PriceStart decimal(20,8), --单价范围开始
	 @PriceEnd  decimal(20,8),  --单价范围结束
	 @TotalStart decimal(20,8), --金额范围开始
	 @TotalEnd  decimal(20,8)  --金额范围结束
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @DetailTable NVARCHAR(20), @DIDAlias NVARCHAR(20) = 'PchDID', @BillNoAlias NVARCHAR(20) = 'PchBillNo'
	SELECT @DetailTable = BillDetail FROM PD_BillType WHERE BillTypeID = @BillType
	IF @BillType > 200
		BEGIN
			SET @DIDAlias = 'SellDID'
			SET @BillNoAlias = 'SellBillNo'
		END 
	   
	IF @DetailTable IS NOT NULL
	    BEGIN
			SET @Sql = 'SELECT detail.DID AS '+@DIDAlias+', detail.BillDate, detail.BillNo AS '+@BillNoAlias+', detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, 
							   @BillType AS BillType, detail.UnitID, detail.Qty, detail.TaxTotal, detail.Remark, detail.TaxPrice AS Price,
							   goods.GoodsNo, goods.GoodsName, price.Unit, ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name
                         FROM ' + @DetailTable + ' detail
                         LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
                         LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID AND price.UnitID = detail.UnitID 
                         LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
                         LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
                         WHERE detail.BillNo = @BillNo '  --完成数量(基本单位), 引用数量(基本数量)
			IF @GoodsNo <> ''
				SET @Sql += 'AND goods.GoodsNo LIKE ''%' + @GoodsNo + '%'' '  
			IF @GoodsName <> ''
				SET @Sql += 'AND goods.GoodsName LIKE ''%' + @GoodsName + '%'' '		            
			IF @PriceStart IS NOT NULL AND @PriceEnd IS NOT NULL 
				SET @Sql +=' AND detail.TaxPrice BETWEEN @PriceStart AND @PriceEnd '
			IF @TotalStart IS NOT NULL AND @TotalEnd IS NOT NULL
				SET @Sql +=' AND detail.TaxTotal BETWEEN @TotalStart AND @TotalEnd '	
			SET @Sql += 'ORDER BY detail.DID'
		    --PRINT @Sql
	        EXEC sp_executesql @Sql, N'@BillNo INT, @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100), @BillType INT, 
	                                   @PriceStart DECIMAL(20,8), @PriceEnd DECIMAL(20,8), @TotalStart DECIMAL(20,8), 
	                                   @TotalEnd DECIMAL(20,8)', 
									@BillNo, @GoodsNo, @GoodsName, @BillType, @PriceStart, @PriceEnd, @TotalStart, @TotalEnd
        END                  
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryCXList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryCXList]
GO
/****** Object:  StoredProcedure [UP_PD_QueryCXList]    Script Date: 02/09/2015 17:52:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/2/9
-- Description:	 单据商品明细
-- =============================================
CREATE PROCEDURE UP_PD_QueryCXList(
     @PageNo INT = 0,
     @PageSize INT = 0,
     @BillCode VARCHAR(50) = '', --单据编号
	 @BTypeID INT = 0,  --往来单位
	 @DeptID VARCHAR(1000) = '',  --部门
	 @ElyID VARCHAR(1000) = '',  --经手人
	 @WhsID VARCHAR(1000) = '',  --仓库
	 @GoodsNo VARCHAR(50)= '',  --商品编号
	 @GoodsName VARCHAR(100)= '',  --商品编号
     @Summary VARCHAR(50)= '',  --摘要
	 @Description VARCHAR(50)= '',  --说明
	 @BillStartDate DATETIME, --录单日期查询开始时间
	 @BillEndDate  DATETIME,  --录单日期查询结束时间
	 @PriceStart decimal(20,8), --单价范围开始
	 @PriceEnd  decimal(20,8),  --单价范围结束
	 @TotalStart decimal(20,8), --金额范围开始
	 @TotalEnd  decimal(20,8),  --金额范围结束
	 @OperatorID INT = 0, --操作员ID
     @DDLBillType INT = 0, --查询条件单据类型（全部:9999）
     @BillType INT = 0, --单据类型（采购发票:507 销售发票:508）
     @OrderClause VARCHAR(50)= '' --排序
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @MainTable NVARCHAR(20), @DetailTable NVARCHAR(20), @RetMainTable NVARCHAR(20), 
	        @RetDetailTable NVARCHAR(20), @InvoiceTable NVARCHAR(20),@InvoiceDetailTable NVARCHAR(20),
	        @BillNoColName NVARCHAR(20) = 'PchBillNo', @DIDColName NVARCHAR(20) = 'PchDID', @ColSql NVARCHAR(2000) = '', 
	        @SqlParam NVARCHAR(4000), @BaseSql NVARCHAR(4000) = '', @SqlJoin NVARCHAR(4000) = '',
	        @RetBillType INT = 0, @BtypeLimit INT = 0, @BaseSqlJoin NVARCHAR(2000) = ''
    DECLARE @TVP_Dept AS [TVP_Type]
    
	IF @DDLBillType = 9999
		BEGIN
			IF @BillType = 507       --采购发票调单
				BEGIN
					SET @DDLBillType = 101;
					SET @RetBillType = 102;
				END
			ELSE                     --销售发票调单
				BEGIN
					SET @DDLBillType = 201;
					SET @RetBillType = 202;
				END
			SELECT @RetMainTable = BillTable, @RetDetailTable = BillDetail FROM PD_BillType WHERE BillTypeID = @RetBillType;
	    END
    
    IF @DDLBillType > 200
		BEGIN
			SET @BillNoColName = 'SellBillNo'
			SET @DIDColName = 'SellDID'
		END
    
	SELECT @MainTable = BillTable, @DetailTable = BillDetail FROM PD_BillType WHERE BillTypeID = @DDLBillType;
	
	SELECT @InvoiceTable = BillTable, @InvoiceDetailTable = BillDetail FROM PD_BillType WHERE BillTypeID = @BillType;
	    
    IF @MainTable IS NOT NULL
		BEGIN
			IF @OrderClause = ''
				SET @OrderClause = 'BillDate Desc' --默认按单据日期倒序
			IF CHARINDEX('ElyCode', @OrderClause) > 0 OR CHARINDEX('ElyName', @OrderClause) > 0
				BEGIN
					SET @SqlJoin += ' INNER JOIN dbo.BD_Employee E on E.ElyID = a.ELyID '
					SET @ColSql += ' , E.ElyCode, E.ElyName '
				END
			ELSE 
				BEGIN
					SET @BaseSql += ', _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName from BD_Employee)'
					SET @BaseSqlJoin += ' INNER JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID '
				END
				
			IF CHARINDEX('BillName', @OrderClause) > 0
				BEGIN
					SET @SqlJoin += ' INNER JOIN dbo.PD_BillType PB on PB.BillTypeID = '+CAST(@DDLBillType AS NVARCHAR(3))+ ' '
					SET @ColSql += ' , PB.BillName '
				END
			ELSE 
				BEGIN
					SET @BaseSql += ', _DATA_BillType AS (SELECT BillTypeID, BillName from PD_BillType)'
					SET @BaseSqlJoin += ' INNER JOIN _DATA_BillType ON Data.BillType = _DATA_BillType.BillTypeID '
				END
									   
			SET @Sql = ' (SELECT DISTINCT a.BillNo, a.BillCode, a.BillDate, a.BTypeID, a.ElyID, a.DeptID, a.Total,
								 a.WhsID, a.Summary, a.[Description], '+CAST(@DDLBillType AS NVARCHAR(3))+' AS BillType, a.InvoiceTotal,  ((CASE '+CAST(@DDLBillType AS NVARCHAR(3))+' WHEN 102 THEN -a.Total WHEN 202 THEN -a.Total ELSE a.Total END) - a.InvoiceTotal) AS NotInvoiceTotal '+@ColSql+' FROM ' + @MainTable + ' a ' +@SqlJoin
			
		    SET @SqlParam = ' WHERE a.Red = 0 AND a.BillDate BETWEEN @BillStartDate AND @BillEndDate 
							  AND a.IsDraft = 0 AND a.Total > ABS(a.InvoiceTotal) AND a.IsInvoice = 1
		                      AND NOT EXISTS (SELECT 1 FROM ' + @InvoiceTable + ' invi
						      INNER JOIN ' + @InvoiceDetailTable + ' inviD ON invi.BillNo = inviD.BillNo
						      WHERE inviD.' + @BillNoColName + ' = a.BillNo
						      AND inviD.BillType = '+CAST(@DDLBillType AS NVARCHAR(3))+'
						      AND invi.InvoiceMode = 2)'  
		            
			IF @BillCode <> '' 
				SET @SqlParam +=' AND a.BillCode LIKE ''%'' + @BillCode + ''%'''
			   
		    IF (@PriceStart IS NOT NULL AND @PriceEnd IS NOT NULL) OR (@TotalStart IS NOT NULL AND @TotalEnd IS NOT NULL)
				BEGIN   
					SET @SqlParam +=' AND EXISTS (SELECT 1 FROM '+@DetailTable+' detail WHERE detail.BillNo = a.BillNo                                        AND NOT EXISTS(SELECT 1 FROM 
	                                  (SELECT '+@DIDColName+', SUM(InvoiceTotal) AS InvoiceTotal FROM 
	                                  ((SELECT inviD.' + @DIDColName + ', invi.InvoiceTotal
	                                  FROM ' + @InvoiceTable + ' invi
									  INNER JOIN ' + @InvoiceDetailTable + ' inviD ON invi.BillNo = inviD.BillNo
									  WHERE inviD.' + @BillNoColName + ' = a.BillNo AND invi.IsDraft = 0
									  AND inviD.BillType = '+CAST(@DDLBillType AS NVARCHAR(3))+'
									  AND invi.InvoiceMode = 1) 
									  UNION ALL 
									  (SELECT inviD.' + @DIDColName + ', invi.InvoiceTotal
	                                  FROM ' + @InvoiceTable + '_His invi
									  INNER JOIN ' + @InvoiceDetailTable + '_His inviD ON invi.BillNo = inviD.BillNo
									  WHERE inviD.' + @BillNoColName + ' = a.BillNo AND invi.IsDraft = 0
									  AND inviD.BillType = '+CAST(@DDLBillType AS NVARCHAR(3))+'
									  AND invi.InvoiceMode = 1))B GROUP BY '+@DIDColName+')C WHERE 
									  '+@DIDColName+' = detail.DID AND ABS(InvoiceTotal) >= detail.TaxTotal )'	    
					IF @PriceStart IS NOT NULL AND @PriceEnd IS NOT NULL 
					   SET @SqlParam +=' AND detail.TaxPrice BETWEEN @PriceStart AND @PriceEnd '	            
					IF @TotalStart IS NOT NULL AND @TotalEnd IS NOT NULL
					   SET @SqlParam +=' AND detail.TaxTotal BETWEEN @TotalStart AND @TotalEnd '
					SET @SqlParam += ' ) '
				END
			--往来单位权限
			SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)
			                    
			IF @BtypeLimit = 1  --部份权限
			   BEGIN
					IF OBJECT_ID('tempdb..#CXListBtypeLimit', 'U') IS NOT NULL
						DROP TABLE #CXListBtypeLimit
					SELECT * INTO #CXListBtypeLimit FROM dbo.UF_BD_BtypeLimit(@OperatorID)
					SET @Sql +=' INNER JOIN #CXListBtypeLimit rBtype ON rBtype.BTypeID = a.BTypeID '
			   END
			      
			IF @BTypeID <> ''
			   SET @SqlParam +=' AND a.BTypeID = @BTypeID'
		       
			IF @DeptID <> ''
			   BEGIN
				 SET @Sql +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = a.DeptID '
				 INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
				 SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
					 INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
					 WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
			   END
		              
			IF @ElyID <> ''
			   BEGIN
					IF OBJECT_ID('tempdb..#CXListElyList', 'U') IS NOT NULL
						DROP TABLE #CXListElyList
					SELECT * INTO #CXListElyList FROM dbo.UF_OT_Split_Int(@ElyID, ',')
					SET @Sql +=' INNER JOIN #CXListElyList _Ely ON _Ely.typeid = a.ElyID '
			   END
		       
			IF @WhsID <> ''
			   BEGIN
					IF OBJECT_ID('tempdb..#CXListWhsList', 'U') IS NOT NULL
						DROP TABLE #CXListWhsList
					SELECT * INTO #CXListWhsList FROM dbo.UF_OT_Split_Int(@WhsID, ',')
					SET @Sql +=' INNER JOIN #CXListWhsList _Whs ON _Whs.typeid = a.WhsID '
			   END
			IF @GoodsNo <> '' OR @GoodsName <> ''
			   BEGIN
				 SET @Sql +=' INNER JOIN ' + @DetailTable + ' detail ON detaiL.BillNo = a.BillNo 
							  INNER JOIN BD_Goods goods on goods.GoodsID = detail.GoodsID '	             
				 IF @GoodsNo <> ''
				  SET @SqlParam +=' AND goods.GoodsNo  LIKE ''%''+@GoodsNo+''%'''  
				  				             
				 IF @GoodsName <> ''
				  SET @SqlParam +=' AND goods.GoodsName  LIKE ''%''+@GoodsName+''%''' 
			   END
		                  
			IF @Summary <> ''
			   SET @SqlParam +=' AND a.Summary LIKE ''%''+@Summary+''%'''
		                  
			IF @Description <> ''
			   SET @SqlParam +=' AND a.Description LIKE ''%''+@Description+''%'''
			
			IF @RetBillType <> 0
				SET @Sql += @SqlParam + ' UNION ALL ' + REPLACE(REPLACE(REPLACE(@Sql, @MainTable, @RetMainTable), @DetailTable, @RetDetailTable), @DDLBillType, @RetBillType)+ REPLACE(REPLACE(@SqlParam, @DDLBillType, @RetBillType), @DetailTable, @RetDetailTable) + ')'	
			ELSE
				SET @Sql += @SqlParam	
			SET @Sql= N'SET NOCOUNT ON;
						;WITH PagingData AS ' + @Sql  +')' + @BaseSql +
					   N', _DATA_Btype AS (SELECT BTypeID AS BID, BTypeCode, BTypeName, ISNULL(PaidCircle, 0) AS PaidCircle from BD_Btype)
					   , _DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName from BD_Whs)
					   , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName from BD_Dept)
					   , DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
								  CROSS JOIN
								 (SELECT ROW_NUMBER() OVER(ORDER BY BillType DESC ) AS ROWID,* FROM PagingData) B
								  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
					   SELECT * FROM DATA LEFT JOIN _DATA_Btype ON Data.BTypeID = _DATA_Btype.BID
										  LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID
										  LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID 
										  '+@BaseSqlJoin+'ORDER BY ROWID'	
			--PRINT @Sql					  
			IF @BtypeLimit = 0
				SET @Sql = N' SELECT * FROM ' + @MainTable + ' WHERE 1 <> 1'
			EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillCode VARCHAR(50), @BTypeID INT, @DeptID VARCHAR(1000),
									   @ElyID VARCHAR(1000), @WhsID VARCHAR(1000), @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100),
									   @Summary VARCHAR(50), @Description VARCHAR(50), @BillStartDate DATETIME, @BillEndDate DATETIME,
									   @OperatorID INT, @TVP_Dept TVP_Type READONLY, @DDLBillType INT, @PriceStart DECIMAL(20,8), 
									   @PriceEnd DECIMAL(20,8), @TotalStart DECIMAL(20,8), @TotalEnd DECIMAL(20,8)', 
									   @PageNo, @PageSize, @BillCode, @BTypeID, @DeptID, @ElyID, @WhsID, @GoodsNo, @GoodsName,
									   @Summary, @Description, @BillStartDate, @BillEndDate, @OperatorID, @TVP_Dept, @DDLBillType, 
									   @PriceStart, @PriceEnd, @TotalStart, @TotalEnd
		END		 
END
GO




/****** Object:  StoredProcedure [UP_PD_QueryExchangeBilllData]    Script Date: 06/25/2014 16:17:55 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryExchangeBilllData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryExchangeBilllData]
GO

/****** Object:  StoredProcedure [UP_PD_QueryExchangeBilllData]    Script Date: 06/25/2014 16:17:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		hl
-- Create date:  2015-12-07
-- Description:	 查询积分兑换单数据
-- =============================================
CREATE PROCEDURE [UP_PD_QueryExchangeBilllData]
(
	@BillNo INT=0
) 
AS
BEGIN
	IF EXISTS (SELECT 1 FROM PD_InOutWhsBill b WHERE b.BillNo=@BillNo)
	BEGIN		--当前数据
		SELECT TOP 1 
			p.IsDraft,p.Red
			,p.BillNo,p.BillDate,p.BillCode
			,p.BTypeID,b.BTypeName
			,p.ElyID,e.ElyName
			,p.DeptID,d.DeptName
			,p.WhsID,w.WhsName
			,p.Summary,p.[Description]
			,p.Creator[CreatorID],e1.ElyName[CreatorName],e2.ElyName AS PosName
			,p.BillQty,p.Total,p.AuditStatus,p.VipCardID,p.ExchangeCent,v.CentBalance
			,CASE WHEN p.VipCardID=0 THEN'' 
					ELSE Vt.TypeName+' 会员卡号：'+v.VipCardNO+' 会员名称：'+V.VipName+' 持卡人：'+CardHolder END AS VipCardInfo
		FROM PD_InOutWhsBill p 
		LEFT JOIN BD_Btype b ON p.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON p.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON p.DeptID=d.DeptID 
		INNER JOIN BD_Whs w ON p.WhsID=w.WhsID 
		LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID 
		LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
		LEFT JOIN dbo.VS_VipCard v ON v.VipCardID=p.VipCardID
		LEFT JOIN dbo.VS_VipCardType vt ON v.VipCardTypeID=vt.VipCardTypeID
		WHERE p.BillNo=@BillNo 
		
		SELECT  p.DID,p.GoodsID,g.GoodsNo,g.GoodsName
				,p.BarCode
				,g.Spec,g.Model
				,p.Ppt1ID,p1.Value[Ppt1Name]
				,p.Ppt2ID,p2.Value[Ppt2Name]
				,p.WhsID,p.WhsPtID,wp.WhsPtName
				,p.Qty,p.BSQty
				,p.UnitID,gp.Unit
				,p.Convfactor
				,p.CostPrice
				,p.CostPrice[GoodsCostPrice],p.CostPrice*p.Convfactor[Price],p.GoodsCostTotal,p.Remark
				,p.BatchNumber,p.ProductDate,p.EndDate
				,gp1.Convfactor[Convfactor1]
				,ISNULL(gp2.Convfactor,1)[Convfactor2]
				,ISNULL(gp3.Convfactor,1)[Convfactor3]
				--,case when gp3.Convfactor is null then 1 else gp3.Convfactor end [Convfactor3]
				,gp1.BarCode[BarCode1],gp2.BarCode[BarCode2],gp3.BarCode[BarCode3]
				,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3],
				g.IsSerial ,p.BatchNumber,p.ProductDate,p.EndDate,p.InPutPrice,g.DateType,g.CostMethod,p.IsSelectBatch
		FROM PD_InOutWhsDetail p 
		INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID 
		LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
		LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID 
		INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID 
		INNER JOIN BD_Goods_Price gp ON p.GoodsID=gp.GoodsID AND p.UnitID=gp.UnitID 
		LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND 1=gp1.UnitID 
		LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND 2=gp2.UnitID 
		LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND 3=gp3.UnitID 
		WHERE p.BillNo=@BillNo 
		
		-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_InOutWhsSerial ps Inner Join PD_InOutWhsDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
	ELSE
	BEGIN
		SELECT TOP 1 
			p.IsDraft,p.Red
			,p.BillNo,p.BillDate,p.BillCode
			,p.BTypeID,b.BTypeName
			,p.ElyID,e.ElyName
			,p.DeptID,d.DeptName
			,p.WhsID,w.WhsName
			,p.Summary,p.[Description]
			,p.Creator[CreatorID],e1.ElyName[CreatorName],e2.ElyName AS PosName
			,p.BillQty,p.Total ,p.AuditStatus,p.VipCardID,p.ExchangeCent ,v.CentBalance
			,CASE WHEN p.VipCardID=0 THEN'' 
					ELSE Vt.TypeName+' 会员卡号：'+v.VipCardNO+' 会员名称：'+V.VipName+' 持卡人：'+CardHolder END AS VipCardInfo
		FROM PD_InOutWhsBill_His p 
		LEFT JOIN BD_Btype b ON p.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON p.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON p.DeptID=d.DeptID 
		INNER JOIN BD_Whs w ON p.WhsID=w.WhsID 
		LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID 
		LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
		LEFT JOIN dbo.VS_VipCard v ON v.VipCardID=p.VipCardID
		LEFT JOIN dbo.VS_VipCardType vt ON v.VipCardTypeID=vt.VipCardTypeID
		WHERE p.BillNo=@BillNo 
		
		SELECT  p.DID,p.GoodsID,g.GoodsNo,g.GoodsName
				,p.BarCode
				,g.Spec,g.Model
				,p.Ppt1ID,p1.Value[Ppt1Name]
				,p.Ppt2ID,p2.Value[Ppt2Name]
				,p.WhsID,p.WhsPtID,wp.WhsPtName
				,p.Qty,p.BSQty
				,p.UnitID,gp.Unit
				,p.Convfactor
				,p.CostPrice
				,p.CostPrice[GoodsCostPrice],p.Price,p.GoodsCostTotal,p.Remark
				,p.BatchNumber,p.ProductDate,p.EndDate
				,gp1.Convfactor[Convfactor1]
				,ISNULL(gp2.Convfactor,1)[Convfactor2]
				,ISNULL(gp3.Convfactor,1)[Convfactor3]
				--,case when gp3.Convfactor is null then 1 else gp3.Convfactor end [Convfactor3]
				,gp1.BarCode[BarCode1],gp2.BarCode[BarCode2],gp3.BarCode[BarCode3]
				,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3],
				g.IsSerial ,p.BatchNumber,p.ProductDate,p.EndDate,p.InPutPrice,g.DateType,g.CostMethod
		FROM PD_InOutWhsDetail_His p 
		INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID 
		LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
		LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID 
		INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID 
		INNER JOIN BD_Goods_Price gp ON p.GoodsID=gp.GoodsID AND p.UnitID=gp.UnitID 
		LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND 1=gp1.UnitID 
		LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND 2=gp2.UnitID 
		LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND 3=gp3.UnitID 
		WHERE p.BillNo=@BillNo 
		
			-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_InOutWhsSerial_His ps Inner Join PD_InOutWhsDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
END

GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：商品往来对账查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryGoodsWLDZ]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BTypeID Int=0,
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@ShowDZ INT=0,
	@RedFlag Int = 0,
	@isHistory INT=0				--是否包含历史数据	
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;


DECLARE @sql nvarchar(MAX)='',@SqlBuy nvarchar(max)='',@SqlBuyBack nvarchar(max)='',@SqlSell nvarchar(max)='',@SqlSellBack nvarchar(max)=''
	,@sqlSellLogist nvarchar(max)='',@sqlBuyLogist nvarchar(max)='',@SqlBuyHis nvarchar(max)='',@SqlBuyBackHis nvarchar(max)='',@SqlSellHis nvarchar(max)='',@SqlSellBackHis nvarchar(max)=''
	,@RowCount int=0,@SqlTable nvarchar(max)='',@SqlRed varchar(100)='',@SqlDZ1 varchar(200)='',@SqlDZ2 varchar(200)='',@SqlDZ3 varchar(200)='',
	@SqlCreateTable varchar(max)='',@SqlBaseTable varchar(max)='',@RedStr varchar(100)='',@RedStr1 varchar(100)='',@sqlListTable varchar(max)='',@SqlRet varchar(max)=''
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlBaseTable+=' INNER JOIN @DType D ON I.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlBaseTable+=' INNER JOIN @EType E ON I.ElyID=E.TypeID ' 
END	
if(@RedFlag = 0) 
	Select @SqlRed = ' And Red = 0 '
Select @RedStr = ',Red '
Select @RedStr1 = ',A.Red '
if(@ShowDZ = 1) 
Begin
	Select @SqlDZ1 = ' Where IsReconciled = 1 '
	Select @SqlDZ2 = ' And IsReconciled = 1 '
	Select @SqlDZ3 = ' where 2=1 '	
ENd
if(@ShowDZ = 2) 
Begin
	Select @SqlDZ1 = ' Where IsReconciled = 0 '
	Select @SqlDZ2 = ' And IsReconciled = 0 '	
ENd
Select @RowCount = (@PageNo-1) * @PageSize	

if @isHistory = 1
	Set @sqlListTable += ' (select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal,IsReconciled,[Order],Red from PD_ListTable
						union all
						select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal,IsReconciled,[Order],Red from PD_ListTable_His)'
else
	Set @sqlListTable += 'PD_ListTable'

--Select @SqlTable=' Declare @total decimal=0
--		select @total=Case when sum(JTotal)-sum(DTotal) IS Not null then sum(JTotal)-sum(DTotal) else 0 end  from '+@sqlListTable+' L where FinanceID in(33,37) And BtypeID = @BTypeID And BillDate < @BeginDate
--		select @total=case when SUM(QcAr)-SUM(QcAR) IS Not Null then SUM(QcAr)-SUM(QcAR) + @total Else @total end from BD_ARAP Where BtypeID = @BTypeID
--'
SELECT @sql+='
UNION ALL 
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
		'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime,Summary,Description ,I.BillNo,'''' as WhsID ' + @RedStr
	+' FROM '+BillTable+' I ' + @SqlBaseTable
	+' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID
	AND BillDate BETWEEN @BeginDate AND @EndDate' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
FROM PD_BillType b
WHERE CanPost=1 And BillTypeID in (401,402,404,405,501,502,503,504)

Select @SqlBuy += '
SELECT  101 AS BillTypeID,
		'''+'采购入库单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID ' + @RedStr +'
		FROM PD_PchBill I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
'
Select @SqlBuyBack += '
SELECT  102 AS BillTypeID,
		'''+'采购退货单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID  ' + @RedStr +'
		FROM PD_PchRetBill I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
'
Select @SqlSell += '
SELECT  201 AS BillTypeID,
		'''+'销售出库单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID  ' + @RedStr +' 
		FROM PD_SellBill I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
'
Select @SqlSellBack += '
SELECT  202 AS BillTypeID,
		'''+'销售退货单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID  ' + @RedStr +' 
		FROM PD_SellRetBill I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
'
SELECT @sqlSellLogist+='
SELECT  201 AS BillTypeID,
		'''+'销售出库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID  ' + @RedStr +' 
		FROM PD_SellBill I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And I.BTypeID <> I.LogistBTypeID  AND BillDate BETWEEN @BeginDate AND @EndDate' 
SELECT @sqlBuyLogist+='
SELECT  101 AS BillTypeID,
		'''+'采购入库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID,I.Freight,I.DeptID,I.ElyID  ' + @RedStr +' 
		FROM PD_PchBill I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And I.BTypeID <> I.LogistBTypeID  AND BillDate BETWEEN @BeginDate AND @EndDate' 
			
IF @isHistory=1
Begin
	SELECT @sql+='
	UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
			'''+billname+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime,Summary,Description ,I.BillNo,'''' as WhsID ' + @RedStr
		+' FROM '+BillTable+'_His I ' + @SqlBaseTable
		+' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID
		AND BillDate BETWEEN @BeginDate AND @EndDate' 
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	FROM PD_BillType b
	WHERE CanPost=1 And BillTypeID in (401,402,404,405,501,502,503,504)

	Select @SqlBuyHis += '
	SELECT  101 AS BillTypeID,
			'''+'采购入库单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID ' + @RedStr +'
			FROM PD_PchBill_His I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
	'
	Select @SqlBuyBackHis += '
	SELECT  102 AS BillTypeID,
			'''+'采购退货单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID  ' + @RedStr +'
			FROM PD_PchRetBill_His I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
	'
	Select @SqlSellHis += '
	SELECT  201 AS BillTypeID,
			'''+'销售出库单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID  ' + @RedStr +' 
			FROM PD_SellBill_His I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
	'
	Select @SqlSellBackHis += '
	SELECT  202 AS BillTypeID,
			'''+'销售退货单'+''' AS BillName,BillCode,BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,DeptID,ElyID,I.BillNo,I.WhsID  ' + @RedStr +' 
			FROM PD_SellRetBill_His I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID AND BillDate BETWEEN @BeginDate AND @EndDate
	'
	SELECT @sqlSellLogist+='
	Union All
	SELECT  201 AS BillTypeID,
			'''+'销售出库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID  ' + @RedStr +' 
			FROM PD_SellBill_His I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And I.BTypeID <> I.LogistBTypeID AND BillDate BETWEEN @BeginDate AND @EndDate' 
	SELECT @sqlBuyLogist+='
	Union All
	SELECT  101 AS BillTypeID,
			'''+'采购入库单'+''' AS BillName,BillCode,LogistBTypeID as BTypeID,BillDate,Createtime,CONVERT(varchar(100), PosTime, 120) AS PosTime ,Summary,Description ,I.BillNo,I.WhsID,I.Freight,I.DeptID,I.ElyID  ' + @RedStr +' 
			FROM PD_PchBill_His I '+ @SqlBaseTable +' WHERE	IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And I.BTypeID <> I.LogistBTypeID  AND BillDate BETWEEN @BeginDate AND @EndDate' 
	
End

Select @SqlRet += '
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,Ppt1ID,Ppt2ID,35 as FinanceID,IsReconciled ,0 as DTotal,Case When Red=2 then isnull(DiscTotal,0) *-1 Else isnull(DiscTotal,0) End as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order] ' + @RedStr +' 
	from BuyBill I left Join PD_PchDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,Ppt1ID,Ppt2ID,35 as FinanceID,IsReconciled ,Case When Red=2 then isnull(DiscTotal,0)*-1 Else isnull(DiscTotal,0) End as DTotal,0 as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order]' + @RedStr +' 
	from BuyBackBill I left Join PD_PchRetDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,Ppt1ID,Ppt2ID,8 as FinanceID,IsReconciled ,Case When Red=2 then isnull(DiscTotal,0)*-1 Else isnull(DiscTotal,0) End as DTotal,0 as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order]' + @RedStr +' 
	from SellBill I left Join PD_SellDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,Ppt1ID,Ppt2ID,35 as FinanceID,IsReconciled ,0 as DTotal,Case When Red=2 then isnull(DiscTotal,0)*-1 Else isnull(DiscTotal,0) End as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order]' + @RedStr +' 
	from SellBackBill I left Join PD_SellRetDetail bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	'
IF @isHistory=1
Begin
Select @SqlRet += '
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,Ppt1ID,Ppt2ID,35 as FinanceID,IsReconciled ,0 as DTotal,Case When Red=2 then isnull(DiscTotal,0)*-1 Else isnull(DiscTotal,0) end as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order] ' + @RedStr +' 
	from BuyBill_His I left Join PD_PchDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,Ppt1ID,Ppt2ID,35 as FinanceID,IsReconciled ,Case When Red=2 then isnull(DiscTotal,0)*-1 Else isnull(DiscTotal,0) End as DTotal,0 as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order]' + @RedStr +' 
	from BuyBackBill_His I left Join PD_PchRetDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,Ppt1ID,Ppt2ID,8 as FinanceID,IsReconciled ,Case When Red=2 then isnull(DiscTotal,0)*-1 Else isnull(DiscTotal,0) End as DTotal,0 as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order]' + @RedStr +' 
	from SellBill_His I left Join PD_SellDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	Select BillTypeID,I.BillNO,BillName,I.BillCode,I.Createtime,I.Postime,I.Summary,I.Description,I.BtypeID,I.DeptID,I.ElyID,BD.WhsID,3Ppt1ID,Ppt2ID,35 as FinanceID,IsReconciled ,0 as DTotal,Case When Red=2 then isnull(DiscTotal,0)*-1 Else isnull(DiscTotal,0) End as JTotal,I.BillDate,GoodsID,BD.Qty,BD.UnitID,BD.DiscPrice,0 as [Order]' + @RedStr +' 
	from SellBackBill_His I left Join PD_SellRetDetail_His bd  On I.BillNo=bd.BillNo '+@SqlDZ1+'
	Union ALL
	'
End
SELECT @sql=@SqlCreateTable+@SqlTable + '
;WITH Bill AS 
('	+STUFF(@sql,1,12,'')+'
)
,BuyBillLogist as
( ' +@sqlBuyLogist+')
,SellBillLogist as
( ' +@sqlSellLogist+')
,SellBill as
(' +@sqlSell+
'),SellBackBill as
('+@SqlSellBack+'
),BuyBill as
('+@SqlBuy+')
,BuyBackBill As
('+@SqlBuyBack+')'
IF @isHistory=1
	Select @sql+= '
		,SellBill_His as
	(' +@SqlSellHis+
	'),SellBackBill_His as
	('+@SqlSellBackHis+'
	),BuyBill_His as
	('+@SqlBuyHis+')
	,BuyBackBill_His As
	('+@SqlBuyBackHis+')'
Select @sql +=',AllData as
( 
	'+@SqlRet+'
	Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal,L.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice,L.[Order] ' + @RedStr1 +' 
	from Bill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37) '+@SqlDZ2+'
	Union ALL
	Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal,L.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice,L.[Order] ' + @RedStr1 +' 
	from BuyBillLogist A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where  FinanceID not in(37,33) And L.BtypeID = @BTypeID '+@SqlDZ2+'
	Union ALL
	Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,A.DeptID,A.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,30 as FinanceID,-1 as IsReconciled ,0 as DTotal,Case When A.Red=2 then A.Freight * -1 else A.Freight End as JTotal,A.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice,20 as [Order] ' + @RedStr1 +' 
	from BuyBillLogist A '+ @SqlDZ3 +'
	Union ALL
	Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal,L.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice,L.[Order] ' + @RedStr1 +' 
	from SellBillLogist A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where  FinanceID not in(37,33) And L.BtypeID = @BTypeID '+@SqlDZ2+'
	Union ALL
  Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal ,isnull(L.JTotal,0) as JTotal,L.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
	from sellbill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,11,35,8) '+@SqlDZ2+'
	Union ALL
  Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal ,isnull(L.JTotal,0) as JTotal,L.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
	from SellBackBill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,11,35,8,20) '+@SqlDZ2+'
	Union ALL
	Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal,L.BillDate ,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
	from BuyBill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,35) '+@SqlDZ2+'
	Union ALL
	Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal,L.BillDate ,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
	from BuyBackBill A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,35,20) '+@SqlDZ2
IF @isHistory=1	
	Select @sql += '
		Union ALL
	  Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal ,isnull(L.JTotal,0) as JTotal,L.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
		from sellbill_His A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
		where FinanceID not in(33,37,11,35,8) '+@SqlDZ2+'
		Union ALL
	  Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal ,isnull(L.JTotal,0) as JTotal,L.BillDate,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
		from SellBackBill_His A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
		where FinanceID not in(33,37,11,35,8,20) '+@SqlDZ2+'
		Union ALL
		Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal,L.BillDate ,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
		from BuyBill_His A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
		where FinanceID not in(33,37,35) '+@SqlDZ2+'
		Union ALL
		Select A.BillTypeID,A.BillNO,A.BillName,BillCode,Createtime,Postime,Summary,Description ,A.BtypeID,L.DeptID,L.ElyID,WhsID,0 as Ppt1ID,0 as Ppt2ID,L.FinanceID,IsReconciled ,isnull(L.DTotal,0) as DTotal,isnull(L.JTotal,0) as JTotal,L.BillDate ,0 as GoodSID,0 as Qty,0 as UnitID,0 as DiscPrice ,L.[Order]' + @RedStr1 +' 
		from BuyBackBill_His A Left Join '+@sqlListTable+' L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
		where FinanceID not in(33,37,35,20) '+@SqlDZ2
	
	Select @sql += '),page as
(
	select row_number() over (order by Createtime,Postime,[Order]) as rowNum,* from AllData
),pageTotal as
(
	Select Case when sum(DTotal)-sum(JTotal) IS Not NULL then sum(DTotal)-sum(JTotal) Else 0 End  as beforTotal from  page where rowNum <= @RowCount
),
pageData as 
(
	SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM AllData) A
	CROSS JOIN
	(
	Select rowNum,BillTypeID,BillNO,BillName,BillCode,Createtime,Postime,BillDate,Summary,Description ,A.BtypeID,A.DeptID,A.ElyID,A.WhsID,A.Ppt1ID,A.Ppt2ID,A.FinanceID,IsReconciled ,DTotal,JTotal,A.GoodSID,qty,discprice
		,b.BTypeCode,b.BTypeName,d.DeptCode,d.DeptName,e.ElyCode,e.ElyName,w.WhsNO,W.WhsName,Gp1.Value as ppt1name,Gp2.Value as ppt2name,Case When BillTypeID in (102,202) and F.FinanceNO = 1243 then '''' Else F.FinanceNO End as FinanceNO,Case When BillTypeID in (102,202) and F.FinanceNO = 1243 then ''' + '退货金额' +''' Else f.FinanceName end as FinanceName,G.goodsno,G.goodsname,G.spec,G.model,Gp.unit ' + @RedStr1 +' 
	from  page A Left Join BD_Btype B on A.BTypeID=b.BTypeID
			Left Join BD_Dept D on A.DeptID=D.DeptID
			Left Join BD_Employee E on A.ElyID=E.ElyID
			Left Join BD_Whs W on A.WhsID=W.WhsID
			Left Join BD_Finance F on A.FinanceID=F.FinanceID
			Left Join BD_Goods G on A.GoodsID = G.GoodsID
			Left Join BD_Goods_Price GP on A.UnitID=Gp.UnitID  And A.GoodsID=GP.GoodsID
			left Join BD_Goods_Ppt1 GP1 On A.Ppt1ID = Gp1.Ppt1ID
			left Join BD_Goods_Ppt2 GP2 On A.Ppt2ID = Gp2.Ppt2ID
	where rowNum > @RowCount And rowNum <= @RowCount + @PageSize
	) B
)
select * from pageData,pageTotal
'
--select @total as total
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END
--select @PageNo,@PageSize,@BeginDate,@EndDate,@BTypeID,@RowCount
------------------添加参数---------------------------------------
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
print @sql
exec sp_executesql @sql,N'@PageNo Int,@PageSize Int,@BeginDate Date,@EndDate Date,@BTypeID VarChar(MAX),@DeptID VarChar(MAX),@ElyID VarChar(MAX),@RowCount Int',@PageNo,@PageSize,@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID,@RowCount

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-8-5
	描述：出入库单据明细
	update : sunzhiyuan 2015-11-23 增加序列号相关字段查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryInOutDetails]
(
	@PageNo INT=0,
	@PageSize INT=0,
	--@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(max)='',
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@InWhsID VARCHAR(max)='',
	@OutWhsID VARCHAR(max)='',
	@FinanceID VARCHAR(max)='',
	@BillCode VARCHAR(100)='',
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100)='',
	@UserCodeMatch INT=0,
	@UserCode VARCHAR(100)='',
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@FullNameMatch INT=0,
	@LogistBillNo VARCHAR(100) = '',
	@LogistBillNoMatch INT=0,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=0,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=0,
	@Remark VARCHAR(100)='',
	@RemarkMatch INT=0,
	@OrderType1 varchar(100)='PosTime',				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额
	@OrderSeq1 Int=1,  --排序类型 1=升序，2=降序
	@OrderType2 varchar(100)='GoodsNo',				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额			
	@OrderSeq2 Int=1,  --排序类型 1=升序，2=降序
	@IsRedFlag Int=0,
	@OperatorID INT,
	@ClassID1 Int = 0,		--汇总条件一，ID
	@ClassType1 Int = 0,	--汇总条件一类型 1为单据汇总，2为仓库汇总
	@ClaseFlag1 Int = 0,	--汇总条件一分类 0为非分类，1为分类汇总
	@ClassID2 Int = 0,		--汇总条件二，ID
	@ClassType2 Int = 0,	--汇总条件二类型 1为商品
	@ClaseFlag2 Int = 0,		--汇总条件二分类 0为非分类，1为分类汇总
	@isHistory INT=0,				--是否包含历史数据
	@ShowSerial INT = 0,    -- 是否显示序列号
	@BillFlag INT=0			--处理调价单和调拨单的出入库明细	
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;
set @OrderType1 = isnull(@OrderType1,'')	
set @OrderType2 = isnull(@OrderType2,'')	
if((@OrderType1='' or @OrderType1 = null) and (@OrderType2='' or @OrderType2 = null))
Begin
	Set @OrderType1='PosTime'
	set @OrderType2 = 'GoodsNo'
End
DECLARE @sql nvarchar(MAX)='',@sqlOut nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlWhs nvarchar(max)='',
		@SqlWhsOut varchar(max)='',@SqlWhsin varchar(max)='',@OrderName nvarchar(100)='',@OrderColumn varchar(max)='',
		@OrderTable varchar(max)='',@GoodsMath varchar(max)='', @SqlPpt1 nvarchar(1000)='',@SqlPpt2 nvarchar(1000)='',
		 @LimitSql NVARCHAR(MAX) = '',@LimitSqlIN NVARCHAR(max)='',@LimitSqlOut NVARCHAR(max)='',@conditionStr varchar(max)='',
		 @RedStr varchar(100)='',@Red varchar(100)='',@SqlClass1 varchar(500)='',@SqlClass2 varchar(500)='',@sqlWhsInClick varchar(max)='',
		 @sqlWhsOutClick varchar(max)='',@sqlWhsClick varchar(max)='',@SqlBSUnit varchar(500)='',@PageDataStr varchar(max)='select BillTypeID,DID',
		 @SqlFreight varchar(500)='',@SqlAtype varchar(500)='',
		 @SaleStr varchar(max)=' DID',@buyStr varchar(max)=' DID',@saleRetStr varchar(max)=' DID',@AssemblyInStr varchar(Max)=' DID',@AssemblyOutStr varchar(Max)=' DID'
		 ,@buyRetStr varchar(max)=' DID',@AllToTStr varchar(max)=' DID',@AllToBStr varchar(max)=' DID',@AdjPriceInStr varchar(max)=' DID',@AdjPriceOutStr varchar(max)=' DID'
		 ,@InOutStr varchar(max)=' DID',@LossSpil varchar(max)=' DID',
		 @SaleStrO varchar(max)='',@buyStrO varchar(max)=' ',@saleRetStrO varchar(max)=' ',@AssemblyInStrO varchar(Max)='',@AssemblyOutStrO varchar(Max)=''
		 ,@buyRetStrO varchar(max)=' ',@AllToTInStrO varchar(max)=' ',@AllToBInStrO varchar(max)=' ',@AllToTOutStrO varchar(max)=' ',@AllToBOutStrO varchar(max)=' ',@AdjPriceInStrO varchar(max)=' '
		 ,@AdjPriceOutStrO varchar(max)=' ' ,@InOutInStrO varchar(max)=' ',@InOutOutStrO varchar(max)=' ',@LossSpilInO varchar(max)=' ',@LossSpilOutO varchar(max)=' '
		 ,@BtypeLimit INT=0,@KtypeLimit INT=0,@InspectTagStr varchar(100)='',
		 -- 序列号相关字段信息
		 @SeriesCol1 NVARCHAR(MAX)='',@SeriesCol2 NVARCHAR(MAX)='',@SeriesCol3 NVARCHAR(MAX)='',@SeriesColEnd NVARCHAR(MAX)='',
		 @301 NVARCHAR(MAX) = '',@301_His NVARCHAR(MAX) = '',@302 NVARCHAR(MAX) = '',@302_His NVARCHAR(MAX) = '',
		 @309 NVARCHAR(MAX) = '',@309_His NVARCHAR(MAX) = '',@310 NVARCHAR(MAX) = '',@310_His NVARCHAR(MAX) = '',
		 @InOutExchangeStrO varchar(max)=' '
		 
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 

-- 是否显示序列号
IF @ShowSerial = 1
BEGIN
	SET @SeriesCol1 += ',GoodsID[BillGoodsID],Serial.Serial[seriesnum],Serial.CostPrice[seriesnumcost],Serial.Remark[seriesnumremark] '
	SET @SeriesCol2 += ',GoodsID[BillGoodsID],Serial.Serial[seriesnum],Serial.AllotPrice[seriesnumcost],Serial.Remark[seriesnumremark] '
	SET @SeriesCol3 += ',GoodsID[BillGoodsID],Serial.Serial[seriesnum],Serial.AdjPrice[seriesnumcost],Serial.Remark[seriesnumremark]	'
	SET @SeriesColEnd += ',bill.DetailWhsID,seriesnum,CASE WHEN bdg.CostMethod = 1 AND seriesnum is not null THEN GoodsStock.Price 
										ELSE seriesnumcost END AS seriesnumcost,seriesnumremark '
	SET @301 += ' LEFT JOIN PD_AllotSerial Serial ON BD.DID = Serial.BillDID '
	SET @301_His += ' LEFT JOIN PD_AllotSerial_His Serial ON BD.DID = Serial.BillDID '
	SET @309 += ' LEFT JOIN PD_AllotSerial Serial ON BD.DID = Serial.BillDID '
	SET @309_His += ' LEFT JOIN PD_AllotSerial_His Serial ON BD.DID = Serial.BillDID ' 
	SET @302 += ' LEFT JOIN PD_AdjPriceSerial Serial ON BD.DID = Serial.BillDID '
	SET @302_His += ' LEFT JOIN PD_AdjPriceSerial_His Serial ON BD.DID = Serial.BillDID '
	SET @310 += ' LEFT JOIN PD_AssemblySerial Serial ON BD.DID = Serial.BillDID '
	SET @310_His += ' LEFT JOIN PD_AssemblySerial_His Serial ON BD.DID = Serial.BillDID '
	SET @OrderTable += ' INNER JOIN BD_Goods bdg ON bill.BillGoodsID = bdg.GoodsID
						 INNER JOIN PD_GoodsStock GoodsStock ON bill.BillGoodsID = GoodsStock.GoodsID AND Bill.DetailWhsID = GoodsStock.WhsID '
END


if object_id('tempdb..#BillType','U') is not null drop table #BillType
CREATE TABLE #BillType(billtype int)
IF @BillTypeID<>''		
	INSERT INTO #BillType SELECT typeid FROM  dbo.UF_OT_Split_Int(@BillTypeID,',') Where typeid IN(101,102,201,202,301,302,303,304,305,306,309,310,600) 
ELSE
	INSERT INTO #BillType SELECT BillTypeID  FROM PD_BillType  WHERE CanPost=1 And BillTypeID IN(101,102,201,202,301,302,303,304,305,306,309,310,600) 
--------------------根据条件筛选单据类型---------------------
IF NOT EXISTS(SELECT TOP 1 1 FROM #BillType WHERE billtype=0)
BEGIN
	IF @BTypeID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,303,304,600)
	IF @FinanceID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,201,102,202)   
	IF @UserCode<>'' OR @FullName<>'' OR @WhsID<>'' OR @Model <> '' OR @AbbName <> '' OR @Brand <> '' OR @Spec <> ''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,301,302,303,304,305,306,309,310,600)   
	if @LogistBillNo <> ''
		DELETE FROM #BillType WHERE billtype NOT IN(201)   
	if @ClassType1 = 1
		DELETE FROM #BillType WHERE billtype <> @ClassID1 
END  
if exists(select 1 from SS_SysCfg where CfgName='AllotWithInspect' and CfgValue = 1) --判断是否启用调拨验证
	select @InspectTagStr = ' AND I.InspectTag = 1 '
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' Inner Join @BType B on I.BTypeID=B.TypeID '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' Inner Join @DType D On I.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' Inner Join @EType E On I.ElyID=E.TypeID ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' Inner Join @CreateEType CE On I.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	Set @SqlWhs += ' Inner Join @KType W On I.WhsID=W.TypeID ' 
	Set @SqlWhsOut += ' Inner Join @KType W On I.OutWhsID = W.TypeID or I.InWhsID=W.TypeID ' 
	--Set @SqlWhsIn += ' And exists( Select 1 from  @KType W where I.InWhsID=W.TypeID) ' 
END	
IF @InWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @InKType As Table(TypeID INT) insert into @InKType Select typeid from dbo.UF_OT_Split_Int(@InWhsID,'','') '
	SET @SqlWhsIn+='  Inner Join @InKType Wi On I.InWhsID=Wi.TypeID ' 
END	
IF @OutWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @OutKType As Table(TypeID INT) insert into @OutKType Select typeid from dbo.UF_OT_Split_Int(@OutWhsID,'','') '
	SET @SqlWhsOut+=' Inner Join @OutKType Wo On I.OutWhsID=Wo.TypeID ' 
END	
IF @BtypeLimit = 1
Begin
	Select @SqlCreateTable += ' DECLARE @LimitBTYPE AS TABLE(BTypeID INT) Insert into  @LimitBTYPE Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '
End
 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSql += ' Inner Join @LimitKType LW On I.WhsID=LW.TypeID ' 
	Set @LimitSqlIN += ' Inner Join @LimitKType LW On LW.TypeID =i.InWhsID ' 	
	Set @LimitSqlOut += ' Inner Join @LimitKType LW On LW.TypeID =i.OutWhsID ' 	
End	
IF @FinanceID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @FType As Table(TypeID INT) insert into @FType Select f2.FinanceID from BD_Finance f INNER JOIN dbo.UF_OT_Split_Int(@FinanceID,'','') f1 ON f1.typeid=f.FinanceID INNER JOIN BD_Finance f2 ON f2.Path like f.Path+''%'''
	SET @SqlAtype+=' Inner Join @FType F On I.FinanceID=F.TypeID ' 
	SET @SqlFreight+=' Inner Join @FType A On  i.FinanceID=A.TypeID or i.FreightFinanceID = a.TypeID ' 
END	 
if(@Summary <> '')
	Set @conditionStr += ' And Summary ' + case @SummaryMatch when 0 then ' Like ''%''+@Summary+''%''' Else ' =@Summary ' End
if(@Description <> '')
	Set @conditionStr += ' And Description ' + case @DescriptionMatch when 0 then ' Like ''%''+@Description+''%''' Else ' =@Description ' END
IF @LogistBillNo <>'' 
	SET @conditionStr = ' AND LogistBillNo'+CASE @LogistBillNoMatch WHEN 0 THEN ' Like''%''+@LogistBillNo+''%''' ELSE ' =@LogistBillNo' END
if(@Remark <> '')
	Set @conditionStr += ' And Remark ' + case @RemarkMatch when 0 then ' Like ''%''+@Remark+''%''' Else ' =@Remark ' END
if(@BillCode <> '')
	Set @conditionStr += ' And BillCode ' + case @BillCodeMatch when 0 then ' Like ''%''+@BillCode+''%''' Else ' =@BillCode ' END	
/*新增商品查询条件 start 150901*/
DECLARE @NewGoodsParam VARCHAR(4000) = ''
IF(@Model <> '')
	SET @NewGoodsParam += ' AND Model ' + CASE @ModelMatch WHEN 0 THEN ' LIKE ''%''+@Model+''%''' ELSE ' =@Model ' END
IF(@AbbName <> '')
	SET @NewGoodsParam += ' AND GoodsAbbName ' + CASE @AbbNameMatch WHEN 0 THEN ' LIKE ''%''+@AbbName+''%''' ELSE ' =@AbbName ' END
IF(@Brand <> '')
	SET @NewGoodsParam += ' AND Brand ' + CASE @BrandMatch WHEN 0 THEN ' LIKE ''%''+@Brand+''%''' ELSE ' =@Brand ' END
IF(@Spec <> '')
	SET @NewGoodsParam += ' AND Spec ' + CASE @SpecMatch WHEN 0 THEN ' LIKE ''%''+@Spec+''%''' ELSE ' =@Spec ' END
IF @BarCode <> ''
	BEGIN
		SET @SqlCreateTable+=' DECLARE @BarCodeParam AS TABLE(TypeID INT) INSERT INTO @BarCodeParam SELECT DISTINCT GoodsID  FROM dbo.BD_Goods_Price WHERE BarCode ' + CASE @BarCodeMatch WHEN 0 THEN ' Like ''%'' + @BarCode + ''%''' ELSE ' =@BarCode ' END
		SET @SqlTable += ' INNER JOIN @BarCodeParam BParam ON BD.GoodsID = BParam.TypeID '
	END
/*end*/	
if(@FullName <> '' or @UserCode <> '' OR @NewGoodsParam <> '')
Begin
	if(@FullName <> '')
		Set @GoodsMath += ' And GoodsName ' + case @FullNameMatch when 0 then ' Like ''%''+@FullName+''%''' Else ' =@FullName ' END
	if(@UserCode <> '')
		Set @GoodsMath += ' And GoodsNo ' + case @UserCodeMatch when 0 then ' Like ''%''+@UserCode+''%''' Else ' =@UserCode ' END
	SET @SqlCreateTable+=' DECLARE @PType As Table(TypeID INT,GoodsName Varchar(100),GoodsNo varchar(50)) insert into @PType Select GoodsID,GoodsName,GoodsNo from BD_GOODS Where 1=1 '+@GoodsMath+@NewGoodsParam	
	Select @SqlTable += ' Inner Join @PType GT On BD.GoodsID = GT.TypeID '
End
IF @ClassID1 <> 0
Begin
	SET @SqlClass1 +=' DECLARE @CTb1  as Table(typeid int) INSERT INTO @CTb1(typeid) '
	Set @SqlCreateTable += Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											Else '' End
    --Set @SqlTable += Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.WhsID = @ClassID1 ' else 'And exists( Select 1 from @CTb1 C1 where I.WhsID=C1.TypeID )' end
				--					  Else '' End
	Set @sqlWhsClick +=	Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.WhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 On I.WhsID=C1.TypeID ' end
									  Else '' End							 
	Set @sqlWhsInClick +=	Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.INWhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 On I.INWhsID=C1.TypeID ' end
									  Else '' End	
	Set @sqlWhsOutClick +=	Case @ClassType1 when 2 then case @ClaseFlag1 when 0 then ' And I.OutWhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 On I.OutWhsID=C1.TypeID ' end
									  Else '' End										  										  
End
IF @ClassID2 <> 0
Begin
	SET @SqlClass2 +=' DECLARE @CTb2  as Table(typeid int) INSERT INTO @CTb2(typeid) '
	Set @SqlCreateTable += case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') end 											
    Set @SqlTable +=  case @ClaseFlag2 when 0 then ' And BD.GoodsID = @ClassID2 ' else ' Inner Join @CTb2 C2 On BD.GoodsID=C2.TypeID ' end 
End
if(@IsRedFlag=0)
Begin
	Set @Red = ' And Red = 0 '
	Select @PageDataStr += Case When @OrderType1 in ('BTypeCode','BTypeName') then ',bill.BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',bill.GoodsID'
							When @OrderType1 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
							When @OrderType1 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 = '' then ''
							Else ','+ 'bill.' +@OrderType1 End
Select @PageDataStr += Case When @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',bill.BTypeID ' End	
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',bill.GoodsID' end 
							When @OrderType2 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
							When @OrderType2 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 = '' then ''
							Else ','+ 'bill.' +@OrderType2 End

End
Else
Begin
	Set @RedStr = ',Red'
if(@OrderType1 <> '')
	Select @PageDataStr += Case When @OrderType1 in ('BTypeCode','BTypeName') then ',bill.BTypeID '
								When @OrderType1 in ('GoodsNo','GoodsName') then ',bill.GoodsID'
								When @OrderType1 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
								When @OrderType1 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
								When @OrderType1 = 'Qty' then ',Case When Bill.Red=2 then bill.Qty * -1 Else bill.Qty End as Qty'
								When @OrderType1 = 'Total' then ',Case When Bill.Red=2 Then bill.Total * -1 Else bill.Total end as Total'
								When @OrderType1 = 'DiscTotal' then ',Case When Bill.Red=2 then bill.DiscTotal * -1 Else bill.DiscTotal End as DiscTotal'
								When @OrderType1 = 'BillTypeID' then '' 
								When @OrderType1 = '' then ''
								Else ','+ 'bill.' +@OrderType1 End
if(@OrderType2 <> '' )
	Select @PageDataStr += Case When @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',bill.BTypeID ' End
								When @OrderType2 in ('GoodsNo','GoodsName')   then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',bill.GoodsID' end 
								When @OrderType2 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
								When @OrderType2 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
								When @OrderType2 = 'Qty' then ',Case When Bill.Red=2 then bill.Qty * -1 Else bill.Qty End as Qty'
								When @OrderType2 = 'Total' then ',Case When Bill.Red=2 Then bill.Total * -1 Else bill.Total end as Total'
								When @OrderType2 = 'DiscTotal' then ',Case When Bill.Red=2 then bill.DiscTotal * -1 Else bill.DiscTotal End as DiscTotal'
								When @OrderType2 = 'BillTypeID' then '' 
								When @OrderType2 = '' then ''
								Else ','+ 'bill.' +@OrderType2 End	
End

---拼查询条件
if(@OrderType1 <> '')
Begin
	select @buyStr+=Case when @OrderType1 in ('BTypeCode','BTypeName') then ',BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',I.'+@OrderType1
							When @OrderType1 = '' then ''
							else ',BD.'+@OrderType1 end
	select @InOutStr+=Case when @OrderType1 in ('BTypeCode','BTypeName') then ',BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',I.'+@OrderType1
							When @OrderType1 = 'Total' then ',BD.GoodsCostTotal  as Total'
							When @OrderType1 = 'Discount' then ',1 as Discount'
							When @OrderType1 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType1 = 'DiscPrice' Then ',BD.Price  as DiscPrice'
							When @OrderType1 = '' then ''
							else ',BD.'+@OrderType1 end
	select @AllToTStr+=Case when @OrderType1 in ('BTypeCode','BTypeName') then ',0 as BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',I.'+@OrderType1
							When @OrderType1 = 'Discount' then ',1 as Discount'
							When @OrderType1 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType1 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType1 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType1 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType1 = '' then ''
							else ',BD.'+@OrderType1 end
	select @AdjPriceInStr+=Case when @OrderType1 in ('BTypeCode','BTypeName') then ',0 as BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',I.'+@OrderType1
							When @OrderType1 = 'Discount' then ',1 as Discount'
							When @OrderType1 = 'Price' Then ',BD.AdjPrice  as Price'
							When @OrderType1 = 'Total' Then ',BD.AdjTotal  as Total'
							When @OrderType1 = 'DiscPrice' then ',BD.AdjPrice  as DiscPrice'
							When @OrderType1 = 'DiscTotal' then ',BD.AdjTotal  as DiscTotal'
							When @OrderType1 = '' then ''
							else ',BD.'+@OrderType1 end
	select @AdjPriceOutStr+=Case when @OrderType1 in ('BTypeCode','BTypeName') then ',0 as BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',I.'+@OrderType1
							When @OrderType1 = 'Discount' then ',1 as Discount'
							When @OrderType1 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType1 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType1 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType1 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType1 = '' then ''
							else ',BD.'+@OrderType1 end
	select @AssemblyInStr+=Case when @OrderType1 in ('BTypeCode','BTypeName') then ',0 as BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',BD.'+@OrderType1
							When @OrderType1 = 'Discount' then ',1 as Discount'
							When @OrderType1 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType1 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType1 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType1 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType1 = '' then ''
							else ',BD.'+@OrderType1 end
	select @AssemblyOutStr+=Case when @OrderType1 in ('BTypeCode','BTypeName') then ',0 as BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',GoodsID'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',BD.'+@OrderType1
							When @OrderType1 = 'Discount' then ',1 as Discount'
							When @OrderType1 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType1 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType1 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType1 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType1 = '' then ''
							else ',BD.'+@OrderType1 end
End
if(@OrderType2 <> '')
Begin
	select @buyStr+=Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',BTypeID ' End
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',GoodsID' end 
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',I.'+@OrderType2
							When @OrderType2 = '' then ''
							else ',BD.'+@OrderType2 end
	select @InOutStr+=Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',BTypeID ' End
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',GoodsID' end 
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',I.'+@OrderType2
							When @OrderType2 = 'Total' then ',BD.GoodsCostTotal  as Total'
							When @OrderType2 = 'Discount' then ',1 as Discount'
							When @OrderType2 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType2 = 'DiscPrice' Then ',BD.Price  as DiscPrice'
							When @OrderType2 = '' then ''
							else ',BD.'+@OrderType2 end
	select @AllToTStr+=Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',0 as BTypeID ' End 
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',GoodsID' end 
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',I.'+@OrderType2
							When @OrderType2 = 'Discount' then ',1 as Discount'
							When @OrderType2 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType2 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType2 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType2 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType2 = '' then ''
							else ',BD.'+@OrderType2 end
	select @AdjPriceInStr+=Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',0 as BTypeID ' End
							When @OrderType2 in ('GoodsNo','GoodsName')  then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',GoodsID' end 
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',I.'+@OrderType2
							When @OrderType2 = 'Discount' then ',1 as Discount'
							When @OrderType2 = 'Price' Then ',BD.AdjPrice  as Price'
							When @OrderType2 = 'Total' Then ',BD.AdjTotal  as Total'
							When @OrderType2 = 'DiscPrice' then ',BD.AdjPrice  as DiscPrice'
							When @OrderType2 = 'DiscTotal' then ',BD.AdjTotal  as DiscTotal'							
							When @OrderType2 = '' then ''
							else ',BD.'+@OrderType2 end
	select @AdjPriceOutStr+=Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',0 as BTypeID ' End
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',GoodsID' end 
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',I.'+@OrderType2
							When @OrderType2 = 'Discount' then ',1 as Discount'
							When @OrderType2 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType2 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType2 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType2 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType2 = '' then ''
							else ',BD.'+@OrderType2 end
	select @AssemblyInStr+=Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',0 as BTypeID ' End
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',GoodsID' end 
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',BD.'+@OrderType2
							When @OrderType2 = 'Discount' then ',1 as Discount'
							When @OrderType2 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType2 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType2 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType2 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType2 = '' then ''
							else ',BD.'+@OrderType2 end
	select @AssemblyOutStr+=Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',0 as BTypeID ' End
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',GoodsID' end 
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',BD.'+@OrderType2
							When @OrderType2 = 'Discount' then ',1 as Discount'
							When @OrderType2 = 'Price' Then ',BD.CostPrice  as Price'
							When @OrderType2 = 'Total' Then ',BD.GoodsCostTotal  as Total'
							When @OrderType2 = 'DiscPrice' then ',BD.CostPrice  as DiscPrice'
							When @OrderType2 = 'DiscTotal' then ',BD.GoodsCostTotal  as DiscTotal'
							When @OrderType2 = '' then ''
							else ',BD.'+@OrderType2 end
End
select @SaleStr=@buyStr
select @buyRetStr=@buyStr
select @saleRetStr=@buyStr
select @LossSpil=@AllToTStr
Select @AllToBStr=@AllToTStr

---拼查询其他字段条件	
select @buyStrO += ' 101 as BillTypeIDS,'''+'采购入库单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,BTypeID,BD.DiscPrice,BD.Price,BD.Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal '	
select @buyStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@buyStrO,',BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@buyStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@buyStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@buyStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@buyStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@buyStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@buyStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@buyStrO,',BD.Price','') 
					When @OrderType1 = 'Total' then REPLACE(@buyStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@buyStrO,',BD.Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@buyStrO,',BD.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@buyStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @buyStrO end	
select @buyStrO = case when  @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@buyStrO,',BTypeID','')
					when  @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@buyStrO,',BD.GoodsID','')
					When  @OrderType2 = 'BillCode' then REPLACE(@buyStrO,',BillCode','') 
					When  @OrderType2 = 'BillDate' then REPLACE(@buyStrO,',I.BillDate','') 
					When  @OrderType2 = 'CreateTime' then REPLACE(@buyStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When  @OrderType2 = 'PosTime' then REPLACE(@buyStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When  @OrderType2 = 'Qty' then REPLACE(@buyStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When  @OrderType2 = 'Price' then REPLACE(@buyStrO,',BD.Price','') 
					When  @OrderType2 = 'Total' then REPLACE(@buyStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When  @OrderType2 = 'Discount' then REPLACE(@buyStrO,',BD.Discount','') 
					When  @OrderType2 = 'DiscPrice' then REPLACE(@buyStrO,',BD.DiscPrice','') 
					When  @OrderType2 = 'DiscTotal' then REPLACE(@buyStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @buyStrO end					
select @buyRetStrO = ' 102 as BillTypeIDS,'''+'采购退货单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,BTypeID,BD.DiscPrice,BD.Price,BD.Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal '
select @buyRetStrO = case when @OrderType1 in ('BTypeCode','BTypeName')  then REPLACE(@buyRetStrO,',BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName')  then REPLACE(@buyRetStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode'  then REPLACE(@buyRetStrO,',BillCode','') 
					When @OrderType1 = 'BillDate'  then REPLACE(@buyRetStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime'  then REPLACE(@buyRetStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime'  then REPLACE(@buyRetStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty'  then REPLACE(@buyRetStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price'  then REPLACE(@buyRetStrO,',BD.Price','') 
					When @OrderType1 = 'Total'  then REPLACE(@buyRetStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When @OrderType1 = 'Discount'  then REPLACE(@buyRetStrO,',BD.Discount','') 
					When @OrderType1 = 'DiscPrice'  then REPLACE(@buyRetStrO,',BD.DiscPrice','') 
					When @OrderType1 = 'DiscTotal'  then REPLACE(@buyRetStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @buyRetStrO end
select @buyRetStrO = case when  @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@buyRetStrO,',BTypeID','')
					when  @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@buyRetStrO,',BD.GoodsID','')
					When  @OrderType2 = 'BillCode' then REPLACE(@buyRetStrO,',BillCode','') 
					When  @OrderType2 = 'BillDate' then REPLACE(@buyRetStrO,',I.BillDate','') 
					When  @OrderType2 = 'CreateTime' then REPLACE(@buyRetStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When  @OrderType2 = 'PosTime' then REPLACE(@buyRetStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When  @OrderType2 = 'Qty' then REPLACE(@buyRetStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When  @OrderType2 = 'Price' then REPLACE(@buyRetStrO,',BD.Price','') 
					When  @OrderType2 = 'Total' then REPLACE(@buyRetStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When  @OrderType2 = 'Discount' then REPLACE(@buyRetStrO,',BD.Discount','') 
					When  @OrderType2 = 'DiscPrice' then REPLACE(@buyRetStrO,',BD.DiscPrice','') 
					When  @OrderType2 = 'DiscTotal' then REPLACE(@buyRetStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @buyRetStrO end				
Select @SaleStrO = ' 201 as BillTypeIDS,'''+'销售出库单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID,BD.UnitID,1 as BsUnitID,LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,BTypeID,BD.DiscPrice,BD.Price,BD.Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal '
select @SaleStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@SaleStrO,',BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@SaleStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@SaleStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@SaleStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@SaleStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@SaleStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@SaleStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price'  then REPLACE(@SaleStrO,',BD.Price','') 
					When @OrderType1 = 'Total'  then REPLACE(@SaleStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When @OrderType1 = 'Discount'  then REPLACE(@SaleStrO,',BD.Discount','') 
					When @OrderType1 = 'DiscPrice'  then REPLACE(@SaleStrO,',BD.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@SaleStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @SaleStrO end
select @SaleStrO = case when  @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@SaleStrO,',BTypeID','')
					when  @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@SaleStrO,',BD.GoodsID','')
					When  @OrderType2 = 'BillCode' then REPLACE(@SaleStrO,',BillCode','') 
					When  @OrderType2 = 'BillDate' then REPLACE(@SaleStrO,',I.BillDate','') 
					When  @OrderType2 = 'CreateTime' then REPLACE(@SaleStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When  @OrderType2 = 'PosTime' then REPLACE(@SaleStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When  @OrderType2 = 'Qty' then REPLACE(@SaleStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When  @OrderType2 = 'Price' then REPLACE(@SaleStrO,',BD.Price','') 
					When  @OrderType2 = 'Total' then REPLACE(@SaleStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When  @OrderType2 = 'Discount' then REPLACE(@SaleStrO,',BD.Discount','') 
					When  @OrderType2 = 'DiscPrice' then REPLACE(@SaleStrO,',BD.DiscPrice','') 
					When  @OrderType2 = 'DiscTotal' then REPLACE(@SaleStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @SaleStrO end		
select @saleRetStrO += ' 202 as BillTypeIDS,'''+'销售退货单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty, 0 as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,BTypeID,BD.DiscPrice,BD.Price,BD.Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total
		,Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal '	
select @saleRetStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@saleRetStrO,',BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@saleRetStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@saleRetStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@saleRetStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@saleRetStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@saleRetStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@saleRetStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@saleRetStrO,',BD.Price','') 
					When @OrderType1 = 'Total' then REPLACE(@saleRetStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@saleRetStrO,',BD.Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@saleRetStrO,',BD.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@saleRetStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @saleRetStrO end	
select @saleRetStrO = case when  @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@saleRetStrO,',BTypeID','')
					when  @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@saleRetStrO,',BD.GoodsID','')
					When  @OrderType2 = 'BillCode' then REPLACE(@saleRetStrO,',BillCode','') 
					When  @OrderType2 = 'BillDate' then REPLACE(@saleRetStrO,',I.BillDate','') 
					When  @OrderType2 = 'CreateTime' then REPLACE(@saleRetStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When  @OrderType2 = 'PosTime' then REPLACE(@saleRetStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When  @OrderType2 = 'Qty' then REPLACE(@saleRetStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When  @OrderType2 = 'Price' then REPLACE(@saleRetStrO,',BD.Price','') 
					When  @OrderType2 = 'Total' then REPLACE(@saleRetStrO,',Case When I.Red=2 Then BD.Total * -1 Else Bd.Total end as Total','') 
					When  @OrderType2 = 'Discount' then REPLACE(@saleRetStrO,',BD.Discount','') 
					When  @OrderType2 = 'DiscPrice' then REPLACE(@saleRetStrO,',BD.DiscPrice','') 
					When  @OrderType2 = 'DiscTotal' then REPLACE(@saleRetStrO,',Case When I.Red=2 then BD.DiscTotal * -1 Else BD.DiscTotal End as DiscTotal','') 
					Else @saleRetStrO end				
Select @AllToTOutStrO = ' 301 as BillTypeIDS,'''+'同价调拨单(出库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.OutWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice,case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @AllToTOutStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@AllToTOutStrO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@AllToTOutStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@AllToTOutStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@AllToTOutStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@AllToTOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@AllToTOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@AllToTOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@AllToTOutStrO,',case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@AllToTOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@AllToTOutStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@AllToTOutStrO,',case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType1 = 'DiscTotal'  then REPLACE(@AllToTOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AllToTOutStrO end
select @AllToTOutStrO = case when  @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@AllToTOutStrO,',0 as BTypeID','')
					when  @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@AllToTOutStrO,',BD.GoodsID','')
					When  @OrderType2 = 'BillCode' then REPLACE(@AllToTOutStrO,',BillCode','') 
					When  @OrderType2 = 'BillDate' then REPLACE(@AllToTOutStrO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@AllToTOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When  @OrderType2 = 'PosTime' then REPLACE(@AllToTOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When  @OrderType2 = 'Qty' then REPLACE(@AllToTOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When  @OrderType2 = 'Price' then REPLACE(@AllToTOutStrO,',case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When  @OrderType2 = 'Total' then REPLACE(@AllToTOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When  @OrderType2 = 'Discount' then REPLACE(@AllToTOutStrO,',1 as Discount','') 
					When  @OrderType2 = 'DiscPrice' then REPLACE(@AllToTOutStrO,',case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When  @OrderType2 = 'DiscTotal' then REPLACE(@AllToTOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AllToTOutStrO end
Select @AllToBOutStrO = REPLACE(@AllToTOutStrO,'301','309')
Select @AllToBOutStrO = REPLACE(@AllToBOutStrO,'同价','变价')
Select @AllToTInStrO = ' 301 as BillTypeIDS,'''+'同价调拨单(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.InWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		, 0 as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice,case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @AllToTInStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@AllToTInStrO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@AllToTInStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@AllToTInStrO,',BillCode','') 
					When @OrderType1 = 'BillDate'  then REPLACE(@AllToTInStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@AllToTInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@AllToTInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@AllToTInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@AllToTInStrO,',case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@AllToTInStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@AllToTInStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@AllToTInStrO,',case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@AllToTInStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AllToTInStrO end
select @AllToTInStrO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@AllToTInStrO,',0 as BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@AllToTInStrO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@AllToTInStrO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@AllToTInStrO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@AllToTInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@AllToTInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@AllToTInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@AllToTInStrO,',case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@AllToTInStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@AllToTInStrO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@AllToTInStrO,',case when BD.Qty = 0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@AllToTInStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AllToTInStrO end
Select @AllToBInStrO = ' 309 as BillTypeIDS,'''+'变价调拨单(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.InWhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,case BD.BSQty when 0 then 0 else Cast(BD.AllotTotal as decimal(20,8))/BD.BSQty end As CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		, 0 as OutQty,
		Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,BD.AllotPrice as DiscPrice,BD.AllotPrice as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.AllotTotal * -1 Else Bd.AllotTotal end as Total
		,Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as DiscTotal '
select @AllToBInStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@AllToBInStrO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@AllToBInStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@AllToBInStrO,',BillCode','') 
					When @OrderType1 = 'BillDate'  then REPLACE(@AllToBInStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@AllToBInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@AllToBInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@AllToBInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@AllToBInStrO,',BD.AllotPrice as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@AllToBInStrO,',Case When I.Red=2 Then BD.AllotTotal * -1 Else Bd.AllotTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@AllToBInStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@AllToBInStrO,',BD.AllotPrice as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@AllToBInStrO,',Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as DiscTotal','') 
					Else @AllToBInStrO end
select @AllToBInStrO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@AllToBInStrO,',0 as BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@AllToBInStrO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@AllToBInStrO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@AllToBInStrO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@AllToBInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@AllToBInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@AllToBInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@AllToBInStrO,',BD.AllotPrice as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@AllToBInStrO,',Case When I.Red=2 Then BD.AllotTotal * -1 Else Bd.AllotTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@AllToBInStrO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@AllToBInStrO,',BD.AllotPrice as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@AllToBInStrO,',Case When I.Red=2 then BD.AllotTotal * -1 Else BD.AllotTotal End as DiscTotal','') 
					Else @AllToBInStrO end					
Select @AdjPriceOutStrO = ' 302 as BillTypeIDS,'''+'调价单(出库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end DiscPrice,case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @AdjPriceOutStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@AdjPriceOutStrO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@AdjPriceOutStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@AdjPriceOutStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@AdjPriceOutStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@AdjPriceOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@AdjPriceOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@AdjPriceOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@AdjPriceOutStrO,',case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@AdjPriceOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@AdjPriceOutStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@AdjPriceOutStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@AdjPriceOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AdjPriceOutStrO end
select @AdjPriceOutStrO = case when  @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@AdjPriceOutStrO,',0 as BTypeID','')
					when  @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@AdjPriceOutStrO,',BD.GoodsID','')
					When  @OrderType2 = 'BillCode' then REPLACE(@AdjPriceOutStrO,',BillCode','') 
					When  @OrderType2 = 'BillDate' then REPLACE(@AdjPriceOutStrO,',I.BillDate','') 
					When  @OrderType2 = 'CreateTime' then REPLACE(@AdjPriceOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When  @OrderType2 = 'PosTime' then REPLACE(@AdjPriceOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When  @OrderType2 = 'Qty' then REPLACE(@AdjPriceOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When  @OrderType2 = 'Price' then REPLACE(@AdjPriceOutStrO,',case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When  @OrderType2 = 'Total' then REPLACE(@AdjPriceOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@AdjPriceOutStrO,',1 as Discount','') 
					When  @OrderType2 = 'DiscPrice' then REPLACE(@AdjPriceOutStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@AdjPriceOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AdjPriceOutStrO end
Select @AdjPriceInStrO = ' 302 as BillTypeIDS,'''+'调价单(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,case BD.BSQty when 0 then 0 else Cast(BD.AdjTotal as decimal(20,8))/BD.BSQty end as CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		,0 as OutQty,
		Case When I.Red=2 then BD.AdjTotal * -1 Else BD.AdjTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,BD.AdjPrice as DiscPrice,BD.AdjPrice as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.AdjTotal * -1 Else Bd.AdjTotal end as Total
		,Case When I.Red=2 then BD.AdjTotal * -1 Else BD.AdjTotal End as DiscTotal '
select @AdjPriceInStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@AdjPriceInStrO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@AdjPriceInStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@AdjPriceInStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@AdjPriceInStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@AdjPriceInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@AdjPriceInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@AdjPriceInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@AdjPriceInStrO,',BD.AdjPrice as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@AdjPriceInStrO,',Case When I.Red=2 Then BD.AdjTotal * -1 Else Bd.AdjTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@AdjPriceInStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@AdjPriceInStrO,',BD.AdjPrice as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@AdjPriceInStrO,',Case When I.Red=2 then BD.AdjTotal * -1 Else BD.AdjTotal End as DiscTotal','') 
					Else @AdjPriceInStrO end
select @AdjPriceInStrO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@AdjPriceInStrO,',0 as BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@AdjPriceInStrO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@AdjPriceInStrO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@AdjPriceInStrO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@AdjPriceInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@AdjPriceInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@AdjPriceInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@AdjPriceInStrO,',BD.AdjPrice as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@AdjPriceInStrO,',Case When I.Red=2 Then BD.AdjTotal * -1 Else Bd.AdjTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@AdjPriceInStrO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@AdjPriceInStrO,',BD.AdjPrice as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@AdjPriceInStrO,',Case When I.Red=2 then BD.AdjTotal * -1 Else BD.AdjTotal End as DiscTotal','') 
					Else @AdjPriceInStrO end
					
Select @AssemblyOutStrO = ' 310 as BillTypeIDS,'''+'生产拆装(出库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @AssemblyOutStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@AssemblyOutStrO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@AssemblyOutStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@AssemblyOutStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@AssemblyOutStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@AssemblyOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@AssemblyOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@AssemblyOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@AssemblyOutStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@AssemblyOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@AssemblyOutStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@AssemblyOutStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@AssemblyOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AssemblyOutStrO end
select @AssemblyOutStrO = case when  @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@AssemblyOutStrO,',0 as BTypeID','')
					when  @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@AssemblyOutStrO,',BD.GoodsID','')
					When  @OrderType2 = 'BillCode' then REPLACE(@AssemblyOutStrO,',BillCode','') 
					When  @OrderType2 = 'BillDate' then REPLACE(@AssemblyOutStrO,',I.BillDate','') 
					When  @OrderType2 = 'CreateTime' then REPLACE(@AssemblyOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When  @OrderType2 = 'PosTime' then REPLACE(@AssemblyOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@AssemblyOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@AssemblyOutStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@AssemblyOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@AssemblyOutStrO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@AssemblyOutStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@AssemblyOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AssemblyOutStrO end
Select @AssemblyInStrO = ' 310 as BillTypeIDS,'''+'生产拆装(入库)'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		,0 as OutQty,
		BD.GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @AssemblyInStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@AssemblyInStrO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@AssemblyInStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@AssemblyInStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@AssemblyInStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@AssemblyInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@AssemblyInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@AssemblyInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@AssemblyInStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@AssemblyInStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@AssemblyInStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@AssemblyInStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@AssemblyInStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AssemblyInStrO end
select @AssemblyInStrO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@AssemblyInStrO,',0 as BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@AssemblyInStrO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@AssemblyInStrO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@AssemblyInStrO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@AssemblyInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@AssemblyInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@AssemblyInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@AssemblyInStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@AssemblyInStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@AssemblyInStrO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@AssemblyInStrO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@AssemblyInStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @AssemblyInStrO end
					
Select @InOutInStrO = ' 303 as BillTypeIDS,'''+'其他入库单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice as CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		,0 as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,BTypeID,BD.Price as DiscPrice,BD.Price as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @InOutInStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@InOutInStrO,',BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@InOutInStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@InOutInStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@InOutInStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@InOutInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@InOutInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@InOutInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@InOutInStrO,',BD.Price as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@InOutInStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@InOutInStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@InOutInStrO,',BD.Price as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@InOutInStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @InOutInStrO end
select @InOutInStrO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@InOutInStrO,',BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@InOutInStrO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@InOutInStrO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@InOutInStrO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@InOutInStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@InOutInStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@InOutInStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@InOutInStrO,',BD.Price as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@InOutInStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@InOutInStrO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@InOutInStrO,',BD.Price as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@InOutInStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @InOutInStrO end
Select @InOutOutStrO = ' 304 as BillTypeIDS,'''+'其他出库单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice as CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		0 as InQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,BTypeID,BD.Price as DiscPrice,BD.Price as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @InOutOutStrO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@InOutOutStrO,',BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@InOutOutStrO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@InOutOutStrO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@InOutOutStrO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@InOutOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@InOutOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@InOutOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@InOutOutStrO,',BD.Price as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@InOutOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@InOutOutStrO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@InOutOutStrO,',BD.Price as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@InOutOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @InOutOutStrO end	
select @InOutOutStrO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@InOutOutStrO,',BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@InOutOutStrO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@InOutOutStrO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@InOutOutStrO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@InOutOutStrO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@InOutOutStrO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@InOutOutStrO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@InOutOutStrO,',BD.Price as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@InOutOutStrO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@InOutOutStrO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@InOutOutStrO,',BD.Price as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@InOutOutStrO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @InOutOutStrO end
SET @InOutExchangeStrO = REPLACE(REPLACE(@InOutOutStrO,304,600),'其他出库单','积分兑换单') 				
Select @LossSpilInO = ' 306 as BillTypeIDS,'''+'报溢单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice as CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty
		, 0 as OutQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice,case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @LossSpilInO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@LossSpilInO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@LossSpilInO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@LossSpilInO,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@LossSpilInO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@LossSpilInO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@LossSpilInO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@LossSpilInO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@LossSpilInO,',case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType1 = 'Total' then REPLACE(@LossSpilInO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@LossSpilInO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@LossSpilInO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@LossSpilInO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @LossSpilInO end	
select @LossSpilInO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@LossSpilInO,',0 as BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@LossSpilInO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@LossSpilInO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@LossSpilInO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@LossSpilInO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@LossSpilInO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@LossSpilInO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@LossSpilInO,',case when BD.Qty =0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@LossSpilInO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@LossSpilInO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@LossSpilInO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@LossSpilInO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @LossSpilInO end
Select @LossSpilOutO = ' 305 as BillTypeIDS,'''+'报损单'+''' AS BillName,BD.BillNo,Creator,PosElyID,DeptID,ElyID,BD.Ppt1ID,BD.Ppt2ID,
		BD.WhsID as WhsID,BD.UnitID,1 as BsUnitID,'''' as LogistBillNo,BD.CostPrice as CostPrice,BD.BatchNumber,BD.ProductDate,BD.EndDate,
		 0 as OutQty,
		Case When I.Red=2 then BD.BSQty*-1 Else BD.BSQty End as InQty,
		Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as GoodsCostTotal
		,BillCode,I.BillDate,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,BD.GoodsID,0 as BTypeID,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice,case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price,1 as Discount
		,Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty
		,Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total
		,Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal '
select @LossSpilOutO = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@LossSpilOutO,',0 as BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName')  then REPLACE(@LossSpilOutO,',BD.GoodsID','')
					When @OrderType1 = 'BillCode'  then REPLACE(@LossSpilOutO,',BillCode','') 
					When @OrderType1 = 'BillDate'  then REPLACE(@LossSpilOutO,',I.BillDate','') 
					When @OrderType1 = 'CreateTime'  then REPLACE(@LossSpilOutO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@LossSpilOutO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty'  then REPLACE(@LossSpilOutO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType1 = 'Price'  then REPLACE(@LossSpilOutO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType1 = 'Total'  then REPLACE(@LossSpilOutO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType1 = 'Discount'  then REPLACE(@LossSpilOutO,',1 as Discount','') 
					When @OrderType1 = 'DiscPrice'  then REPLACE(@LossSpilOutO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType1 = 'DiscTotal'  then REPLACE(@LossSpilOutO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @LossSpilOutO end	
select @LossSpilOutO = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@LossSpilOutO,',0 as BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@LossSpilOutO,',BD.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@LossSpilOutO,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@LossSpilOutO,',I.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@LossSpilOutO,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@LossSpilOutO,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@LossSpilOutO,',Case When I.Red=2 then BD.Qty * -1 Else Bd.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@LossSpilOutO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as Price','') 
					When @OrderType2 = 'Total' then REPLACE(@LossSpilOutO,',Case When I.Red=2 Then BD.GoodsCostTotal * -1 Else Bd.GoodsCostTotal end as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@LossSpilOutO,',1 as Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@LossSpilOutO,',case when BD.Qty=0 then 0 else Cast((BD.CostPrice*BD.BSQty) as decimal(20,8))/BD.Qty end as DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@LossSpilOutO,',Case When I.Red=2 then BD.GoodsCostTotal * -1 Else BD.GoodsCostTotal End as DiscTotal','') 
					Else @LossSpilOutO end					
select @sql +='
	UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID, '
	+ Case  When BillTypeID = 101 then @buyStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			When BillTypeID = 102 then @buyRetStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			When BillTypeID = 201 then @SaleStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			When BillTypeID = 202 then @saleRetStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			When BillTypeID = 303 then @InOutStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			When BillTypeID = 304 then @InOutStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			When BillTypeID = 305 then @LossSpil + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			When BillTypeID = 306 then @LossSpil + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			WHEN BillTypeID = 600 then @InOutStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]'
			Else '' End	
	 + @RedStr
	+' FROM  ' + BillDetail + ' BD  Inner Join '+BillTable+' I On I.BillNo=bd.BillNo '
	+ CASE WHEN @ShowSerial = 1 THEN ' LEFT JOIN ' + BillSerial + ' Serial ON BD.DID = Serial.BillDID ' ELSE '' End -- 连接单据序列号表
	+ @SqlTable + @sqlWhsClick + @LimitSql
	+ @SqlWhs 
	--+ Case When BillTypeID = 201 then @SqlFreight Else @SqlAtype End  只有单账户情况下 update 150619
	+ ' where 
	 BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red 
	
	+CASE WHEN @FinanceID='' OR billtypeid NOT IN(101,201,102,202) THEN '' ELSE ' AND EXISTS(SELECT 1 FROM @FType A WHERE I.FinanceID=A.TypeID '+case when billtypeid in (101,201) THEN 'OR I.FreightFinanceID=A.TypeID ' ELSE '' END+'
			OR EXISTS(SELECT 1 FROM PD_MulAccounts M WHERE M.BillTypeID='+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo and M.FinanceID= a.TypeID))' END 
	  	
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	+@conditionStr
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0 
WHERE CanPost=1 and billtype not in (301,302,309,310)
IF EXISTS (select 1 from #BillType where billtype= 301)
BEGIN
	IF @BillFlag = 1 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	SELECT @Sql+='
		UNION ALL 
			SELECT  30101 AS BillTypeID, '+@AllToTStr+ @SeriesCol1 + @RedStr + ',BD.OutWhsID[DetailWhsID]' + ' 
			FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '
			+ @301
			+@SqlTable +@sqlWhsOutClick + @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 301 ' +@Red		
			+@conditionStr
	IF @BillFlag = 2 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	SELECT @Sql +='
		UNION ALL 
			SELECT  30102 AS BillTypeID, '+@AllToTStr+ @SeriesCol1 + @RedStr + ',BD.InWhsID[DetailWhsID]' + ' 
			FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '
			+ @301
			+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 301 ' + @Red + @InspectTagStr
			+@conditionStr
END
IF EXISTS (select 1 from #BillType where billtype= 309)
BEGIN
	IF @BillFlag = 1 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	SELECT @Sql+='
		UNION ALL 
			SELECT  30901 AS BillTypeID, '+@AllToBStr+ @SeriesCol1 + @RedStr + ',BD.OutWhsID[DetailWhsID]' + ' 
			FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '
			+ @309
			+@SqlTable +@sqlWhsOutClick + @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 309 ' +@Red		
			+@conditionStr
	IF @BillFlag = 2 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
		SELECT @Sql +='
		UNION ALL 
			SELECT  30902 AS BillTypeID, '+@AllToBStr+ @SeriesCol2 + @RedStr + ',BD.InWhsID[DetailWhsID]' + ' 
			FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '
			+ @309
			+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 309 ' + @Red+ @InspectTagStr
			+@conditionStr
END
IF EXISTS (select 1 from #BillType where billtype= 302)
BEGIN
	IF @BillFlag = 3 or @BillFlag = 0	
		SELECT @Sql+='
		UNION ALL 
			SELECT  30201 AS BillTypeID, ' + @AdjPriceInStr + @SeriesCol1 + @RedStr + ',BD.WhsID[DetailWhsID]' + ' 
			FROM  PD_AdjPriceDetail BD  Inner Join PD_AdjPriceBill I On I.BillNo=bd.BillNo '
			+ @302
			+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
			+@conditionStr
	IF @BillFlag = 4 or @BillFlag = 0	
		SELECT @Sql +='
		UNION ALL 
			SELECT  30202 AS BillTypeID, ' + @AdjPriceOutStr+ @SeriesCol3 + @RedStr + ',BD.WhsID[DetailWhsID]' + ' 
			FROM  PD_AdjPriceDetail BD  Inner Join PD_AdjPriceBill I On I.BillNo=bd.BillNo '
			+ @302
			+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
			+@conditionStr
END
IF EXISTS (select 1 from #BillType where billtype= 310)
BEGIN
	IF @BillFlag = 5 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @InWhsID <> '')
		SELECT @Sql+='
		UNION ALL 
			SELECT  31001 AS BillTypeID, ' + @AssemblyInStr + @SeriesCol1 + @RedStr + ',BD.WhsID[DetailWhsID]'  + ' 
			FROM  PD_AssemblyDetail BD  Inner Join PD_AssemblyBill I On I.BillNo=bd.BillNo '
			+ @310
			+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=1 ' + @Red
			+@conditionStr
	IF @BillFlag = 6 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @OutWhsID <> '')
		Select @Sql +='
		UNION ALL 
			SELECT  31002 AS BillTypeID, ' + @AssemblyOutStr+ @SeriesCol1 + @RedStr + ',BD.WhsID[DetailWhsID]'  + ' 
			FROM  PD_AssemblyDetail BD  Inner Join PD_AssemblyBill I On I.BillNo=bd.BillNo '
			+ @310
			+@SqlTable + @sqlWhsOutClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
			BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=2 ' + @Red
			+@conditionStr
END

IF @isHistory = 1
BEGIN
	select @sql +='
	UNION ALL 
		SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID, '
	+ Case  When BillTypeID = 101 then @buyStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 102 then @buyRetStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 201 then @SaleStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 202 then @saleRetStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 303 then @InOutStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 304 then @InOutStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 305 then @LossSpil + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 306 then @LossSpil + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			When BillTypeID = 600 then @InOutStr + @SeriesCol1 + ',BD.WhsID[DetailWhsID]' 
			Else '' End	 + @RedStr
		+' FROM  ' + BillDetail + '_His BD  Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo '
		+ CASE WHEN @ShowSerial = 1 THEN ' LEFT JOIN ' + BillSerial + '_His Serial ON BD.DID = Serial.BillDID ' ELSE '' End -- 连接单据序列号表
		+ @SqlTable + @sqlWhsClick	+ @LimitSql	
		+ @SqlWhs 
		--+ Case When BillTypeID = 201 then @SqlFreight Else @SqlAtype End  只有单账户情况 update 150619
		+' where 
		BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red 
		
		+CASE WHEN @FinanceID='' OR billtypeid NOT IN(101,201,102,202,403,404,405,406) THEN '' ELSE ' AND EXISTS(SELECT 1 FROM @FType A WHERE I.FinanceID=A.TypeID '+case when billtypeid in (101,201) THEN 'OR I.FreightFinanceID=A.TypeID ' ELSE '' END+'
			OR EXISTS(SELECT 1 FROM PD_MulAccounts M WHERE M.BillTypeID='+Cast(BillTypeID AS varchar)+' AND M.BillNo=I.BillNo and M.FinanceID= a.TypeID))' END
		
		+CASE WHEN BillTable+'_His' IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+@conditionStr
	FROM PD_BillType b
	INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0 
	WHERE CanPost=1 and billtype not in (301,302,309,310)
	IF EXISTS (select 1 from #BillType where billtype= 301)
	BEGIN
		IF @BillFlag = 1 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = ''  and @OutWhsID = '')
			SELECT @Sql+='
			UNION ALL 
				SELECT  30101 AS BillTypeID, '+@AllToTStr+ @SeriesCol1+ @RedStr + ',BD.OutWhsID[DetailWhsID]'   + ' 
				FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ @301_His
				+@SqlTable + @sqlWhsOutClick+ @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 301 ' +@Red
				+@conditionStr
		IF @BillFlag = 2 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
			SELECT @Sql +='
			UNION ALL 
				SELECT  30102 AS BillTypeID, '+@AllToTStr+ @SeriesCol1+ @RedStr + ',BD.InWhsID[DetailWhsID]'   + ' 
				FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ @301_His
				+@SqlTable + @sqlWhsInClick + @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 301 ' + @Red+ @InspectTagStr
				+@conditionStr
	END
	IF EXISTS (select 1 from #BillType where billtype= 309)
	BEGIN
		IF @BillFlag = 1 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0 and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = ''  and @OutWhsID = '')
			SELECT @Sql+='
			UNION ALL 
				SELECT  30901 AS BillTypeID, '+@AllToBStr+ @SeriesCol1+ @RedStr + ',BD.OutWhsID[DetailWhsID]'   + ' 
				FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ @309_His
				+@SqlTable + @sqlWhsOutClick+ @LimitSqlOut+ @SqlWhsOut + @SqlWhsin+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 309 ' +@Red
				+@conditionStr
		IF @BillFlag = 2 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
			SELECT @Sql +='
			UNION ALL 
				SELECT  30902 AS BillTypeID, '+@AllToBStr+ @SeriesCol2+ @RedStr + ',BD.InWhsID[DetailWhsID]'   + ' 
				FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ @309_His
				+@SqlTable + @sqlWhsInClick + @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 AND I.BillTypeID = 309 ' + @Red+ @InspectTagStr
				+@conditionStr
	END
	IF EXISTS (select 1 from #BillType where billtype= 302)
	BEGIN
		IF @BillFlag = 3 or @BillFlag = 0	
			SELECT @Sql+='
			UNION ALL 
				SELECT  30201 AS BillTypeID, ' + @AdjPriceInStr + @SeriesCol1+ @RedStr + ',BD.WhsID[DetailWhsID]'   + ' 
				FROM  PD_AdjPriceDetail_His BD  Inner Join PD_AdjPriceBill_His I On I.BillNo=bd.BillNo '
				+ @302_His
				+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
				+@conditionStr
		IF @BillFlag = 4 or @BillFlag = 0	
			SELECT @Sql +='
			UNION ALL 
				SELECT  30202 AS BillTypeID, ' + @AdjPriceOutStr+ @SeriesCol3+ @RedStr + ',BD.WhsID[DetailWhsID]'   + ' 
				FROM  PD_AdjPriceDetail_His BD  Inner Join PD_AdjPriceBill_His I On I.BillNo=bd.BillNo '
				+ @302_His
				+@SqlTable + @sqlWhsClick + @LimitSql+ @SqlWhs+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 ' + @Red
				+@conditionStr
	END
	IF EXISTS (select 1 from #BillType where billtype= 310)
	BEGIN
		IF @BillFlag = 5 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @InWhsID <> '')
			SELECT @Sql+='
			UNION ALL 
				SELECT  31001 AS BillTypeID, ' + @AssemblyInStr + @SeriesCol1+ @RedStr + ',BD.WhsID[DetailWhsID]'   + ' 
				FROM  PD_AssemblyDetail_His BD  Inner Join PD_AssemblyBill_His I On I.BillNo=bd.BillNo '
				+ @310_His
				+@SqlTable + @sqlWhsInClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=1 ' + @Red
				+@conditionStr
		IF @BillFlag = 6 or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '') or (@BillFlag = 0 and @OutWhsID <> '')
			SELECT @Sql +='
			UNION ALL 
				SELECT  31002 AS BillTypeID, ' + @AssemblyOutStr+ @SeriesCol1+ @RedStr + ',BD.WhsID[DetailWhsID]'   + ' 
				FROM  PD_AssemblyDetail_His BD  Inner Join PD_AssemblyBill_His I On I.BillNo=bd.BillNo '
				+ @310_His
				+@SqlTable + @sqlWhsOutClick+ @LimitSqlIN+ @SqlWhsin + @SqlWhsOut+' where 
				BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And DetailType=2 ' + @Red
				+@conditionStr
	END
END

SELECT @sqlOut +='
	UNION ALL 
	SELECT A.*, '
	+ Case  When BillTypeID = 101 then @buyStrO
			When BillTypeID = 102 then @buyRetStrO
			When BillTypeID = 201 then @SaleStrO
			When BillTypeID = 202 then @saleRetStrO
			When BillTypeID = 303 then @InOutInStrO
			When BillTypeID = 304 then @InOutOutStrO
			When BillTypeID = 305 then @LossSpilOutO
			When BillTypeID = 306 then @LossSpilInO
			WHEN BillTypeID = 600 then @InOutExchangeStrO
			Else '' End	
	+' FROM #InOutTemp A Inner Join ' + BillDetail + ' BD On A.DID=BD.DID Inner Join '+BillTable+' I On I.BillNo=bd.BillNo' 
	+ ' where A.BillTypeID = ' +Cast(BillTypeID AS varchar)
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0 
WHERE CanPost=1 and billtype not in (301,302,309,310)
if exists (select 1 from #BillType where billtype= 301)
begin
  if @BillFlag = 1 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @sqlOut+='
	UNION ALL 
		SELECT  A.*, '+@AllToTOutStrO+' 
		FROM  #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' 
		+ ' where A.BillTypeID = 30101 '
  if @BillFlag = 2 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @sqlOut +='
	UNION ALL 
		SELECT  A.*, '+@AllToTInStrO+' 
		FROM #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '
		+ ' where A.BillTypeID = 30102 '
End
if exists (select 1 from #BillType where billtype= 309)
begin
  if @BillFlag = 1 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @sqlOut+='
	UNION ALL 
		SELECT  A.*, '+@AllToBOutStrO+' 
		FROM  #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo ' 
		+ ' where A.BillTypeID = 30901 '
  if @BillFlag = 2 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
	Select @sqlOut +='
	UNION ALL 
		SELECT  A.*, '+@AllToBInStrO+' 
		FROM #InOutTemp A Inner Join PD_AllotDetail BD On A.DID=BD.DID Inner Join PD_AllotBill I On I.BillNo=bd.BillNo '
		+ ' where A.BillTypeID = 30902 '
End
if exists (select 1 from #BillType where billtype= 302)
begin
  if @BillFlag = 3 or @BillFlag = 0	
	Select @sqlOut+='
	UNION ALL 
		SELECT  A.*, ' + @AdjPriceInStrO +' 
		FROM  #InOutTemp A Inner Join PD_AdjPriceDetail BD On A.DID=BD.DID Inner Join PD_AdjPriceBill I On I.BillNo=bd.BillNo '
		+ ' where A.BillTypeID = 30201 '
  if @BillFlag = 4 or @BillFlag = 0	
	Select @sqlOut +='
	UNION ALL 
		SELECT  A.*, ' + @AdjPriceOutStrO+' 
		FROM  #InOutTemp A Inner Join PD_AdjPriceDetail BD On A.DID=BD.DID Inner Join PD_AdjPriceBill I On I.BillNo=bd.BillNo '
		+ ' where A.BillTypeID = 30202 '
End
if exists (select 1 from #BillType where billtype= 310)
begin
  if @BillFlag = 5 or @BillFlag = 0	
	Select @sqlOut+='
	UNION ALL 
		SELECT  A.*, ' + @AssemblyInStrO +' 
		FROM  #InOutTemp A Inner Join PD_AssemblyDetail BD On A.DID=BD.DID Inner Join PD_AssemblyBill I On I.BillNo=bd.BillNo '
		+ ' where A.BillTypeID = 31001 And BD.DetailType = 1 '
  if @BillFlag = 6 or @BillFlag = 0	
	Select @sqlOut +='
	UNION ALL 
		SELECT  A.*, ' + @AssemblyOutStrO+' 
		FROM  #InOutTemp A Inner Join PD_AssemblyDetail BD On A.DID=BD.DID Inner Join PD_AssemblyBill I On I.BillNo=bd.BillNo '
		+ ' where A.BillTypeID = 31002 And BD.DetailType = 2 '
End

IF @isHistory=1
BEGIN
	SELECT @sqlOut +='
	UNION ALL 
		SELECT   A.*,'
	+ Case   When BillTypeID = 101 then @buyStrO
			When BillTypeID = 102 then @buyRetStrO
			When BillTypeID = 201 then @SaleStrO
			When BillTypeID = 202 then @saleRetStrO
			When BillTypeID = 303 then @InOutInStrO
			When BillTypeID = 304 then @InOutOutStrO
			When BillTypeID = 305 then @LossSpilOutO
			When BillTypeID = 306 then @LossSpilInO
			WHEN BillTypeID = 600 then @InOutExchangeStrO
			Else '' End	
		+' FROM  #InOutTemp A Inner Join ' + BillDetail + '_His BD On A.DID=BD.DID Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo '
		+ ' where A.BillTypeID = ' +Cast(BillTypeID AS varchar)
	FROM PD_BillType b
	INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0 
	WHERE CanPost=1 and billtype not in (301,302,309,310)
	IF EXISTS (select 1 from #BillType where billtype= 301)
	BEGIN
		if @BillFlag = 1 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = ''  and @OutWhsID = '')
			SELECT @sqlOut+='
			UNION ALL 
				SELECT  A.*, '+@AllToTOutStrO+' 
				FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 30101 '			
		IF @BillFlag = 2 or (@BillFlag = 0 and charindex('301',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
			SELECT @sqlOut +='
			UNION ALL 
				SELECT  A.*, '+@AllToTInStrO+' 
				FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 30102 '
	END
	IF EXISTS (select 1 from #BillType where billtype= 309)
	BEGIN
		IF @BillFlag = 1 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @OutWhsID <> '') or (@BillFlag = 0 and @InWhsID = ''  and @OutWhsID = '')
			SELECT @sqlOut+='
			UNION ALL 
				SELECT  A.*, '+@AllToBOutStrO+' 
				FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 30901 '			
		IF @BillFlag = 2 or (@BillFlag = 0 and charindex('309',@BillTypeID)>0  and @InWhsID <> '') or (@BillFlag = 0 and @InWhsID = '' and @OutWhsID = '')
			Select @sqlOut +='
			UNION ALL 
				SELECT  A.*, '+@AllToBInStrO+' 
				FROM  #InOutTemp A Inner Join PD_AllotDetail_His BD On A.DID=BD.DID Inner Join PD_AllotBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 30902 '
	END
	IF EXISTS (select 1 from #BillType where billtype= 302)
	BEGIN
		IF @BillFlag = 3 or @BillFlag = 0	
			SELECT @sqlOut+='
			UNION ALL 
				SELECT  A.*, ' + @AdjPriceInStrO +' 
				FROM  #InOutTemp A Inner Join PD_AdjPriceDetail_His BD On A.DID=BD.DID Inner Join PD_AdjPriceBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 30201 '
		IF @BillFlag = 4 or @BillFlag = 0	
			SELECT @sqlOut +='
			UNION ALL 
				SELECT  A.*, ' + @AdjPriceOutStrO+' 
				FROM #InOutTemp A Inner Join PD_AdjPriceDetail_His BD On A.DID=BD.DID Inner Join PD_AdjPriceBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 30202'
	END
	IF EXISTS (select 1 from #BillType where billtype= 310)
	BEGIN
		IF @BillFlag = 5 or @BillFlag = 0	
			SELECT @sqlOut+='
			UNION ALL 
				SELECT  A.*, ' + @AssemblyInStrO +' 
				FROM  #InOutTemp A Inner Join PD_AssemblyDetail_His BD On A.DID=BD.DID Inner Join PD_AssemblyBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 31001 And BD.DetailType = 1 '
		IF @BillFlag = 6 or @BillFlag = 0	
			SELECT @sqlOut +='
			UNION ALL 
				SELECT  A.*, ' + @AssemblyOutStrO+' 
				FROM  #InOutTemp A Inner Join PD_AssemblyDetail_His BD On A.DID=BD.DID Inner Join PD_AssemblyBill_His I On I.BillNo=bd.BillNo '
				+ ' where A.BillTypeID = 31002 And BD.DetailType = 2 '
	END
END
DROP TABLE #BillType	

IF (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
BEGIN
	Set @OrderColumn += ',BT.BTypeCode,BT.BTypeName '
	Set @OrderTable +=' LEFT JOIN BD_Btype BT ON bill.BTypeID = BT.BTypeID '
END 
IF (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
BEGIN
	Set @OrderColumn += ',G.GoodsNo,G.GoodsName '
	if(@FullName <> '' or @UserCode <> '')
		Set @OrderTable +=' LEFT JOIN @PType G on bill.GoodsID = G.TypeID '
	Else
		Set @OrderTable +=' Inner JOIN BD_GOODS G on bill.GoodsID = G.GoodsID '
END 
SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+STUFF(@sql,1,13,'')+'
),
 PagingData AS
 ('
	+@PageDataStr+@OrderColumn+@RedStr + @SeriesColEnd +' 
		from Bill bill '+@OrderTable +
' )'

---排序字段
IF @OrderType1 <> ''
BEGIN
	IF @OrderSeq1 = 1 SET @OrderName = @OrderType1+' ASC' ELSE SET @OrderName = @OrderType1 +' DESC'
END
IF @OrderType2 <> ''
BEGIN
	IF @OrderName <> '' SET @OrderName +=', '
	IF @OrderSeq2 = 1 SET @OrderName += @OrderType2+' ASC' ELSE SET @OrderName += @OrderType2 +' DESC'
END	

 set @sql +=',DATA AS (
  SELECT *   
		FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' 
				FROM PagingData) A
			   CROSS JOIN
			   (
			   select ROW_NUMBER() OVER( ORDER BY '+@OrderName +') AS ROWID,*
						FROM PagingData 
				) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	select * into #InOutTemp from DATA
	
	select data.*,WhsNO,WhsName,DeptCode,DeptName,E.ElyCode,E.ElyName as ElyName,EC.ElyName as CreatorName,EP.ElyName as PostName,Gpc.Unit,BSGpc.Unit as BSUnit, Gpc.BarCode, G.Model, G.Spec, G.Brand, G.GoodsAbbName
		,GP1.Value as Ppt1Name,GP2.Value as Ppt2Name '
	if Not (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
	    set @sql += ' ,BTypeCode,BTypeName  '
	    
	if Not (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
	    set @sql += ' ,GoodsNo,GoodsName  '  
		set @sql += ' from ( '+STUFF(@sqlOut,1,12,'')+' ) data
		Inner Join BD_Whs W On Data.WhsID = W.WhsID
		Left JOIN BD_Dept D ON Data.DeptID = D.DeptID  
		LEFT JOIN BD_Employee E ON Data.ElyID = E.ElyID 
		LEFT JOIN BD_Employee EC ON Data.Creator = EC.ElyID 
		LEFT JOIN BD_Employee EP ON Data.PosElyID = EP.ElyID 
		Inner Join BD_Goods_Price Gpc On Data.UnitID = Gpc.UnitID and Data.GoodsID = Gpc.GoodsID 
		Inner Join BD_Goods_Price BSGpc On Data.BsUnitID = BSGpc.UnitID and Data.GoodsID = BSGpc.GoodsID 
		Left Join BD_Goods_Ppt1 GP1 ON Data.Ppt1ID = GP1.Ppt1ID 
		Left Join BD_Goods_Ppt2 GP2 ON Data.Ppt2ID = GP2.Ppt2ID 
		'
if Not (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
	IF @BtypeLimit = 1
		set @sql += ' Left JOIN (select B.BTypeID,BTypeCode,BTypeName from BD_Btype b Inner join @LimitBTYPE bl on b.BTypeID = bl.BTypeID
								union all
					  select b.BTypeID,''***'' as BtypeCode,''***'' as BtypeName from BD_Btype b where not exists( select 1 from @LimitBTYPE where b.BTypeID = BTypeID)
							) B ON Data.BtypeID = B.BtypeID  '
	Else IF @BtypeLimit = 2
		set @sql += ' Left JOIN BD_Btype B ON Data.BtypeID = B.BtypeID  '
	Else
		Set @Sql += ' Left JOIN (select BtypeID,''***'' as BtypeCode,''***'' as BtypeName from BD_Btype ) B ON Data.BtypeID = B.BtypeID  '
--if Not (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
	set @sql += ' Inner JOIN BD_Goods G ON Data.GoodsID = G.GoodsID  '
set @sql += 'ORDER BY ROWID'
Select @sql += ' drop table #InOutTemp '
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END
DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
--Set @EndDate = CASE WHEN @DateType=0 THEN @EndDate ELSE DATEADD(day,1,@EndDate) END	
IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

			
Exec sp_executesql @Sql,N'@PageNo Int,@PageSize Int,@BeginDate Date,@EndDate Date,@OperatorID Int,@ClassID1 Int,@WhsTypeID Int,
			@ClassID2 Int,@GoodsTypeID Int,@BTypeID VarChar(MAX),@DeptID VarChar(MAX)
			,@ElyID VarChar(MAX),@CreatorID varchar(MAx),@WhsID VarChar(MAX),@BillCode VarChar(MAX),@FullName VarChar(100),@UserCode VarChar(50)
			,@Summary VarChar(256),@Description VarChar(100),@Remark VarChar(256),@FinanceID VarChar(Max),@LogistBillNo VarChar(100),@InWhsID VarChar(100),@OutWhsID VarChar(100), @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100),
			@ShowSerial INT '
			,@PageNo,@PageSize,@BeginDate,@EndDate,@OperatorID,@ClassID1,@ClassID1,@ClassID2,@ClassID2,
			@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@BillCode,@FullName,
			@UserCode,@Summary,@Description,@Remark,@FinanceID,@LogistBillNo,@InWhsID,@OutWhsID, @Model, @AbbName, @Brand, @Spec, @BarCode ,
			@ShowSerial



GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：出入库汇总统计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryInOutStock]
(
	@PageNo INT=0,
	@PageSize INT=0,
	--@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(max)='',
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@InWhsID VARCHAR(max)='',
	@OutWhsID VARCHAR(max)='',
	@PtypeID VARCHAR(max)='',
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Summary VARCHAR(256)='',
	@SummaryType Int=0,
	@Description VARCHAR(100)='',
	@DescriptionType Int=0,
	@Remark VARCHAR(100)='',
	@RemarkType VARCHAR(100)=0,
	@CollectType1 INT=1,  --汇总条件 1单据类型，2仓库分类
	@Layer1 INT=6,  --汇总层级 0-4（层级），5按仓库汇总
	@CollectType2 INT=1,  --汇总条件 1商品分类
	@Layer2 INT=6,  --汇总层级 0-4（层级），5按商品汇总
	@OrderType1 Varchar(100)='BillName',	--排序条件，1=单据类型,2=仓库分类,3=商品分类,4=入库数量,5=出库数量,6=成本单价,7=入库金额,8=出库金额		
	@OrderSeq1 Int=1,  --排序类型 1=升序，2=降序
	@OrderType2 Varchar(100)='GoodsNo',	--排序条件，1=单据类型,2=仓库分类,3=商品分类,4=入库数量,5=出库数量,6=成本单价,7=入库金额,8=出库金额								
	@OrderSeq2 Int=1,  --排序类型 1=升序，2=降序
	@OperatorID INT,
	@isHistory INT=0				--是否包含历史数据
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;

DECLARE @sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlGoods nvarchar(max)=' WHERE 1 = 1 ',@SqlWhs varchar(max)=''
		,@SqlWhsOut varchar(max)='',@SqlWhsin varchar(max)='',@SqlOrder NVARCHAR(MAX) = '',@SqlGroup Nvarchar(MAX) = ''
		,@PathLen1 INT, @PathLen2 INT,@SummaryStr varchar(max)='',@DescriptionStr varchar(max)='',@RemarkStr varchar(max)='',@OrderName varchar(200)='',
		 @LimitSql NVARCHAR(MAX) = '',@LimitSqlIN nvarchar(max)='',@LimitSqlOut nvarchar(max)='',@OrderStr varchar(500)='',@sqlSelStr varchar(200)=''
		 ,@sqlStt varchar(100)='',@KtypeLimit INT=0,@InspectTagStr varchar(100)=''
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSql += ' And exists( Select 1 from  @LimitKType LW where I.WhsID=LW.TypeID ) ' 
	Set @LimitSqlIN += ' And exists( Select 1 from  @LimitKType LW where  LW.TypeID =i.InWhsID ) ' 	
	Set @LimitSqlOut += ' And exists( Select 1 from  @LimitKType LW where LW.TypeID =i.OutWhsID ) ' 	
End		
if @Summary <> ''
Begin 
	if @SummaryType = 0
		Select @SummaryStr = ' And Summary like''%'+ @Summary + '%''' 
	else 
		Select @SummaryStr = ' And Summary = ''' + @Summary + ''''
End
if @Description <> ''
Begin
	if @DescriptionType = 0
		Select @DescriptionStr = ' And Description like''%'+ @Description + '%''' 
	else 
		Select @DescriptionStr = ' And Description = ''' + @Description + ''''
End
if @Remark <> ''
Begin
	if @RemarkType = 0
		Select @RemarkStr = ' And Remark like''%'+ @Remark + '%''' 
	else 
		Select @RemarkStr = ' And Remark = ''' + @Remark + ''''
End
if exists(select 1 from SS_SysCfg where CfgName='AllotWithInspect' and CfgValue = 1) --判断是否启用调拨验证
	select @InspectTagStr = ' AND I.InspectTag = 1 '
if object_id('tempdb..#BillType','U') is not null drop table #BillType
CREATE TABLE #BillType(billtype int)
IF @BillTypeID<>''		
	INSERT INTO #BillType SELECT typeid FROM  dbo.UF_OT_Split_Int(@BillTypeID,',')
ELSE
	INSERT INTO #BillType SELECT BillTypeID  FROM PD_BillType where BillTypeID in (101,102,201,202,301,302,303,304,305,306,309,310,600)
IF NOT EXISTS(SELECT TOP 1 1 FROM #BillType WHERE billtype=0)
BEGIN
	IF @BTypeID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,303,304,600) 
END 
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' And exists( Select 1 from @BType B where I.BTypeID=B.TypeID ) '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' And exists( Select 1 from @DType D where I.DeptID=D.TypeID ) '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' And exists( Select 1 from @EType E where I.ElyID=E.TypeID ) ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' And exists( Select 1 from @CreateEType E where I.Creator=E.TypeID ) ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	--SET @SqlTable+=' And exists( Select 1 from  @KType W where I.WhsID=W.TypeID ) ' 
	Set @SqlWhs += ' And exists( Select 1 from  @KType W where I.WhsID=W.TypeID ) ' 
	Set @SqlWhsOut += ' And exists( Select 1 from  @KType W where I.OutWhsID = W.TypeID or I.InWhsID=W.TypeID) ' 
	--Set @SqlWhsIn += ' And exists( Select 1 from  @KType W where I.InWhsID=W.TypeID) ' 
END	
IF @InWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @InKType As Table(TypeID INT) insert into @InKType Select typeid from dbo.UF_OT_Split_Int(@InWhsID,'','') '
	SET @SqlWhsIn+='  And exists( Select 1 from  @InKType Wi where I.InWhsID=Wi.TypeID ) ' 
END	
IF @OutWhsID<>''
BEGIN 
	SET @SqlCreateTable+=' DECLARE @OutKType As Table(TypeID INT) insert into @OutKType Select typeid from dbo.UF_OT_Split_Int(@OutWhsID,'','') '
	SET @SqlWhsOut+='  And exists( Select 1 from   @OutKType Wo  where I.OutWhsID=Wo.TypeID ) ' 
END	

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)='', @GoodsInfoSql NVARCHAR(4000)='', @GoodsInfoCols NVARCHAR(2000) = ''
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   BEGIN
	   SET @SqlCreateTable+=' DECLARE @GoodsParam As Table(TypeID INT) insert into @GoodsParam Select goods.GoodsID FROM dbo.BD_Goods goods WHERE 1 = 1 ' + @ClauseParam
	   SET @SqlGoods+=' AND exists( Select 1 from @GoodsParam GP where G.GoodsID=GP.TypeID) '
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
	   SET @SqlCreateTable+=' DECLARE @BarCodeParam As Table(TypeID INT) insert into @BarCodeParam Select pri.GoodsID FROM dbo.BD_Goods_Price pri WHERE 1 = 1 '	
	   IF @BarCodeMatch = 0
		   SET @SqlCreateTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlCreateTable += N' AND pri.BarCode = @BarCode '    
	   SET @SqlGoods+=' AND exists( Select 1 from @BarCodeParam BCP where G.GoodsID=BCP.TypeID) '
   END    
/*end*/

IF @PtypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @PType As Table(TypeID INT) insert into @PType Select typeid from dbo.UF_OT_Split_Int(@PTypeID,'','') '
	--SET @SqlGoods+=' INNER JOIN @PType P ON BD.GoodsID=P.TypeID ' 
	SET @SqlGoods+=' AND exists( Select 1 from   @PType P  where G.GoodsID=P.TypeID) '
END	
--if @CollectType1 = 2 and @Layer1 <> 6
	--Set @SqlCreateTable += 'DECLARE @TVP_WhsType AS [TVP_Type]  
	--	INSERT INTO @TVP_WhsType([TypeID],[ChildTypeID]) 
	--	SELECT pwt.WhsTypeID,wt.WhsTypeID 
	--	FROM BD_Whs_Type wt 
	--	 INNER JOIN BD_Whs_Type pwt ON pwt.[Path] = 
	--	(CASE WHEN LEN(wt.[Path]) > @Layer1 * 5 
	--		  THEN SUBSTRING(wt.[Path], 1, @Layer1 * 5)
	--		  ELSE wt.[Path] END) 
	--	WHERE wt.SonNum = 0 '
	
if @Layer2 <> 6
	--Set @SqlCreateTable+='DECLARE @TVP_GoodsType AS [TVP_Type]  
	--	INSERT INTO @TVP_GoodsType([TypeID],[ChildTypeID]) 
	--	SELECT pgt.GoodsTypeID, gt.GoodsTypeID 
	--	FROM BD_Goods_Type gt 
	--	INNER JOIN BD_Goods_Type pgt ON pgt.[Path] = 
	--	(CASE WHEN LEN(gt.[Path]) > @Layer2 * 5 
	--		  THEN SUBSTRING(gt.[Path], 1, @Layer2 * 5) 
	--		  ELSE gt.[Path] END) 
	--	WHERE gt.SonNum = 0 '
	Set @SqlCreateTable +='';
else
	BEGIN
		Set @sqlStt = ',Stt'
		SET @GoodsInfoCols += ' , g.Spec, g.Model, g.GoodsAbbName, g.Brand, b.BarCode '
		SET @GoodsInfoSql += ' INNER JOIN dbo.BD_Goods g ON g.GoodsID = tmp.GoodsID 
							   INNER JOIN dbo.BD_Goods_Price b ON b.GoodsID = tmp.GoodsID AND b.UnitID = 1 '
	END
select @sql +='
	UNION ALL 
	SELECT  ' + Case When @CollectType1 = 1 then  Cast(BillTypeID AS varchar)+' AS BillTypeID,'''+billname+''' AS BillName,'
					 When @CollectType1 = 2 Then CASE WHEN billtypeid IN(101,102,201,202,303,304,305,306,600) THEN 'BD.WhsID' WHEN billtypeid in (301,309) THEN 'BD.OutWhsID'  ELSE '0' END+' as WhsID,'
					 Else '' End
		+' BD.GoodsID,'
		+CASE WHEN billtypeid IN(101,202,303,306) THEN ' Sum(BD.BSQty) ' else '0' end +' as InStockQty, '
		+CASE WHEN billtypeid IN(102,201,304,305,600) THEN ' Sum(BD.BSQty) ' else '0' end +' as OutStockQty, '
		+CASE WHEN billtypeid IN(101,202,303,306) THEN ' Sum(BD.GoodsCostTotal) ' else ' 0 ' end +' as InTotal, '
		+CASE WHEN billtypeid IN(102,201,304,305,600) THEN ' Sum(BD.GoodsCostTotal) ' else ' 0 ' end +' as OutTotal'	
	+' FROM  ' + BillDetail + ' BD '
	+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  '+BillTable+' I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
	+ @SqlTable	+ @LimitSql + @SqlWhs
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END		
	+')'
	+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
	+' group by BD.GoodsID '
	+CASE WHEN billtypeid IN(101,102,201,202,303,304,305,306,600) THEN ',BD.WhsID' WHEN billtypeid in (301,309) THEN ',BD.OutWhsID,BD.InWhsID'  ELSE '' END
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0
WHERE CanPost=1 and billtype not in (301,302,309,310)
if exists (select 1 from #BillType where billtype in (301,309))
begin
if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0) and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
	Select @Sql+='
	UNION ALL
		SELECT ' + Case When @CollectType1 = 1 then ' BillTypeID AS BillTypeID, Case When BillTypeID = 301 then '''+'同价调拨单(出库)'+''' Else '''+'变价调拨单(出库)'+''' End AS BillName,'
						When @CollectType1 = 2 Then 'BD.OutWhsID as WhsID,'
						Else '' End
		+'BD.GoodsID,0 as InStockQty, Sum(BD.BSQty)  as OutStockQty,0 as InTotal,  Sum(BD.GoodsCostTotal)  as OutTotal
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  ' 
		+ @SqlTable	+ @LimitSqlOut + @SqlWhsOut + @SqlWhsIn
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		+' And BillTypeID = ' + Cast(billtype as varchar(10))
		+' group by BD.GoodsID,BD.OutWhsID,bd.InWhsID,I.BillTypeID ' from #BillType where billtype in (301,309)
if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0) and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
			Select @Sql+=' 
UNION ALL 
		SELECT ' +Case When @CollectType1 = 1 Then '  BillTypeID AS BillTypeID, Case When BillTypeID = 301 then '''+'同价调拨单(入库)'+''' Else '''+'变价调拨单(入库)'+''' End AS BillName,'
					   When @CollectType1 = 2 Then ' BD.InWhsID as WhsID,' 
					   Else '' End
		+' BD.GoodsID,Sum(BD.BSQty) as InStockQty, 0  as OutStockQty, Case When BillTypeID = 301 then Sum(BD.GoodsCostTotal) Else Sum(BD.AllotTotal) End as InTotal, 0 as OutTotal
		FROM  PD_AllotDetail BD Inner Join PD_AllotBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  ' 
		+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut + @InspectTagStr
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		+' And BillTypeID = ' + Cast(billtype as varchar(10))
	   +' group by BD.GoodsID,BD.OutWhsID,bd.InWhsID,I.BillTypeID ' from #BillType where billtype in (301,309)
End
if exists (select 1 from #BillType where billtype = 310)
begin
if (charindex('310',@BillTypeID)>0  and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
	Select @Sql+='
	UNION ALL
		SELECT ' + Case When @CollectType1 = 1 then ' 310 AS BillTypeID, '''+'生产拆装(出库)'+''' AS BillName,'
						When @CollectType1 = 2 Then ' BD.WhsID as WhsID,'
						Else '' End
		+'BD.GoodsID,0 as InStockQty, Sum(BD.BSQty)  as OutStockQty,0 as InTotal,  Sum(BD.GoodsCostTotal) as OutTotal
		FROM  PD_AssemblyDetail BD  Inner Join PD_AssemblyBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=2  ' 
		+ @SqlTable	+ @LimitSqlOut + @SqlWhsOut + @SqlWhsIn
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		+' group by BD.GoodsID,BD.WhsID ' from #BillType where billtype = 310
if (charindex('310',@BillTypeID)>0  and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
			Select @Sql+=' 
UNION ALL 
		SELECT ' +Case When @CollectType1 = 1 Then ' 310 AS BillTypeID,'''+'生产拆装(入库)'+''' AS BillName,'
					   When @CollectType1 = 2 Then ' BD.WhsID as WhsID,' 
					   Else '' End
		+' BD.GoodsID,Sum(BD.BSQty) as InStockQty, 0  as OutStockQty, Sum(BD.GoodsCostTotal) as InTotal, 0 as OutTotal
		FROM  PD_AssemblyDetail BD Inner Join PD_AssemblyBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=1 ' 
		+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
	   +' group by BD.GoodsID,BD.WhsID ' from #BillType where billtype = 310
End
if exists (select 1 from #BillType where billtype= 302)
begin
	Select @Sql+='
	UNION ALL 
		SELECT '+Case When @CollectType1 = 1 Then ' 302 AS BillTypeID,'''+'调价单(出库)'+''' AS BillName,'
					  When @CollectType1 = 2 Then ' BD.WhsID as WhsID,'
					  Else '' End
		+' BD.GoodsID,0 as InStockQty, Sum(BD.BSQty)  as OutStockQty,0 as InTotal,  Sum(BD.GoodsCostTotal)  as OutTotal
		FROM  PD_AdjPriceDetail BD  '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
		+ @SqlTable	+ @LimitSql + @SqlWhs
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+')'
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		+' group by BD.GoodsID,BD.WhsID '
		+' UNION ALL 
		SELECT ' + Case When @CollectType1 = 1 Then ' 302 AS BillTypeID,'''+'调价单(入库)'+''' AS BillName,'
						When @CollectType1 = 2 Then ' BD.WhsID as WhsID,'
						Else '' End
		+ ' BD.GoodsID,Sum(BD.BSQty) as InStockQty, 0  as OutStockQty, Sum(BD.AdjTotal) as InTotal, 0 as OutTotal
		FROM  PD_AdjPriceDetail BD  '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
		+ @SqlTable	+ @LimitSql + @SqlWhs
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+')'
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		+' group by BD.GoodsID,BD.WhsID '
End

IF @isHistory=1
Begin
	select @sql +='
		UNION ALL 
		SELECT  ' + Case When @CollectType1 = 1 then  Cast(BillTypeID AS varchar)+' AS BillTypeID,'''+billname+''' AS BillName,'
						 When @CollectType1 = 2 Then CASE WHEN billtypeid IN(101,102,201,202,303,304,305,306,600) THEN 'BD.WhsID' WHEN billtypeid in (301,309) THEN 'BD.OutWhsID'  ELSE '0' END+' as WhsID,'
						 Else '' End
		+' BD.GoodsID,'
			+CASE WHEN billtypeid IN(101,202,303,306) THEN ' Sum(BD.BSQty) ' else '0' end +' as InStockQty, '
			+CASE WHEN billtypeid IN(102,201,304,305,600) THEN ' Sum(BD.BSQty) ' else '0' end +' as OutStockQty, '
			+CASE WHEN billtypeid IN(101,202,303,306) THEN ' Sum(BD.GoodsCostTotal) ' else ' 0 ' end +' as InTotal, '
			+CASE WHEN billtypeid IN(102,201,304,305,600) THEN ' Sum(BD.GoodsCostTotal) ' else ' 0 ' end +' as OutTotal'	
		+' FROM  ' + BillDetail + '_His BD '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  '+BillTable+'_His I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
		+ @SqlTable	+ @LimitSql + @SqlWhs	
			+CASE WHEN BillTable+'_His' IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END		
		+')'
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		+' group by BD.GoodsID '
		+CASE WHEN billtypeid IN(101,102,201,202,303,304,305,306,600) THEN ',BD.WhsID' WHEN billtypeid in (301,309) THEN ',BD.OutWhsID,BD.InWhsID'  ELSE '' END
	FROM PD_BillType b
	INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0
	WHERE CanPost=1 and billtype not in (301,302,309,310)
	if exists (select 1 from #BillType where billtype in (301,309))
	begin
		if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0) and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
		Select @Sql+='
		UNION ALL 
			SELECT ' + Case When @CollectType1 = 1 then ' BillTypeID AS BillTypeID, Case When BillTypeID = 301 then '''+'同价调拨单(出库)'+''' Else '''+'变价调拨单(出库)'+''' End AS BillName,'
						When @CollectType1 = 2 Then 'BD.OutWhsID as WhsID,'
						Else '' End
			+'BD.GoodsID,0 as InStockQty, Sum(BD.BSQty)  as OutStockQty,0 as InTotal,  Sum(BD.GoodsCostTotal)  as OutTotal
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  ' 
			+ @SqlTable	+ @LimitSqlOut + @SqlWhsIn + @SqlWhsOut
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
			+' And BillTypeID = ' + Cast(billtype as varchar(10))			
			+' group by BD.GoodsID,BD.OutWhsID,bd.InWhsID,I.BillTypeID ' from #BillType where billtype in (301,309)
		if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0)and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
		Select @Sql+=' 
		UNION ALL 
			SELECT  ' +Case When @CollectType1 = 1 Then ' BillTypeID AS BillTypeID, Case When BillTypeID = 301 then '''+'同价调拨单(入库)'+''' Else '''+'变价调拨单(入库)'+''' End AS BillName,'
					   When @CollectType1 = 2 Then ' BD.InWhsID as WhsID,' 
					   Else '' End
			+' BD.GoodsID,Sum(BD.BSQty) as InStockQty, 0  as OutStockQty, Case When BillTypeID = 301 then Sum(BD.GoodsCostTotal) Else Sum(BD.AllotTotal) End as InTotal, 0 as OutTotal
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill_His I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  ' 
			+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut + @InspectTagStr
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
			+' And BillTypeID = ' + Cast(billtype as varchar(10))			
		   +' group by BD.GoodsID,BD.OutWhsID,bd.InWhsID,I.BillTypeID ' from #BillType where billtype in (301,309)
	End
	if exists (select 1 from #BillType where billtype = 310)
	begin
	if (charindex('310',@BillTypeID)>0  and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
		Select @Sql+='
		UNION ALL
			SELECT ' + Case When @CollectType1 = 1 then ' 310 AS BillTypeID, '''+'生产拆装(出库)'+''' AS BillName,'
							When @CollectType1 = 2 Then ' BD.WhsID as WhsID,'
							Else '' End
			+'BD.GoodsID,0 as InStockQty, Sum(BD.BSQty)  as OutStockQty,0 as InTotal,  Sum(BD.GoodsCostTotal) as OutTotal
			FROM  PD_AssemblyDetail_His BD  Inner Join PD_AssemblyBill_His I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=2  ' 
			+ @SqlTable	+ @LimitSqlOut + @SqlWhsOut + @SqlWhsIn
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
			+' group by BD.GoodsID,BD.WhsID ' from #BillType where billtype = 310
	if (charindex('310',@BillTypeID)>0  and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
				Select @Sql+=' 
	UNION ALL 
			SELECT ' +Case When @CollectType1 = 1 Then ' 310 AS BillTypeID,'''+'生产拆装(入库)'+''' AS BillName,'
						   When @CollectType1 = 2 Then ' BD.WhsID as WhsID,' 
						   Else '' End
			+' BD.GoodsID,Sum(BD.BSQty) as InStockQty, 0  as OutStockQty, Sum(BD.GoodsCostTotal) as InTotal, 0 as OutTotal
			FROM  PD_AssemblyDetail_His BD Inner Join PD_AssemblyBill_His I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=1 ' 
			+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		   +' group by BD.GoodsID,BD.WhsID ' from #BillType where billtype = 310
	End
	if exists (select 1 from #BillType where billtype= 302)
	begin
		Select @Sql+='
		UNION ALL 
			SELECT  '+Case When @CollectType1 = 1 Then ' 302 AS BillTypeID,'''+'调价单(出库)'+''' AS BillName,'
					  When @CollectType1 = 2 Then ' BD.WhsID as WhsID,'
					  Else '' End
			+' BD.GoodsID,0 as InStockQty, Sum(BD.BSQty)  as OutStockQty,0 as InTotal,  Sum(BD.GoodsCostTotal)  as OutTotal
			FROM  PD_AdjPriceDetail_His BD  '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill_His I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
			+ @SqlTable	+ @LimitSql + @SqlWhs
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+')'
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
			+' group by BD.GoodsID,BD.WhsID '
			+' UNION ALL 
			SELECT  ' + Case When @CollectType1 = 1 Then ' 302 AS BillTypeID,'''+'调价单(入库)'+''' AS BillName,'
						When @CollectType1 = 2 Then ' BD.WhsID as WhsID,'
						Else '' End
			+ ' BD.GoodsID,Sum(BD.BSQty) as InStockQty, 0  as OutStockQty, Sum(BD.AdjTotal) as InTotal, 0 as OutTotal
			FROM  PD_AdjPriceDetail_His BD  '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill_His I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
			+ @SqlTable	+ @LimitSql + @SqlWhs
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+')'
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
			+' group by BD.GoodsID,BD.WhsID '
	End
End

drop table #BillType
if(@CollectType1 = 1)
Begin
	Select @OrderStr += ' BillTypeID,BillName,'
	Select @SqlGroup += ' BillTypeID,BillName,'
	SELECT @sqlSelStr += 'BillTypeID,BillName,'	
End
Else if(@CollectType1 = 2)
Begin
	if(@Layer1 <> 6 )
	BEGIN
		Select @OrderStr += ' Wt.WhsTypeID,Wt.TypeCode as WTypeCode,Wt.TypeName as WTypeName,'
		Select @SqlGroup += ' Wt.WhsTypeID,Wt.TypeCode,Wt.TypeName,'
		Select @sqlSelStr += ' WhsTypeID,WTypeCode,WTypeName,'
	END
	ELSE
	BEGIN
		Select @OrderStr += ' A.WhsID,WhsName,WhsNO,'
		Select @SqlGroup += ' A.WhsID,W.WhsName,W.WhsNO,'
		Select @sqlSelStr += ' WhsID,WhsName,WhsNO,'
	END
End
if(@Layer2 <> 6 )
BEGIN
	Select @OrderStr += ' Gt.GoodsTypeID,Gt.TypeCode as GTypeCode,Gt.TypeName as GTypeName,'
	Select @SqlGroup += ' Gt.GoodsTypeID,Gt.TypeCode,Gt.TypeName'
	Select @sqlSelStr += ' GoodsTypeID,GTypeCode,GTypeName,'
END
ELSE
BEGIN
	Select @OrderStr += ' A.GoodsID,GoodsName,GoodsNo,G.Stt,'
	Select @SqlGroup += ' A.GoodsID,G.GoodsName,G.GoodsNo,G.Stt'
	Select @sqlSelStr += ' GoodsID,GoodsName,GoodsNo,Stt,'
END

SELECT @sql=@SqlCreateTable+'
;WITH Bill AS 
('	+STUFF(@sql,1,12,'')+'
)
,PagingData as
('		
	Select @sql += ' select '+ @OrderStr+ ' Sum(InStockQty) as InStockQty,Sum(OutStockQty) as OutStockQty,Sum(InTotal) as InTotal,Sum(OutTotal) as OutTotal 
	, case (Sum(OutStockQty) + Sum(InStockQty)) when 0 then 0 else Convert(NUMERIC(17,8),(Sum(InTotal) + Sum(OutTotal))/(Sum(OutStockQty) + Sum(InStockQty))) end as CostPrice
	from Bill A Inner Join BD_Goods G on A.GoodsID = G.GoodsID '
	if(@CollectType1 = 2)
	Begin
		if(@Layer1 <> 6 )
		Begin
		Select @sql += ' Inner Join BD_Whs W on A.WhsID = w.WhsID 
						  --Inner Join  @TVP_WhsType Wt1 on W.WhsTypeID = Wt1.ChildTypeID
						  --Inner Join BD_Whs_Type Wt On Wt1.TypeID=Wt.WhsTypeID
						  Inner Join dbo.UF_BD_BaseSummary(''KTYPE'', @Layer1) BW ON W.WhsTypeID = BW.ParID 
						  Inner Join BD_Whs_Type Wt On Wt.WhsTypeID = BW.BaseID
						 '
		End
		ELSE
			Select @Sql += ' Inner Join BD_Whs W on A.WhsID = w.WhsID '
	End
	if(@Layer2 <> 6 )
	BEGIN
		--Select @Sql += ' Inner Join  @TVP_GoodsType Gt1 on gt1.ChildTypeID = G.GoodsTypeID Inner Join BD_Goods_Type Gt on gt.GoodsTypeID = gt1.TypeID'
		Select @Sql += ' Inner Join dbo.UF_BD_BaseSummary(''PTYPE'', @Layer2) BS ON G.GoodsTypeID = BS.ParID 
							Inner Join BD_Goods_Type Gt On gt.GoodsTypeID = bs.BaseID  '
	END
	Select @Sql += @SqlGoods +' Group By '+ @SqlGroup+'
) '
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END
---排序字段
IF @OrderType1 <> ''
BEGIN
	IF @OrderSeq1 = 1 SET @OrderName = @OrderType1+' ASC' ELSE SET @OrderName = @OrderType1 +' DESC'
END
IF @OrderType2 <> ''
BEGIN
	IF @OrderName <> '' SET @OrderName +=', '
	IF @OrderSeq2 = 1 SET @OrderName += @OrderType2+' ASC' ELSE SET @OrderName += @OrderType2 +' DESC'
END	
Select @Sql += '
	,DATA AS (
SELECT 
  ROW_NUMBER() OVER( ORDER BY   '+@OrderName+' ) AS ROWID, 
  count(*) over() as '''+'rowcount'+''', *	 
FROM PagingData

) 
SELECT * INTO #InOutQueryTempTb FROM (select * from data
WHERE ROWID>(@PageNo-1)*@PageSize aND ROWID<=@PageNo*@PageSize)S;
SELECT tmp.* ' + @GoodsInfoCols + ' FROM #InOutQueryTempTb tmp ' + @GoodsInfoSql + ';
DROP TABLE #InOutQueryTempTb; '
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 --PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
print @Sql
if(@KtypeLimit = 0) SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--Set @EndDate = CASE WHEN @DateType=0 THEN @EndDate ELSE DATEADD(day,1,@EndDate) END						
exec sp_executesql @sql,N'@PageNo Int,@PageSize Int,@BeginDate Date,@EndDate Date,@OperatorID Int,@BTypeID VarChar(MAX),@DeptID VarChar(MAX),@ElyID VarChar(MAX),@CreatorID varchar(MAx)
						,@WhsID VarChar(MAX),@inWhsID VarChar(MAX),@OutWhsID VarChar(MAX),@PTypeID VarChar(MAX),@Layer1 Int,@Layer2 Int, @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)'
						,@PageNo,@PageSize,@BeginDate,@EndDate,@OperatorID,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@inWhsID,@OutWhsID,@PTypeID,@Layer1,@Layer2, @Model, @AbbName, @Brand, @Spec, @BarCode


GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-7-14
	描述：出入库汇总统计合计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryInOutStockSum]
(
	--@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(max)='',
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@InWhsID VARCHAR(max)='',
	@OutWhsID VARCHAR(max)='',
	@PtypeID VARCHAR(max)='',
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Summary VARCHAR(256)='',
	@SummaryType Int=1,
	@Description VARCHAR(100)='',
	@DescriptionType Int=1,
	@Remark VARCHAR(100)='',
	@RemarkType VARCHAR(100)=1,
	@OperatorID INT,
	@isHistory INT=0				--是否包含历史数据
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;

DECLARE @sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlGoods nvarchar(max)='',@SqlOrder NVARCHAR(MAX) = '',@SqlGroup Nvarchar(MAX) = ''
		,@PathLen1 INT, @PathLen2 INT,@SqlWhs Nvarchar(Max)='',@SummaryStr varchar(max)='',@DescriptionStr varchar(max)=''
		,@RemarkStr varchar(max)='', @LimitSql NVARCHAR(MAX) = '',@LimitSqlIN nvarchar(max)='',@LimitSqlOut nvarchar(max)=''
		,@SqlWhsOut nvarchar(max)='',@SqlWhsin varchar(max)='',@KtypeLimit INT=0,@InspectTagStr varchar(100)=''
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSql += ' And exists( Select 1 from  @LimitKType LW where I.WhsID=LW.TypeID ) ' 
	Set @LimitSqlIN += ' And exists( Select 1 from  @LimitKType LW where  LW.TypeID =i.InWhsID ) ' 	
	Set @LimitSqlOut += ' And exists( Select 1 from  @LimitKType LW where LW.TypeID =i.OutWhsID ) ' 	
End		
if @Summary <> ''
Begin 
	if @SummaryType = 0
		Select @SummaryStr = ' And Summary like''%'+ @Summary + '%''' 
	else 
		Select @SummaryStr = ' And Summary = ''' + @Summary + ''''
End
if @Description <> ''
Begin
	if @DescriptionType = 0
		Select @DescriptionStr = ' And Description like''%'+ @Description + '%''' 
	else 
		Select @DescriptionStr = ' And Description = ''' + @Description + ''''
End
if @Remark <> ''
Begin
	if @RemarkType = 0
		Select @RemarkStr = ' And Remark like''%'+ @Remark + '%''' 
	else 
		Select @RemarkStr = ' And Remark = ''' + @Remark + ''''
End
if exists(select 1 from SS_SysCfg where CfgName='AllotWithInspect' and CfgValue = 1) --判断是否启用调拨验证
	select @InspectTagStr = ' AND I.InspectTag = 1 '
if object_id('tempdb..#BillType','U') is not null drop table #BillType
CREATE TABLE #BillType(billtype int)
IF @BillTypeID<>''		
	INSERT INTO #BillType SELECT typeid FROM  dbo.UF_OT_Split_Int(@BillTypeID,',')
ELSE
	INSERT INTO #BillType SELECT BillTypeID  FROM PD_BillType where BillTypeID in (101,102,201,202,301,302,303,304,305,306,309,310,600)
IF NOT EXISTS(SELECT TOP 1 1 FROM #BillType WHERE billtype=0)
BEGIN
	IF @BTypeID<>''
		DELETE FROM #BillType WHERE billtype NOT IN(101,102,201,202,303,304,600) 
END 
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' And exists( Select 1 from @BType B where I.BTypeID=B.TypeID ) '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' And exists( Select 1 from @DType D where I.DeptID=D.TypeID ) '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' And exists( Select 1 from @EType E where I.ElyID=E.TypeID ) ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' And exists( Select 1 from @CreateEType E where I.Creator=E.TypeID ) ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	--SET @SqlTable+=' And exists( Select 1 from  @KType W where I.WhsID=W.TypeID ) ' 
	Set @SqlWhs += ' And exists( Select 1 from  @KType W where I.WhsID=W.TypeID ) ' 
	Set @SqlWhsOut += ' And exists( Select 1 from  @KType W where I.OutWhsID = W.TypeID or I.InWhsID=W.TypeID) ' 
	--Set @SqlWhsIn += ' And exists( Select 1 from  @KType W where I.InWhsID=W.TypeID) ' 
END	
IF @InWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @InKType As Table(TypeID INT) insert into @InKType Select typeid from dbo.UF_OT_Split_Int(@InWhsID,'','') '
	SET @SqlTable+='  And exists( Select 1 from  @InKType Wi where I.InWhsID=Wi.TypeID ) ' 
END	
IF @OutWhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @OutKType As Table(TypeID INT) insert into @OutKType Select typeid from dbo.UF_OT_Split_Int(@OutWhsID,'','') '
	SET @SqlTable+='  And exists( Select 1 from   @OutKType Wo  where I.OutWhsID=Wo.TypeID ) ' 
END	

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)=''
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   BEGIN
	   SET @SqlCreateTable+=' DECLARE @GoodsParam As Table(TypeID INT) insert into @GoodsParam Select goods.GoodsID FROM dbo.BD_Goods goods WHERE 1 = 1 ' + @ClauseParam
	   SET @SqlGoods+=' AND exists( Select 1 from @GoodsParam GP where BD.GoodsID=GP.TypeID) '
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
	   SET @SqlCreateTable+=' DECLARE @BarCodeParam As Table(TypeID INT) insert into @BarCodeParam Select pri.GoodsID FROM dbo.BD_Goods_Price pri WHERE 1 = 1 '	
	   IF @BarCodeMatch = 0
		   SET @SqlCreateTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlCreateTable += N' AND pri.BarCode = @BarCode '    
	   SET @SqlGoods+=' AND exists( Select 1 from @BarCodeParam BCP where BD.GoodsID=BCP.TypeID) '
   END    
/*end*/
IF @PtypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @PType As Table(TypeID INT) insert into @PType Select typeid from dbo.UF_OT_Split_Int(@PTypeID,'','') '
	--SET @SqlGoods+=' INNER JOIN @PType P ON BD.GoodsID=P.TypeID ' 
	SET @SqlGoods+=' And exists( Select 1 from   @PType P  where BD.GoodsID=P.TypeID) '
END	

SELECT @sql+='
UNION ALL 
SELECT  '
		+CASE WHEN billtypeid IN(101,202,301,302,303,306,309) THEN ' BD.BSQty ' else '0' end +' as InStockQty, '
		+CASE WHEN billtypeid IN(102,201,301,302,304,305,309,600) THEN ' BD.BSQty ' else '0' end +' as OutStockQty, '
		+CASE WHEN billtypeid IN(101,202,301,302,303,306,309) THEN ' BD.GoodsCostTotal ' else ' 0 ' end +' as InTotal, '
		+CASE WHEN billtypeid IN(102,201,301,302,304,305,309,600) THEN ' BD.GoodsCostTotal ' else ' 0 ' end +' as OutTotal'
		+' FROM  ' + BillDetail + ' BD '
	+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  '+BillTable+' I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' + @SqlTable
	+ @LimitSql
		+ @SqlWhs
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END		
	+')'
	+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
	+ @SqlGoods
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0
WHERE CanPost=1 and billtype not in (301,302,309,310)

if exists (select 1 from #BillType where billtype in (301,309))
begin
	if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0) and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
	Select @Sql+='
UNION ALL 
		SELECT  0 as InStockQty, BD.BSQty  as OutStockQty,0 as InTotal,  BD.GoodsCostTotal  as OutTotal
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 ' 
		+ @SqlTable	+ @LimitSqlOut + @SqlWhsIn + @SqlWhsOut
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
		+' And BillTypeID = ' + Cast(billtype as varchar(10))  from #BillType where billtype in (301,309)	 		
	if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0) and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
	Select @Sql+='
UNION ALL 
		SELECT  BD.BSQty as InStockQty, 0  as OutStockQty, Case When BillTypeID = 301 then BD.GoodsCostTotal Else BD.AllotTotal End as InTotal, 0 as OutTotal
		FROM  PD_AllotDetail BD  Inner Join PD_AllotBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 ' 
		+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut+ @InspectTagStr
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
		+' And BillTypeID = ' + Cast(billtype as varchar(10))  from #BillType where billtype in (301,309)	 		
End
if exists (select 1 from #BillType where billtype = 310)
begin
	if (charindex('310',@BillTypeID)>0 and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
	Select @Sql+='
UNION ALL 
		SELECT  0 as InStockQty, BD.BSQty  as OutStockQty,0 as InTotal,  BD.GoodsCostTotal  as OutTotal
		FROM  PD_AssemblyDetail BD  Inner Join PD_AssemblyBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=2' 
		+ @SqlTable	+ @LimitSqlOut + @SqlWhsIn + @SqlWhsOut
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
		from #BillType where  billtype = 310	 		
	if (charindex('310',@BillTypeID)>0 and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
	Select @Sql+='
UNION ALL 
		SELECT  BD.BSQty as InStockQty, 0  as OutStockQty, BD.GoodsCostTotal as InTotal, 0 as OutTotal
		FROM  PD_AssemblyDetail BD  Inner Join PD_AssemblyBill I ON  I.BillNo=bd.BillNo '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=1 ' 
		+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
	   from #BillType where  billtype = 310	 		
End

if exists (select 1 from #BillType where billtype= 302)
begin
	Select @Sql+='
	UNION ALL 
		SELECT 0 as InStockQty, BD.BSQty  as OutStockQty,0 as InTotal,BD.GoodsCostTotal  as OutTotal
		FROM  PD_AdjPriceDetail BD  '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
		+ @SqlTable	+ @LimitSql + @SqlWhs
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+')'
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
		+' UNION ALL 
		SELECT BD.BSQty as InStockQty, 0  as OutStockQty, BD.AdjTotal as InTotal, 0 as OutTotal
		FROM  PD_AdjPriceDetail BD  '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
		+ @SqlTable	+ @LimitSql + @SqlWhs
		+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
		+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
		+')'
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
End

IF @isHistory=1
Begin
	SELECT @sql+='
	UNION ALL 
	SELECT  '
			+CASE WHEN billtypeid IN(101,202,301,302,303,306,309) THEN ' BD.BSQty ' else '0' end +' as InStockQty, '
			+CASE WHEN billtypeid IN(102,201,301,302,304,305,309,600) THEN ' BD.BSQty ' else '0' end +' as OutStockQty, '
			+CASE WHEN billtypeid IN(101,202,301,302,303,306,309) THEN ' BD.GoodsCostTotal ' else ' 0 ' end +' as InTotal, '
			+CASE WHEN billtypeid IN(102,201,301,302,304,305,309,600) THEN ' BD.GoodsCostTotal ' else ' 0 ' end +' as OutTotal'
			+' FROM  ' + BillDetail + '_His BD '
		+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  '+BillTable+'_His I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' + @SqlTable
		+ @LimitSql
			+ @SqlWhs
			+CASE WHEN BillTable+'_His' IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END		
		+')'
		+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END
		+ @SqlGoods
	FROM PD_BillType b
	INNER JOIN #BillType T ON b.billtypeid=T.billtype OR T.billtype=0
	WHERE CanPost=1 and billtype not in (301,302,309,310)

	if exists (select 1 from #BillType where billtype in (301,309))
	begin
	if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0) and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
	Select @Sql+='
	UNION ALL 
			SELECT  0 as InStockQty, BD.BSQty  as OutStockQty,0 as InTotal,  BD.GoodsCostTotal  as OutTotal
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 ' 
			+ @SqlTable	+ @LimitSqlOut + @SqlWhsIn + @SqlWhsOut
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
			+' And BillTypeID = ' + Cast(billtype as varchar(10))  from #BillType where billtype in (301,309)	 		
		if ((charindex('301',@BillTypeID)>0 or charindex('309',@BillTypeID)>0) and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
		Select @Sql+=' 
		UNION ALL 
			SELECT  BD.BSQty as InStockQty, 0  as OutStockQty, Case When BillTypeID = 301 then BD.GoodsCostTotal Else BD.AllotTotal End as InTotal, 0 as OutTotal
			FROM  PD_AllotDetail_His BD  Inner Join PD_AllotBill I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 ' 
			+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut+ @InspectTagStr
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
			+' And BillTypeID = ' + Cast(billtype as varchar(10))  from #BillType where billtype in (301,309)	 		
	End
	if exists (select 1 from #BillType where billtype = 310)
	begin
		if (charindex('310',@BillTypeID)>0  and @OutWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
		Select @Sql+='
	UNION ALL 
			SELECT  0 as InStockQty, BD.BSQty  as OutStockQty,0 as InTotal,  BD.GoodsCostTotal  as OutTotal
			FROM  PD_AssemblyDetail_His BD  Inner Join PD_AssemblyBill_His I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=2' 
			+ @SqlTable	+ @LimitSqlOut + @SqlWhsIn + @SqlWhsOut
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
			from #BillType where  billtype = 310	 		
		if (charindex('310',@BillTypeID)>0  and @InWhsID<>'') or (@OutWhsID='' and @InWhsID = '')
		Select @Sql+='
	UNION ALL 
			SELECT  BD.BSQty as InStockQty, 0  as OutStockQty, BD.GoodsCostTotal as InTotal, 0 as OutTotal
			FROM  PD_AssemblyDetail_His BD  Inner Join PD_AssemblyBill_His I ON  I.BillNo=bd.BillNo '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 And BD.DetailType=1 ' 
			+ @SqlTable	+ @LimitSqlIN + @SqlWhsIn + @SqlWhsOut
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
		   from #BillType where  billtype = 310	 		
	End
	if exists (select 1 from #BillType where billtype= 302)
	begin
		Select @Sql+='
		UNION ALL 
			SELECT 0 as InStockQty, BD.BSQty  as OutStockQty,0 as InTotal,BD.GoodsCostTotal  as OutTotal
			FROM  PD_AdjPriceDetail_His BD  '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill_His I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
			+ @SqlTable	+ @LimitSql + @SqlWhs
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+')'
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
			+' UNION ALL 
			SELECT BD.BSQty as InStockQty, 0  as OutStockQty, BD.AdjTotal as InTotal, 0 as OutTotal
			FROM  PD_AdjPriceDetail_His BD  '
			+'where BD.BillDate BETWEEN @BeginDate AND @EndDate and exists(select 1 from  PD_AdjPriceBill_His I where IsDraft=0 And Red = 0 and I.BillNo=bd.BillNo ' 
			+ @SqlTable	+ @LimitSql + @SqlWhs
			+CASE WHEN @Summary ='' THEN '' ELSE @SummaryStr  END 
			+CASE WHEN @Description ='' THEN '' ELSE @DescriptionStr END	
			+')'
			+CASE WHEN @Remark ='' THEN '' ELSE @RemarkStr END + @SqlGoods
	End
End

drop table #BillType

SELECT @sql=@SqlCreateTable+'
;WITH Bill AS 
('	+STUFF(@sql,1,12,'')+'
)
,page as
( 	select InStockQty,OutStockQty,InTotal,OutTotal from Bill 
),PagingData As
(
	SELECT Sum(InStockQty) as InStockQty,Sum(OutStockQty) as OutStockQty,Sum(InTotal) as InTotal,Sum(OutTotal) as OutTotal From page
)
select InStockQty,OutStockQty,InTotal,OutTotal from PagingData
'
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END
--DECLARE @curPos INT = 1,@count1 INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count1 += 1  
--	 END  
if(@KtypeLimit = 0) SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--Set @EndDate = CASE WHEN @DateType=0 THEN @EndDate ELSE DATEADD(day,1,@EndDate) END
EXEC SP_EXECUTESQL @Sql,N'@BeginDate VARCHAR(50),@EndDate VARCHAR(50),@BillTypeID VARCHAR(50),@BTypeID VARCHAR(50),@DeptID VARCHAR(50),@ElyID VARCHAR(1000),@CreatorID varchar(MAx),@WhsID VARCHAR(1000),@InWhsID VARCHAR(1000),@OutWhsID VARCHAR(1000),@PtypeID VARCHAR(MAX),@Summary VARCHAR(50),@SummaryType Int,@Description VARCHAR(50),@DescriptionType INT,@Remark varchar(50),@RemarkType Int,@OperatorID INT, @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)',@BeginDate,@EndDate,@BillTypeID,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@InWhsID,@OutWhsID,@PtypeID,@Summary,@SummaryType,@Description,@DescriptionType,@Remark,@RemarkType,@OperatorID, @Model, @AbbName, @Brand, @Spec, @BarCode


GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryInOutWhsBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryInOutWhsBill]
GO
/****** Object:  StoredProcedure [UP_PD_QueryInOutWhsBill]    Script Date: 06/16/2014 11:40:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/6/16
-- Description:	 查询其他出入库单
-- =============================================
CREATE PROCEDURE [UP_PD_QueryInOutWhsBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SqlMain NVARCHAR(4000), @SqlDetail NVARCHAR(4000),@SqlSerial   NVARCHAR(2000),
	        @MainTable NVARCHAR(40) = 'PD_InOutWhsBill', @DetailTable NVARCHAR(40) = 'PD_InOutWhsDetail', @SerialTable NVARCHAR(40) = 'PD_InOutWhsSerial'
	IF NOT EXISTS (SELECT 1 FROM PD_InOutWhsBill WHERE BillNo = @BillNo)
		BEGIN
			SET @MainTable += '_His'
			SET @DetailTable += '_His'
			set @SerialTable += '_His'
		END
	SET @SqlMain = 'SELECT inout.BillNo, inout.BillTypeID, inout.BillCode, inout.BillDate, inout.BTypeID, inout.DeptID, inout.ElyID, inout.WhsID, inout.BillQty, 
						   inout.Total, creator.ElyName AS CreatorName, inout.CreateTime, inout.PosElyID, inout.PosTime, inout.Summary, 
						   inout.Description, inout.Red, inout.IsDraft, inout.Creator AS CreatorID, inout.AuditStatus,
						   whs.WhsName, dept.DeptName, ely.ElyName, btype.BTypeName, pos.ElyName AS PosName
						   FROM ' + @MainTable + ' inout
						   LEFT JOIN BD_Whs whs ON inout.WhsID = whs.WhsID
						   LEFT JOIN BD_Dept dept ON inout.DeptID = dept.DeptID
						   LEFT JOIN BD_Employee ely ON inout.ElyID = ely.ElyID
						   LEFT JOIN BD_Employee creator ON inout.Creator = creator.ElyID
						   LEFT JOIN BD_Employee pos ON inout.PosElyID = pos.ElyID
						   LEFT JOIN BD_Btype btype ON inout.BTypeID = btype.BTypeID
					   WHERE inout.BillNo = @BillNo'  --查询主表
						
	EXEC sp_executesql @SqlMain, N'@BillNo INT', @BillNo
				       
	SET @SqlDetail = 'SELECT detail.DID, detail.BillNo, detail.BarCode, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.WhsID, 
						   detail.WhsPtID, detail.UnitID, detail.Convfactor, detail.Qty, detail.BSQty, detail.GoodsCostTotal, 
						   detail.CostPrice, detail.Price, detail.Remark, goods.GoodsNo, goods.GoodsName, goods.Spec, goods.Model, 
						   price.Unit, ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name, whspt.WhsPtName,
						   price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1, 
						   case when price1.Convfactor IS null then 1 else price1.Convfactor end  AS Convfactor1,
						   price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, 
						   case when price2.Convfactor IS null then 1 else price2.Convfactor end  AS Convfactor2,
						   price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3,
						   case when price3.Convfactor IS null then 1 else price3.Convfactor end  AS Convfactor3,
						   goods.IsSerial,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.InPutPrice,goods.DateType,goods.ValidDays,goods.CostMethod    
						   FROM ' + @DetailTable + ' detail
						   LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
						   LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID
						   LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
						   LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
						   LEFT JOIN BD_Whs_Position whspt ON whspt.WhsPtID = detail.WhsPtID
						   LEFT JOIN BD_Goods_Price price1 ON price1.GoodsID = detail.GoodsID
						   LEFT JOIN BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID And price2.UnitID = 2
						   LEFT JOIN BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID And price3.UnitID = 3
					   WHERE detail.BillNo = @BillNo AND price.UnitID = detail.UnitID
							AND price1.UnitID = 1'  --查询明细 
						
	EXEC sp_executesql @SqlDetail, N'@BillNo INT', @BillNo
	
	Set @SqlSerial = ' select Serial,BillDID,ps.Remark from ' +@SerialTable+ ' ps Inner Join '+@DetailTable+ ' pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	'
	 
	EXEC sp_executesql @SqlSerial, N'@BillNo INT', @BillNo
END
GO




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

/*------------------------------------------
    作者：李文博
	日期：2015-02-11
	描述：查询待开票的单据
-------------------------------------------*/
CREATE PROCEDURE UP_PD_QueryInvoiceBillData
(
	@BtypeID INT = 0, --往来单位
	@InvoiceBillType INT = 0, --发票类型（508销售发票，507采购发票）
	@BillTypeID TINYINT = 1, --单据类型
	@DeptID VARCHAR(MAX), --部门
	@ElyID VARCHAR(MAX), --经手人
	@BillCode VARCHAR(50), --单据编号
	@Summary VARCHAR(256), --摘要
	@Description VARCHAR(100), --说明
	@WhsID VARCHAR(MAX), --仓库
	@BeginDate VARCHAR(10), --开始日期
	@EndDate VARCHAR(10) --结束日期
)

AS

DECLARE @Sql NVARCHAR(MAX)='', @CreateTableSql NVARCHAR(MAX)='', @IndexSql NVARCHAR(MAX) ='', @TableSql NVARCHAR(MAX) = ''
DECLARE @BillNo NVARCHAR(100) = '', @BillTypeSql NVARCHAR(MAX) = '', @BuyFeeBill NVARCHAR(MAX) = '', @UnionSql NVARCHAR(100) = ''
DECLARE @BuyBill NVARCHAR(MAX) = '', @BuyBackBill NVARCHAR(MAX) = '', @SaleBill NVARCHAR(MAX) = '', @SaleBackBill NVARCHAR(MAX) = ''
DECLARE @FeeRecBill NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = '', @QCBill NVARCHAR(MAX) = '', @SaleFeeBill NVARCHAR(MAX) = ''

SET @IndexSql += ' AND IsInvoice = 1 ' --只查询是否开票为是的单据
IF @BeginDate <> ''
	SET @IndexSql += ' AND BillDate >= @BeginDate'
IF @EndDate <> ''
	SET @IndexSql += ' AND BillDate <= @EndDate'

SET @IndexSql += ' AND BillCode like ''%''+@BillCode+''%''  AND Summary Like ''%''+@Summary+''%'' AND Description Like ''%''+@Description+''%'' '

IF @DeptID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT) 
				 INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d 
				 INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID 
				 INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''
				 WHERE d2.SonNum = 0
				 '
	SET @TableSql+=' INNER JOIN @DType D ON I.DeptID=D.DeptID '	 
END
	
IF @ElyID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT) 
				 INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','') 
				 '
	SET @TableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '	 
END

IF @WhsID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @KType Table(WhsID INT) 
				 INSERT  INTO @KType SELECT typeid AS WhsID  FROM dbo.UF_OT_Split_Int(@WhsID,'','') 
				 '
	SET @TableSql+=' INNER JOIN @Ktype K ON I.WhsID=K.WhsID '
END

IF @InvoiceBillType = 507 --采购发票
BEGIN
	SET @BillNo = ' PchBillNo '
	--采购单
	IF @BillTypeID = 1 OR @BillTypeID = 101
	BEGIN
		SET @BuyBill = '
		SELECT	BillNo,	BillCode,	BillDate,	101 AS BillType,	Summary,	Description, 
				Total,	InvoiceTotal AS YInvoiceTotal, (Total - InvoiceTotal) AS NInvoiceTotal  
			FROM PD_PchBill I '+ @TableSql +'
			WHERE IsDraft = 0 AND Red = 0 AND BtypeID = @BtypeID AND (InvoiceMode = 0 OR InvoiceMode = 2) '+ @IndexSql
	END
	--采购退货单
	IF @BillTypeID = 1 OR @BillTypeID = 102
	BEGIN
		IF @BuyBill = '' SET @UnionSql = '' ELSE SET  @UnionSql = ' UNION ALL '
		SET @BuyBackBill = @UnionSql + '
		SELECT	BillNo,		BillCode,	BillDate,	102 AS BillType,	Summary,	Description, 
				Total*(-1) AS Total, (InvoiceTotal) AS YInvoiceTotal,	Total*(-1) - InvoiceTotal AS NInvoiceTotal  
			FROM PD_PchRetBill I '+ @TableSql +'
			WHERE IsDraft = 0 AND Red = 0 AND BtypeID = @BtypeID AND (InvoiceMode = 0 OR InvoiceMode = 2) '+ @IndexSql
	END
END ELSE
IF @InvoiceBillType = 508 --销售发票
BEGIN
	SET @BillNo = ' SellBillNo '
	--销售单
	IF @BillTypeID = 1 OR @BillTypeID = 201
	BEGIN
		SET @SaleBill = '
		SELECT	BillNo,	BillCode,	BillDate,	201 AS BillType,	Summary,	Description, 
				Total,	InvoiceTotal AS YInvoiceTotal, (Total - InvoiceTotal) AS NInvoiceTotal  
			FROM PD_SellBill I '+ @TableSql +'
			WHERE IsDraft = 0 AND Red = 0 AND BtypeID = @BtypeID AND (InvoiceMode = 0 OR InvoiceMode = 2) '+ @IndexSql
	END
	
	--销售退货单
	IF @BillTypeID = 1 OR @BillTypeID = 202
	BEGIN
		IF @SaleBill = '' SET @UnionSql = '' ELSE SET  @UnionSql = ' UNION ALL '
		SET @BuyBackBill = @UnionSql + '
		SELECT	BillNo,		BillCode,	BillDate,	202 AS BillType,	Summary,	Description, 
				Total*(-1) AS Total, (InvoiceTotal) AS YInvoiceTotal,	Total*(-1) - InvoiceTotal AS NInvoiceTotal  
			FROM PD_SellRetBill I '+ @TableSql +'
			WHERE IsDraft = 0 AND Red = 0 AND BtypeID = @BtypeID AND (InvoiceMode = 0 OR InvoiceMode = 2) '+ @IndexSql
	END
END

SET @Sql = @CreateTableSql + '
SELECT		BillNo AS '+ @BillNo +',		BD.BillCode,	BillDate,	BD.BillType,	BillName,	Summary,	Description,
			Total,		YInvoiceTotal,	NInvoiceTotal
FROM (
	'+ @BuyBill + @SaleBill + @BuyBackBill + @SaleBackBill + @FeeRecBill + @ARAPBill + @QcBill + @SaleFeeBill + @BuyFeeBill + '
	) BD '+ @BillTypeSql+'
INNER JOIN PD_BillType BT ON BD.BillType = BT.BillTypeID
WHERE NInvoiceTotal <> 0 ORDER BY BillType desc ,BillDate
'

--PRINT(@sql)
EXEC sp_executesql @sql,N'@BtypeID INT, @DeptID VARCHAR(MAX), @ElyID VARCHAR(MAX), @WhsID VARCHAR(MAX), @BillTypeID VARCHAR(MAX),@BillCode VARCHAR(50), 
@Summary VARCHAR(256),@Description VARCHAR(100),@BeginDate VARCHAR(10),@EndDate VARCHAR(10), @BillNo NVARCHAR(100)', 
@BtypeID, @DeptID, @ElyID, @WhsID, @BillTypeID, @BillCode, @Summary, @Description, @BeginDate, @EndDate, @BillNo


GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-7-15
	描述：查询进销存明细查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryJXCSum]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@WhsID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@PtypeID VARCHAR(max)='',
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@CollectType1 INT=1,  --汇总条件 1单据类型，2仓库分类
	@Layer1 INT=6,  --汇总层级 1-5（层级），5按仓库汇总
	@OrderType1 Varchar(50)='GoodsNo',	--排序条件，1=单据类型,2=仓库分类,3=商品分类,4=入库数量,5=出库数量,6=成本单价,7=入库金额,8=出库金额		
	@OrderSeq1 Int=1,  --排序类型 1=升序，2=降序
	@OperatorID INT,
	@isHistory INT=0,			--是否包含历史数据
	@ShowTotal Int = 0          --是否显示金额
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;


DECLARE @sql nvarchar(MAX)='',@InBill varchar(max)='',@OutBill varchar(Max)='',@StartOrEndInStock varchar(max)='',@EndOutStock varchar(max)='',
@sqlAllotOut nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlGoods nvarchar(max)='',@OrderName varchar(200)=''
,@SqlWhs varchar(Max)='',@SqlWhsIn varchar(Max)='',@SqlWhsOut varchar(Max)='',@SqlWhsStock varchar(Max)='',@SqlWhsInDb varchar(max)='',@SqlWhsOutDb varchar(max)='',@DateFlag int,
@SqlOrder NVARCHAR(MAX) = '',@SqlColumns Varchar(Max)='',@SqlGroup Nvarchar(MAX) = '',@SqlBase varchar(max)='',	@InspectTagStr varchar(100)='',	
@SummaryStr varchar(max)='',@DescriptionStr varchar(max)='',@RemarkStr varchar(max)='', @LimitSql NVARCHAR(MAX) = '',@LimitSqlIN nvarchar(max)='',@LimitSqlOut nvarchar(Max)='',@KtypeLimit INT=0
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
--Select @DateFlag=Case when datediff(DAY,MIN(StartDate), @BeginDate) >dateDiff(DAY,@EndDate,getdate()) then 1 Else 0 end  from SS_MonthProc
select @DateFlag = 0 
if exists(select 1 from SS_SysCfg where CfgName='AllotWithInspect' and CfgValue = 1) --判断是否启用调拨验证
	select @InspectTagStr = ' AND I.InspectTag = 1 '
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	Set @LimitSql += ' Inner Join  @LimitKType LW On I.WhsID=LW.TypeID  ' 
	Set @LimitSqlIN += ' Inner Join  @LimitKType LW On I.InWhsID=LW.TypeID  ' 
	Set @LimitSqlOut += ' Inner Join @LimitKType LW On I.OutWhsID=LW.TypeID ' 	
End	
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' Inner Join @DType D On I.DeptID=D.TypeID  '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' Inner Join @EType E On I.ElyID=E.TypeID  ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' Inner Join @CreateEType CE On I.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	Select @SqlWhs += ' Inner Join @KType W On I.WhsID=W.TypeID ' 
	Select @SqlWhsStock += ' Inner Join @KType W On I.WhsID=W.TypeID ' 
	Select @SqlWhsInDb += ' Inner Join @KType W On I.InWhsID=W.TypeID ' 
	Select @SqlWhsOutDb += ' Inner Join @KType W On I.OutWhsID=W.TypeID ' 
	Select @SqlWhsIn += ' Inner Join @KType W On bd.InWhsID=W.TypeID '
	Select @SqlWhsOut += ' Inner Join @KType W On bd.OutWhsID=W.TypeID '
END

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)='', @GoodsInfoSql NVARCHAR(4000)='', @GoodsInfoCols NVARCHAR(2000) = '', @TBAlias VARCHAR(1) = 'G' 
IF @Layer1 = 6 
   SET @TBAlias = 'I'
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   BEGIN
	   SET @SqlCreateTable+=' DECLARE @GoodsParam As Table(TypeID INT) insert into @GoodsParam Select goods.GoodsID FROM dbo.BD_Goods goods WHERE 1 = 1 ' + @ClauseParam
	   SET @SqlGoods+=' Inner Join @GoodsParam GP On '+@TBAlias+'.GoodsID=GP.TypeID  '
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
	   SET @SqlCreateTable+=' DECLARE @BarCodeParam As Table(TypeID INT) insert into @BarCodeParam Select DISTINCT pri.GoodsID FROM dbo.BD_Goods_Price pri WHERE 1 = 1 '	
	   IF @BarCodeMatch = 0
		   SET @SqlCreateTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlCreateTable += N' AND pri.BarCode = @BarCode '    
	   SET @SqlGoods+=' Inner Join @BarCodeParam BCP On '+@TBAlias+'.GoodsID=BCP.TypeID  '
   END    
/*end*/
	
IF @PtypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @PType As Table(TypeID INT) insert into @PType Select typeid from dbo.UF_OT_Split_Int(@PTypeID,'','') '
	if @Layer1 = 6
		SET @SqlGoods+=' Inner Join @PType P On I.GoodsID=P.TypeID '
	Else
		SET @SqlGoods+=' Inner Join @PType P On G.GoodsID=P.TypeID '
END	
if(@Layer1 = 6)
BEGIN
	Set @SqlColumns+=' BaseID,GoodsName,GoodsNo,'
	Set @SqlGroup +=' BaseID,GoodsName,GoodsNo'
	Set @SqlBase += ' (Select GoodsName,GoodsNo,GoodsID As BaseID from BD_Goods I ' + @SqlGoods +') G'
	SET @GoodsInfoCols += ' , g.Spec, g.Model, g.GoodsAbbName, g.Brand, b.BarCode '
	SET @GoodsInfoSql += ' INNER JOIN dbo.BD_Goods g ON g.GoodsID = tmp.BaseID 
						   INNER JOIN dbo.BD_Goods_Price b ON b.GoodsID = tmp.BaseID AND b.UnitID = 1 '
END
ELSE
BEGIN
	Set @SqlColumns+=' TypeName,TypeCode,'
	Set @SqlGroup +=' TypeName,TypeCode'
	Set @SqlBase += ' (Select TypeCode,TypeName,G.GoodsID As BaseID from BD_Goods_Type I 
						INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @Layer1) BS ON I.GoodsTypeID=BS.BaseID 
						Inner Join BD_Goods G On BS.ParID=G.GoodsTypeID' + @SqlGoods +') G'
END
--
select @InBill +=' 
UNION ALL 
	SELECT  BD.GoodsID,'
	+ CASE WHEN BillTypeID = 101 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyQty,'
	+ ' 0 As BuyBackQty,'
	+ ' 0 As SaleQty,'
	+ CASE WHEN BillTypeID = 202 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleBackQty,'
	+ CASE WHEN BillTypeID = 301 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotTInQty,'
	+ CASE WHEN BillTypeID = 309 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotBInQty,'
	+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyInQty,'
	+' 0 As AllotTOutQty,'
	+' 0 As AllotBOutQty,'
	+' 0 As AssemblyOutQty,'
	+ CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceInQty,'
    + ' 0 As AdjuestPriceOutQty,'
	+ CASE WHEN BillTypeID = 303 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherInQty,'
	+ ' 0 As OtherOutQty,'
	+ CASE WHEN BillTypeID = 306 then ' Sum(BD.BSQty)' else ' 0' End + ' As PlusStockQty,'
	+ ' 0 As ExchangeOutQty, 0 As MinusStockQty,'
	+ CASE WHEN BillTypeID IN (301,309) THEN ' Sum(BD.InspectQty)' ELSE ' Sum(BD.BSQty) ' END + ' as InBsQty,' 
	+ ' 0 as OutBsQty' 
	+ Case When @ShowTotal = 1 then	
		 CASE WHEN BillTypeID = 101 then ' ,sum(BD.GoodsCostTotal)' else ' ,0' End + ' As BuyTotal,'
		+ ' 0 As BuyBackTotal,'
		+ ' 0 As SaleTotal,'
		+ CASE WHEN BillTypeID = 202 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleBackTotal,'
		+ CASE WHEN BillTypeID = 301 then ' sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' else ' 0' End + ' As AllotTInTotal,'
		+ CASE WHEN BillTypeID = 309 then ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' else ' 0' End + ' As AllotBInTotal,'
		+ CASE WHEN BillTypeID = 310 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyInTotal,'
		+ ' 0 As AllotTOutTotal,'
		+ ' 0 As AllotBOutTotal,'
		+ ' 0 As AssemblyOutTotal,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.AdjTotal)' else ' 0' End + ' As AdjuestPriceInTotal,'
		+ ' 0 As AdjuestPriceOutTotal,'
		+ CASE WHEN BillTypeID = 303 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherInTotal,'
		+ ' 0 As OtherOutTotal, '
		+ CASE WHEN BillTypeID = 306 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As PlusStockTotal,'
		+ ' 0 AS ExchangeOutTotal, 0 As MinusStockTotal,'
		+ CASE BillTypeID WHEN 302 Then ' Sum(BD.AdjTotal)' WHEN 309 THEN ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' when 301 then ' SUM(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' Else ' Sum(BD.GoodsCostTotal)' End + ' AS InToTal,'
		+ ' 0 AS OutToTal'
	Else ''	End
	+' FROM  ' + BillDetail + ' BD '
	+'Inner Join  '+BillTable+' I On I.BillNo=bd.BillNo ' + @SqlTable
		+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
		+Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsIn Else @SqlWhsInDb End
	+' Where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  '	
	+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=1 ' ELSE '' END 	 
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
	+' Group By GoodsID
	 '
FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309,310)
And CanPost=1 
Select @OutBill += '
UNION ALL 
	SELECT  BD.GoodsID,'
	+ ' 0 As BuyQty,'
	+ CASE WHEN BillTypeID = 102 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyBackQty,'
	+ CASE WHEN BillTypeID = 201 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleQty,'
	+ ' 0 As SaleBackQty,'
	+ ' 0 As AllotTInQty,'
	+ ' 0 As AllotBInQty,'
	+ ' 0 As AssemblyInQty,'
	+ CASE WHEN BillTypeID = 301 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotTOutQty,'
	+ CASE WHEN BillTypeID = 309 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotBOutQty,'
	+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyOutQty,'
	+ ' 0 As AdjuestPriceInQty,'
    + CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceOutQty,'
	+ ' 0 As OtherInQty,'
	+ CASE WHEN BillTypeID = 304 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherOutQty,'
	+ ' 0 As PlusStockQty,'
	+ CASE WHEN BillTypeID = 600 then ' Sum(BD.BSQty)' else ' 0' End + ' As ExchangeOutQty,'
	+ CASE WHEN BillTypeID = 305 then ' Sum(BD.BSQty)' else ' 0' End + ' As MinusStockQty,'	
	+ ' 0 as InBsQty,' 
	+ ' Sum(BD.BSQty) as OutBsQty' 
	+ Case When @ShowTotal = 1 then	
		 ' ,0 As BuyTotal,'
		+ CASE WHEN BillTypeID = 102 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As BuyBackTotal,'
		+ CASE WHEN BillTypeID = 201 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleTotal,'
		+ ' 0 As SaleBackTotal,'
		+ ' 0 As AllotTInTotal,'
		+ ' 0 As AllotBInTotal,'
		+ ' 0 As AssemblyInTotal,'
		+ CASE WHEN BillTypeID = 301 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotTOutTotal,'
		+ CASE WHEN BillTypeID = 309 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotBOutTotal,'
		+ CASE WHEN BillTypeID = 310 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyOutTotal,'
		+ ' 0 As AdjuestPriceInTotal,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AdjuestPriceOutTotal,'
		+ ' 0 As OtherInTotal,'
		+ CASE WHEN BillTypeID = 304 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherOutTotal,'
		+ ' 0 As PlusStockTotal,'
		+ CASE WHEN BillTypeID = 600 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As ExchangeOutTotal,'
		+ CASE WHEN BillTypeID = 305 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As MinusStockTotal,'
		+ ' 0 AS InToTal,'
		+ ' Sum(BD.GoodsCostTotal) AS OutToTal'
	Else '' End
	+' FROM  ' + BillDetail + ' BD '
	+'Inner Join  '+BillTable+' I On I.BillNo=bd.BillNo  ' + @SqlTable
		+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
		+Case When billtypeid IN(102,201,302,304,305,600) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsOut Else @SqlWhsOutDb End
	 +' where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 '	
	 + CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=2 ' ELSE '' END 	 
	 +CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
	+' Group By GoodsID
	 '
FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)

Select @StartOrEndInStock += '
UNION ALL 
	SELECT  BD.GoodsID,'
	+ CASE WHEN BillTypeID IN (301,309) THEN 'SUM(BD.InspectQty)' ELSE 'Sum(bd.BSQty)' END + ' as BsQty'
	+ Case When @ShowTotal = 1 then	
		case When BillTypeID = 302 then ' ,Sum(bd.AdjTotal)'
		When BillTypeID = 301 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)'
		When BillTypeID = 309 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.AllOtTotal End)'
		Else ' ,Sum(bd.GoodsCostTotal)' End +' as GoodsCostTotal '
	Else '' End
	+' From ' + BillDetail +' BD Inner Join  '+BillTable+' I On I.BillNo=bd.BillNo '	
	+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
	+ @SqlTable +Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsIn Else @SqlWhsInDb End
	+' where ' + Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End + ' and IsDraft=0 And Red = 0 '
	+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=1 ' ELSE '' END 	 
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END			 
	+' Group By GoodsID
	 '
	FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309,310)
Select @StartOrEndInStock += '
UNION ALL 
	SELECT  BD.GoodsID,Sum(bd.BSQty)*-1 as BsQty '
	+ Case When @ShowTotal = 1 then	',SUM(bd.GoodsCostTotal)*-1 as GoodsCostTotal '
	  Else '' End
	+' From ' + BillDetail +' BD Inner Join '+BillTable+' I On I.BillNo=bd.BillNo '
	+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
	+ @SqlTable +Case When billtypeid IN (102,201,302,304,305,600) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsOut Else @SqlWhsOutDb End
	+' where ' + Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End +' and IsDraft=0 And Red = 0 '
	+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=2 ' ELSE '' END 	 
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
	 
	+' Group By GoodsID
	 '
	FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)
if @isHistory = 1 or @DateFlag=0
Begin
	Select @StartOrEndInStock += '
	UNION ALL 
		SELECT  BD.GoodsID,' 
		+ CASE WHEN BillTypeID IN (301.309) THEN 'SUM(BD.InspectQty)' ELSE 'Sum(bd.BSQty)' END + ' as BsQty'
		+ Case When @ShowTotal = 1 then	
			case When BillTypeID = 302 then ' ,Sum(bd.AdjTotal)' 
			When BillTypeID = 301 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)'
			When BillTypeID = 309 then ' ,Sum(case BD.InspectQty when 0 then 0 else BD.AllOtTotal End)'
			Else ' ,Sum(bd.GoodsCostTotal)' End +' as GoodsCostTotal '
		Else '' End
		+ ' From '	+ BillDetail +'_His BD Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo '
		+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
		+ @SqlTable +Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsIn Else @SqlWhsInDb End
		+' where '+ Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End +' and IsDraft=0 And Red = 0  '
		+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=1 ' ELSE '' END 	 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		
		+' Group By GoodsID '
		FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309,310)
	Select @StartOrEndInStock += '
	UNION ALL 
		SELECT  BD.GoodsID,Sum(bd.BSQty)*-1 as BsQty '
		+ Case When @ShowTotal = 1 then	',SUM(bd.GoodsCostTotal)*-1 as GoodsCostTotal '
		  Else '' End
		+' From ' + BillDetail +'_His BD Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo '
		+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
		+ @SqlTable +Case When billtypeid IN (102,201,302,304,305,600) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsOut Else @SqlWhsOutDb End
		+' where ' + Case When @DateFlag =1 then ' BD.BillDate > @EndDate ' Else ' BD.BillDate < @BeginDate' End +' and IsDraft=0 And Red = 0 '
		+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=2 ' ELSE '' END 	 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		
		+' Group By GoodsID '
		FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)
End
IF @isHistory=1
Begin
	select @InBill +=' 
	UNION ALL 
		SELECT  BD.GoodsID,'
		+ CASE WHEN BillTypeID = 101 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyQty,'
		+ ' 0 As BuyBackQty,'
		+ ' 0 As SaleQty,'
		+ CASE WHEN BillTypeID = 202 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleBackQty,'
		+ CASE WHEN BillTypeID = 301 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotTInQty,'
		+ CASE WHEN BillTypeID = 309 then ' Sum(BD.InspectQty)' else ' 0' End + ' As AllotBInQty,'
		+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyInQty,'
		+' 0 As AllotTOutQty,'
		+' 0 As AllotBOutQty,'
		+' 0 As AssemblyOutQty,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceInQty,'
		+ ' 0 As AdjuestPriceOutQty,'
		+ CASE WHEN BillTypeID = 303 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherInQty,'
		+ ' 0 As OtherOutQty,'
		+ CASE WHEN BillTypeID = 306 then ' Sum(BD.BSQty)' else ' 0' End + ' As PlusStockQty,'
		+ ' 0 As ExchangeOutQty, 0 As MinusStockQty,'
		+ CASE WHEN BillTypeID IN (301,309) THEN ' Sum(BD.InspectQty)' ELSE ' Sum(BD.BSQty) ' END + ' as InBsQty,' 
		+ ' 0 as OutBsQty' 
		+ Case When @ShowTotal = 1 then	
			 CASE WHEN BillTypeID = 101 then ' ,sum(BD.GoodsCostTotal)' else ' ,0' End + ' As BuyTotal,'
			+ ' 0 As BuyBackTotal,'
			+ ' 0 As SaleTotal,'
			+ CASE WHEN BillTypeID = 202 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleBackTotal,'
			+ CASE WHEN BillTypeID = 301 then ' sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' else ' 0' End + ' As AllotTInTotal,'
			+ CASE WHEN BillTypeID = 309 then ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' else ' 0' End + ' As AllotBInTotal,'
			+ CASE WHEN BillTypeID = 310 then ' sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyInTotal,'
			+ ' 0 As AllotTOutTotal,'
			+ ' 0 As AllotBOutTotal,'
			+ ' 0 As AssemblyOutTotal,'
			+ CASE WHEN BillTypeID = 302 then ' Sum(BD.AdjTotal)' else ' 0' End + ' As AdjuestPriceInTotal,'
			+ ' 0 As AdjuestPriceOutTotal,'
			+ CASE WHEN BillTypeID = 303 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherInTotal,'
			+ ' 0 As OtherOutTotal,'
			+ CASE WHEN BillTypeID = 306 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As PlusStockTotal,'
			+ ' 0 AS ExchangeOutTotal, 0 As MinusStockTotal,'
			+ CASE BillTypeID WHEN 302 Then ' Sum(BD.AdjTotal)' WHEN 309 THEN ' sum(case BD.InspectQty when 0 then 0 else BD.AllotTotal End)' WHEN 301 THEN ' sum(case BD.InspectQty when 0 then 0 else BD.GoodsCostTotal End)' Else ' Sum(BD.GoodsCostTotal)' End + ' AS InToTal,'
			+ ' 0 AS OutToTal'
		Else '' ENd
		+' FROM  ' + BillDetail + '_His BD '
		+' Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo ' + @SqlTable
			+Case When billtypeid IN(101,202,302,303,306) Then @LimitSql Else @LimitSqlIN End
			+Case When billtypeid IN(101,202,302,303,306) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsIn Else @SqlWhsInDb End
			+' where  BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0 '
			+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=1 ' ELSE '' END 
			
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		+'  Group By GoodsID
		 '
	FROM PD_BillType b where BillTypeID in (101,202,301,302,303,306,309,310)
	And CanPost=1 
	Select @OutBill += '
	UNION ALL 
		SELECT  BD.GoodsID,'
		+ ' 0 As BuyQty,'
		+ CASE WHEN BillTypeID = 102 then ' Sum(BD.BSQty)' else ' 0' End + ' As BuyBackQty,'
		+ CASE WHEN BillTypeID = 201 then ' Sum(BD.BSQty)' else ' 0' End + ' As SaleQty,'
		+ ' 0 As SaleBackQty,'
		+ ' 0 As AllotTInQty,'
		+ ' 0 As AllotBInQty,'
		+ ' 0 As AssemblyInQty,'
		+ CASE WHEN BillTypeID = 301 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotTOutQty,'
		+ CASE WHEN BillTypeID = 309 then ' Sum(BD.BSQty)' else ' 0' End + ' As AllotBOutQty,'
		+ CASE WHEN BillTypeID = 310 then ' Sum(BD.BSQty)' else ' 0' End + ' As AssemblyOutQty,'
		+ ' 0 As AdjuestPriceInQty,'
		+ CASE WHEN BillTypeID = 302 then ' Sum(BD.BSQty)' else ' 0' End + ' As AdjuestPriceOutQty,'
		+ ' 0 As OtherInQty,'
		+ CASE WHEN BillTypeID = 304 then ' Sum(BD.BSQty)' else ' 0' End + ' As OtherOutQty,'
		+ ' 0 As PlusStockQty,'
		+ CASE WHEN BillTypeID = 600 then ' Sum(BD.BSQty)' else ' 0' End + ' As ExchangeOutQty,'
		+ CASE WHEN BillTypeID = 305 then ' Sum(BD.BSQty)' else ' 0' End + ' As MinusStockQty,'	
		+ ' 0 as InBsQty,' 
		+ ' Sum(BD.BSQty) as OutBsQty' 
		+ Case When @ShowTotal = 1 then	
			 ' ,0 As BuyTotal,'
			+ CASE WHEN BillTypeID = 102 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As BuyBackTotal,'
			+ CASE WHEN BillTypeID = 201 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As SaleTotal,'
			+ ' 0 As SaleBackTotal,'
			+ ' 0 As AllotTInTotal,'
			+ ' 0 As AllotBInTotal,'
			+ ' 0 As AssemblyInTotal,'
			+ CASE WHEN BillTypeID = 301 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotTOutTotal,'
			+ CASE WHEN BillTypeID = 309 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AllotBOutTotal,'
			+ CASE WHEN BillTypeID = 310 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AssemblyOutTotal,'
			+ ' 0 As AdjuestPriceInTotal,'
			+ CASE WHEN BillTypeID = 302 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As AdjuestPriceOutTotal,'
			+ ' 0 As OtherInTotal,'
			+ CASE WHEN BillTypeID = 304 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As OtherOutTotal,'
			+ ' 0 As PlusStockTotal,'
			+ CASE WHEN BillTypeID = 600 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As ExchangeOutTotal,'
			+ CASE WHEN BillTypeID = 305 then ' Sum(BD.GoodsCostTotal)' else ' 0' End + ' As MinusStockTotal,'
			+ ' 0 AS InToTal,'
			+ ' Sum(BD.GoodsCostTotal) AS OutToTal'
		Else '' End
		+' FROM  ' + BillDetail + '_His BD '
		+' Inner Join '+BillTable+'_His I On I.BillNo=bd.BillNo ' + @SqlTable
			+Case When billtypeid IN(102,201,302,304,305,600) Then @LimitSql Else @LimitSqlOut End
			+Case When billtypeid IN(102,201,302,304,305,600) Then @SqlWhs WHEN billtypeid IN(301,309) THEN @SqlWhsOut Else @SqlWhsOutDb End
			+' Where BD.BillDate BETWEEN @BeginDate AND @EndDate and IsDraft=0 And Red = 0  '
			+ CASE WHEN billtypeid = 310 THEN ' AND BD.DetailType=2 ' ELSE '' END 
			
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END		
		+' Group By GoodsID
		 '
	FROM PD_BillType b where BillTypeID in (102,201,301,302,304,305,309,310,600)

End

SELECT @sql +=@SqlCreateTable+'
;WITH Bill AS 
('	+STUFF(@InBill+@OutBill,1,12,'')+'
)'
Select @Sql +=',StartOrEndInOutStock as
(' +STUFF(@StartOrEndInStock,1,12,'')+')
,StartOrEndStock as --开始日期之前或者截止日期之后数量，金额
(
	select GoodsID,sum(BSQty) as StartOrEndStockQty'+ Case When @ShowTotal = 1 then	',SUM(GoodsCostTotal) as StartOrEndStockTotal ' else '' end
	+'  from StartOrEndInOutStock group by GoodsID	
)
,GoodsStock as  --库存(或者期初)数量，金额
('+Case When @DateFlag =1 then ' select G.goodsid,SUM(Qty) as qty'+ Case When @ShowTotal = 1 then	',SUM(Total) as total ' else '' end
	+' from bd_Goods g Left join (select GoodsID,WhsID,Qty' + case when @ShowTotal = 1 then ',total ' else '' end +' from PD_GoodsStock I '+@SqlWhsStock +@LimitSql +') I on g.GoodsID = I.goodsID   group by G.goodsid '
	Else
	' select G.goodsid,SUM(Qty) as qty'+ Case When @ShowTotal = 1 then	',SUM(Total) as total ' else '' end
	+' from  bd_Goods g Left join (select GoodsID,WhsID,Qty' + case when @ShowTotal = 1 then ',total ' else '' end +' from BD_OpeningStock I '+@SqlWhsStock+ @LimitSql+') I on g.GoodsID = I.goodsID group by G.goodsid '
	End	
+')'
select @sql += '
	,InOutStockSum as  --出库合计和入库合计
	(
		select 	GoodsID,sum(InBsQty) as INStockQty,sum(OutBsQty) as OutStockQty ' + Case When @ShowTotal = 1 then ',SUM(InToTal) as INStockTotal,SUM(OutToTal) as OutStockTotal '  Else '' End 
		+ ' from bill group by GoodsID
	)'
if @DateFlag = 1 
Begin
	select @sql += ',EndStockSum as --截止数量，金额
	(
		select a.goodsid,IsNull(a.Qty,0) - isnull(b.StartOrEndStockQty,0) as EndStockQty'
		+ Case When @ShowTotal = 1 then	',IsNull(a.Total,0)-  ISNULL(b.StartOrEndStockTotal,0) as EndStockTotal ' else '' End 
		+ ' from GoodsStock a left join StartOrEndStock b on a.GoodsID = b.GoodsID
	)'
	select @sql += '
	,StartStockSum as --开始数量、金额
	(
		select A.GoodsID,IsNUll(OutStockQty,0) - ISNULL(InStockQty,0) + ISNULL(EndStockQty,0) as BeforeQty '
			   + Case When @ShowTotal = 1 then ',ISNULL(OutStockTotal,0) - ISNULL(InStockTotal,0) + ISNULL(EndStockTotal,0) as BeforeTotal ' Else '' End
		+ ' from EndStockSum A left Join InOutStockSum B on a.GoodsID= b.GoodsID 
	)'
End
Else
Begin	
	select @sql +=',StartStockSum as --开始数量、金额
	(
		select a.goodsid,IsNull(a.Qty,0) + isnull(b.StartOrEndStockQty,0) as BeforeQty'
		+ Case When @ShowTotal = 1 then	',isnull(a.Total,0) + ISNULL(b.StartOrEndStockTotal,0) as BeforeTotal ' else '' End 
		+ ' from GoodsStock a left join StartOrEndStock b on a.GoodsID = b.GoodsID
	)'
	select @sql += ',EndStockSum as --截止数量，金额
	(
	select A.GoodsID,ISNULL(BeforeQty,0) + IsNUll(InStockQty,0) - ISNULL(OutStockQty,0)  as EndStockQty '
			   + Case When @ShowTotal = 1 then ',ISNULL(BeforeTotal,0)+ISNULL(InStockTotal,0) - ISNULL(OutStockTotal,0) as EndStockTotal ' Else '' End
		+ ' from StartStockSum A left Join InOutStockSum B on a.GoodsID= b.GoodsID 
	)'
End
Select @Sql += ' ,StockData as
( 	select  GoodsID,Sum(BuyQty) as BuyQty,Sum(BuyBackQty) as BuyBackQty,Sum(SaleQty) as SaleQty,Sum(SaleBackQty) as SaleBackQty,Sum(AllotTInQty) as AllotTInQty,Sum(AllotBInQty) as AllotBInQty,Sum(AllotTOutQty) as AllotTOutQty,Sum(AllotBOutQty) as AllotBOutQty,
	Sum(AdjuestPriceInQty) as AdjuestPriceInQty,Sum(AdjuestPriceOutQty) as AdjuestPriceOutQty,Sum(OtherInQty) as OtherInQty,Sum(OtherOutQty) as OtherOutQty,Sum(PlusStockQty) as PlusStockQty,Sum(ExchangeOutQty) as ExchangeOutQty,Sum(MinusStockQty) as MinusStockQty,Sum(AssemblyInQty) as AssemblyInQty,Sum(AssemblyOutQty) as AssemblyOutQty'
	+ Case When @ShowTotal = 1 then	',Sum(BuyTotal) as BuyTotal,Sum(BuyBackTotal) as BuyBackTotal,Sum(SaleTotal) as SaleTotal,Sum(SaleBackTotal) as SaleBackTotal,Sum(AllotTInTotal) as AllotTInTotal,Sum(AllotBInTotal) as AllotBInTotal,Sum(AllotTOutTotal) as AllotTOutTotal,Sum(AllotBOutTotal) as AllotBOutTotal,
	Sum(AdjuestPriceInTotal) as AdjuestPriceInTotal,Sum(AdjuestPriceOutTotal) as AdjuestPriceOutTotal,Sum(OtherInTotal) as OtherInTotal,Sum(OtherOutTotal) as OtherOutTotal,Sum(PlusStockTotal) as PlusStockTotal,Sum(ExchangeOutTotal) as ExchangeOutTotal,Sum(MinusStockTotal) as MinusStockTotal,sum(AssemblyInTotal) as AssemblyInTotal,sum(AssemblyOutTotal) as AssemblyOutTotal '
	Else '' End
	+' from Bill Group By  GoodsID
) '
select @Sql += ',PagingData as
(
	select '+@SqlColumns+' Sum(BuyQty) as BuyQty,Sum(BuyBackQty) as BuyBackQty,Sum(SaleQty) as SaleQty,Sum(SaleBackQty) as SaleBackQty,Sum(AllotTInQty) as AllotTInQty,Sum(AllotBInQty) as AllotBInQty,Sum(AllotTOutQty) as AllotTOutQty,Sum(AllotBOutQty) as AllotBOutQty,
	Sum(AdjuestPriceInQty) as AdjuestPriceInQty,Sum(AdjuestPriceOutQty) as AdjuestPriceOutQty,Sum(OtherInQty) as OtherInQty,Sum(OtherOutQty) as OtherOutQty,Sum(PlusStockQty) as PlusStockQty,Sum(ExchangeOutQty) as ExchangeOutQty,Sum(MinusStockQty) as MinusStockQty,Sum(AssemblyInQty) as AssemblyInQty,Sum(AssemblyOutQty) as AssemblyOutQty,
	Sum(IOSS.InStockQty) as InStockQty,Sum(IOSS.OutStockQty) as OutStockQty,Sum(sss.BeforeQty) as BeforeQty,Sum(ESS.EndStockQty) as EndStockQty '
	+ Case When @ShowTotal = 1 then ',Sum(BuyTotal) as BuyTotal,Sum(BuyBackTotal) as BuyBackTotal,Sum(SaleTotal) as SaleTotal,Sum(SaleBackTotal) as SaleBackTotal,Sum(AllotTInTotal) as AllotTInTotal,Sum(AllotBInTotal) as AllotBInTotal,Sum(AllotTOutTotal) as AllotTOutTotal,Sum(AllotBOutTotal) as AllotBOutTotal,
	Sum(AdjuestPriceInTotal) as AdjuestPriceInTotal,Sum(AdjuestPriceOutTotal) as AdjuestPriceOutTotal,Sum(OtherInTotal) as OtherInTotal,Sum(OtherOutTotal) as OtherOutTotal,Sum(PlusStockTotal) as PlusStockTotal,Sum(ExchangeOutTotal) as ExchangeOutTotal,Sum(MinusStockTotal) as MinusStockTotal,sum(AssemblyInTotal) as AssemblyInTotal,sum(AssemblyOutTotal) as AssemblyOutTotal
	,Sum(IOSS.InStockTotal) as InStockTotal,Sum(IOSS.OutStockTotal) as OutStockTotal,Sum(sss.BeforeTotal) as BeforeTotal,Sum(ESS.EndStockTotal) as EndStockTotal,case sum(EndStockQty) when 0 then 0 else Convert(NUMERIC(17,8),sum(EndStockTotal))/Convert(NUMERIC(17,8),sum(EndStockQty)) end as CostPrice '
	Else '' End
	+' from '+@SqlBase+' Left Join StockData SD on g.BaseID = SD.GoodsID 	
	left Join InOutStockSum IOSS  on G.BaseID =IOSS.GoodsID 
	Left join StartStockSum SSS on G.BaseID = SSS.GoodsID
	left join EndStockSum ESS on G.BaseID = ESS.GoodsID
	where BuyQty<>0 Or BuyBackQty <> 0 Or SaleQty<>0 Or SaleBackQty<>0 Or AllotTInQty<>0 Or AllotTOutQty<>0 Or AllotBInQty<>0 Or AllotBOutQty<>0 Or AdjuestPriceInQty <> 0 
			Or AdjuestPriceOutQty <> 0 Or OtherInQty <> 0 Or OtherOutQty<>0 Or PlusStockQty <> 0 Or ExchangeOutQty <> 0 Or MinusStockQty <> 0 
			Or IOSS.InStockQty <> 0 Or IOSS.OutStockQty<>0 Or sss.BeforeQty <> 0 Or ESS.EndStockQty <> 0'
	+ Case When @ShowTotal = 1 then ' Or BuyToTal<>0 Or BuyBackToTal <> 0 Or SaleToTal<>0 Or SaleBackToTal<>0 Or AllotTInToTal<>0 Or AllotBInToTal<>0 
			Or AllotTOutToTal<>0 Or AllotBOutToTal<>0 Or AdjuestPriceInToTal <> 0 Or AdjuestPriceOutToTal <> 0 Or OtherInToTal <> 0 Or OtherOutToTal<>0 
			Or PlusStockToTal <> 0 Or ExchangeOutTotal <> 0 Or MinusStockToTal <> 0 Or IOSS.InStockTotal<>0 Or IOSS.OutStockTotal<>0 Or sss.BeforeTotal<>0
			Or ESS.EndStockTotal <> 0'
	Else '' End
	+ ' group by '+@SqlGroup+'
)
'
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

---排序字段
IF @OrderType1 <> ''
BEGIN
	IF @OrderSeq1 = 1 SET @OrderName = @OrderType1+' ASC' ELSE SET @OrderName = @OrderType1 +' DESC'
END
------------------添加参数---------------------------------------
select @sql += ',DATA AS (
SELECT 
  ROW_NUMBER() OVER( ORDER BY   '+@OrderName+' ) AS ROWID, 
  count(*) over() as '''+'rowcount'+''', *	 
FROM PagingData

) 
SELECT * INTO #JXCSumTempTb FROM (select * from data
WHERE ROWID>(@PageNo-1)*@PageSize aND ROWID<=@PageNo*@PageSize)S;
SELECT tmp.* ' + @GoodsInfoCols + ' FROM #JXCSumTempTb tmp ' + @GoodsInfoSql + ';
DROP TABLE #JXCSumTempTb; '
IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
	 --PRINT @sql
exec sp_executesql @sql,N'@PageNo Int,@PageSize Int,@BeginDate Date,@EndDate Date,@OperatorID Int,@DeptID VarChar(MAX),@ElyID VarChar(MAX),@CreatorID varchar(MAx)
						,@WhsID VarChar(MAX),@PTypeID VarChar(MAX),@Layer1 Int, @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)'
						,@PageNo,@PageSize,@BeginDate,@EndDate,@OperatorID,@DeptID,@ElyID,@CreatorID,@WhsID,@PTypeID,@Layer1, @Model, @AbbName, @Brand, @Spec, @BarCode

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryLossSpillBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryLossSpillBillData
GO
/****** Object:  StoredProcedure [UP_PD_QueryLossSpillBillData]    Script Date: 06/16/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		hanlin
-- Create date:  2014/6/16
-- Description:	 查询报损报溢单数据
-- =============================================
CREATE PROCEDURE [UP_PD_QueryLossSpillBillData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS
BEGIN

IF EXISTS(SELECT 1 FROM PD_LossSpillBill WHERE BillNo=@BillNo)
BEGIN
	SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			BillTypeID AS BillType,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.WhsID,
			w.WhsName,
			Summary,
			Description,
			BillQty,
			Total,
			InPutPrice,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			Red,
			IsDraft,
			IsOS,
			p.AuditStatus
	FROM PD_LossSpillBill p
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs w ON w.WhsID=p.WhsID
	WHERE BillNo=@BillNo
	
	SELECT  P.DID,
			p.GoodsID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			g.Spec,
			p.WhsPtID,
			p.WhsID,
			wp.WhsPtName,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			ROUND(CostPrice*p.Convfactor,8) AS CostPrice,
			CostPrice AS GoodsCostPrice,
			Qty,
			BSQty,
			GoodsCostTotal,
			p.Remark,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,		
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			g.IsSerial,
			p.BatchNumber,
			p.ProductDate,
			p.EndDate,
			p.InPutPrice,g.DateType,g.ValidDays,g.CostMethod,p.IsSelectBatch			
	FROM PD_LossSpillDetail p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2 
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_LossSpillSerial ps Inner Join PD_LossSpillDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
END
ELSE
BEGIN
	SELECT	TOP 1
			BillCode,
			BillDate,
			BillNo,
			BillTypeID AS BillType,
			p.DeptID,
			d.DeptName,
			p.ElyID,
			e.ElyName,
			p.WhsID,
			w.WhsName,
			Summary,
			Description,
			BillQty,
			Total,
			InPutPrice,
			p.Creator AS CreatorID,
			e1.ElyName AS CreatorName,
			e2.ElyName AS PosName,
			Red,
			IsDraft,
			IsOS,
			p.AuditStatus
	FROM PD_LossSpillBill_his p
	INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
	LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID
	LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
	INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
	INNER JOIN BD_Whs w ON w.WhsID=p.WhsID
	WHERE BillNo=@BillNo
	
	SELECT  P.DID,
			p.GoodsID,
			g.GoodsNo,
			g.GoodsName,
			p.BarCode,
			g.Model,
			g.Spec,
			p.WhsPtID,
			p.WhsID,
			wp.WhsPtName,
			p.Ppt1ID,
			p1.Value AS Ppt1Name,
			p.Ppt2ID,
			p2.Value AS Ppt2Name,
			p.UnitID,
			gp.Unit,
			p.Convfactor,
			ROUND(CostPrice*p.Convfactor,8) AS CostPrice,
			CostPrice AS GoodsCostPrice,
			Qty,
			BSQty,
			GoodsCostTotal,
			p.Remark,
			gp1.Convfactor Convfactor1,
			ISNULL(gp2.Convfactor,1) AS Convfactor2,
			ISNULL(gp3.Convfactor,1) AS Convfactor3,		
			gp1.Unit Unit1,
			gp2.Unit Unit2,
			gp3.Unit Unit3	,
			gp1.BarCode[BarCode1],
			gp2.BarCode[BarCode2],
			gp3.BarCode[BarCode3],
			g.IsSerial,
			p.BatchNumber,
			p.ProductDate,
			p.EndDate,
			p.InPutPrice,g.DateType,g.ValidDays,g.CostMethod		
	FROM PD_LossSpillDetail_his p
	INNER JOIN BD_Goods_Price gp ON p.GoodsID = gp.GoodsID AND p.UnitID = gp.UnitID
	INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID
	INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID
	LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID
	LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
	LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND gp2.UnitID=2 
	LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND gp3.UnitID=3
	WHERE BillNo=@BillNo 
	
	select Serial,BillDID,ps.Remark from PD_LossSpillSerial_His ps Inner Join PD_LossSpillDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
END	
END
GO




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

/*------------------------------------------
    作者：李文博
	日期：2014-06-14
	描述：查询往来单位对应的未结算单据
-------------------------------------------*/
CREATE PROCEDURE UP_PD_QueryNoPaidBill
(
	@BtypeID INT = 0,
	@BillTypeID VARCHAR(MAX),
	@DeptID VARCHAR(MAX),
	@ElyID VARCHAR(MAX),
	@BillCode VARCHAR(50),
	@Summary VARCHAR(256),
	@Description VARCHAR(100),
	@BeginDate VARCHAR(10),
	@EndDate VARCHAR(10),
	@PayRecType INT = 0
)

AS

DECLARE @Sql NVARCHAR(MAX)='', @CreateTableSql NVARCHAR(MAX)='', @IndexSql NVARCHAR(MAX) ='', @TableSql NVARCHAR(MAX) = ''
DECLARE @BtypeName VARCHAR(100), @QCBillDate DATE = '1900-01-01', @BillTypeSql NVARCHAR(MAX) = '', @BuyFeeBill NVARCHAR(MAX) = ''
DECLARE @BuyBill NVARCHAR(MAX) = '', @BuyBackBill NVARCHAR(MAX) = '', @SaleBill NVARCHAR(MAX) = '', @SaleBackBill NVARCHAR(MAX) = ''
DECLARE @FeeRecBill NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = '', @QCBill NVARCHAR(MAX) = '', @SaleFeeBill NVARCHAR(MAX) = ''

SELECT @BtypeName = BTypeName FROM BD_Btype WHERE BTypeID = @BtypeID
SELECT @QCBillDate = StartDate FROM SS_MonthProc WHERE Period = 1

IF @BeginDate <> ''
	SET @IndexSql += ' AND BillDate >= @BeginDate'
IF @EndDate <> ''
	SET @IndexSql += ' AND BillDate <= @EndDate'

SET @IndexSql += ' AND BillCode like ''%''+@BillCode+''%''  AND Summary Like ''%''+@Summary+''%'' AND Description Like ''%''+@Description+''%'' '

IF @DeptID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT) 
				 INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d 
				 INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID 
				 INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''
				 WHERE d2.SonNum = 0
				 '
	SET @TableSql+=' INNER JOIN @DType D ON I.DeptID=D.DeptID '	 
END
	
IF @ElyID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT) 
				 INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','') 
				 '
	SET @TableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '	 
END

IF @BillTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BillType Table(BillTypeID INT) 
				 INSERT  INTO @BillType SELECT typeid AS BillTypeID  FROM dbo.UF_OT_Split_Int(@BillTypeID,'','') 
		'
	SET @BillTypeSql += ' INNER JOIN @BillType bill ON bd.BillTypeID=bill.BillTypeID '	
END

IF @PayRecType = 401 --付款
BEGIN
	--采购单
	SET @BuyBill = '
	SELECT	BillNo,	BillCode,	BillDate,	101 AS BillTypeID,	Summary,	Description, 
			Total,	(Total - PaidTotal - PayRecTotal - Privilege) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_PchBill I '+ @TableSql +'
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--采购退货单
	SET @BuyBackBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	102 AS BillTypeID,	Summary,	Description, 
			Total*(-1) AS Total, (Total - PaidTotal -PayRecTotal-Privilege)*(-1) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_PchRetBill I '+ @TableSql +'
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--一般费用单	
	SET @FeeRecBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	BillTypeID,		Summary,	Description, 
			Total,		(Total - PaidTotal - PayRecTotal) AS BalanceTotal,	0 AS Tag,	4 AS GroupID   
		FROM MF_FeeRecBill I ' + @TableSql + '
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND BillTypeID = 404 '+ @IndexSql
	--应付增加/减少	
	SET @ARAPBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	BillTypeID,		Summary,	Description, 
			   CASE BillTypeID WHEN 503 THEN Total ELSE Total*(-1) END AS Total, 
			   CASE BillTypeID WHEN 503 THEN (Total - PaidTotal) ELSE (Total - PaidTotal)*(-1) END AS BalanceTotal,
			   0 AS Tag,	5 AS GroupID  
		FROM MF_ARAPBill I ' + @TableSql + '
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND BillTypeID IN (503, 504) ' + @IndexSql
	--期初应付	
	SET @QCBill = '
	UNION ALL
	SELECT	ARAPID AS BillNo,	''本年期初应付'' AS BillCode,	@QCBillDate AS BillDate,	999 AS BillTypeID, 
			   ''【' +@BtypeName+'】本年期初应付'' AS Summary,	'''' AS Description,	QcAP AS Total, 
			   QcAP - APPaidTotal AS  BalanceTotal ,	0 AS Tag,	1 AS GroupID 
		FROM BD_ARAP I 
		WHERE BtypeID = @BtypeID AND QcAP <>0 '
	--销售单运费	
	SET @SaleFeeBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	201 AS BillTypeID,		''【物流运费】''+Summary,	Description, 
			   Freight AS Total,	(Freight - FreightPaidTotal - FreightTotal) AS BalanceTotal,
			   1 AS Tag,	6 AS GroupID  
		FROM PD_SellBill I' + @TableSql +'
		WHERE LogistBTypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND IsOS = 0 AND Freight <> 0'+@IndexSql
	--采购单运费
	SET @BuyFeeBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	101 AS BillTypeID,		''【物流运费】''+Summary,	Description, 
			   Freight AS Total,	(Freight - FreightPaidTotal - FreightTotal) AS BalanceTotal,
			   1 AS Tag,	6 AS GroupID  
		FROM PD_PchBill I' + @TableSql +'
		WHERE LogistBTypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND Freight <> 0'+@IndexSql
END ELSE
IF @PayRecType = 402 --收款
BEGIN
	--销售单
	SET @SaleBill = '
	SELECT	BillNo,	BillCode,	BillDate,	201 AS BillTypeID,	Summary,	Description, 
			Total,	(Total - PaidTotal - PayRecTotal - Privilege) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_SellBill I '+ @TableSql +'
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--销售退货单
	SET @BuyBackBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	202 AS BillTypeID,	Summary,	Description, 
			Total*(-1) AS Total, (Total - PaidTotal -PayRecTotal-Privilege)*(-1) AS BalanceTotal,	0 AS Tag,	2 AS GroupID  
		FROM PD_SellRetBill I '+ @TableSql +'
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 '+ @IndexSql
	--其它收入单
	SET @FeeRecBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	BillTypeID,		Summary,	Description, 
			Total,		(Total - PaidTotal - PayRecTotal) AS BalanceTotal,	0 AS Tag,	4 AS GroupID   
		FROM MF_FeeRecBill I ' + @TableSql + '
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND BillTypeID = 405 '+ @IndexSql
	--应收增加/减少
	SET @ARAPBill = '
	UNION ALL
	SELECT	BillNo,		BillCode,	BillDate,	BillTypeID,		Summary,	Description, 
			   CASE BillTypeID WHEN 501 THEN Total ELSE Total*(-1) END AS Total, 
			   CASE BillTypeID WHEN 501 THEN (Total - PaidTotal) ELSE (Total - PaidTotal)*(-1) END AS BalanceTotal,
			   0 AS Tag,	5 AS GroupID  
		FROM MF_ARAPBill I ' + @TableSql + '
		WHERE BtypeID = @BtypeID AND IsDraft = 0 AND Red = 0 AND BillTypeID IN (501, 502) ' + @IndexSql
	SET @QcBill = '
	UNION ALL
	SELECT	ARAPID AS BillNo,	''本年期初应收'' AS BillCode,	@QCBillDate AS BillDate,	998 AS BillTypeID, 
			   ''【' +@BtypeName+'】本年期初应付'' AS Summary,	'''' AS Description,	QcAR AS Total, 
			   QcAR - ARPaidTotal AS  BalanceTotal ,	0 AS Tag,	1 AS GroupID 
		FROM BD_ARAP I 
		WHERE BtypeID = @BtypeID AND QcAR <>0 '
END

SET @Sql = @CreateTableSql + '
SELECT		BillNo,		BD.BillCode,	BillDate,	BD.BillTypeID,	BillName,	Summary,	Description,
			Total,		BalanceTotal,	Tag,		GroupID 
FROM (
	'+ @BuyBill + @SaleBill + @BuyBackBill + @SaleBackBill + @FeeRecBill + @ARAPBill + @QcBill + @SaleFeeBill + @BuyFeeBill + '
	) BD '+ @BillTypeSql+'
INNER JOIN PD_BillType BT ON BD.BillTypeID = BT.BillTypeID
WHERE BalanceTotal <> 0 ORDER BY BillDate, GroupID
'

EXEC sp_executesql @sql,N'@BtypeID INT, @DeptID VARCHAR(MAX), @ElyID VARCHAR(MAX), @BillTypeID VARCHAR(MAX),@BillCode VARCHAR(50), 
@Summary VARCHAR(256),@Description VARCHAR(100),@BeginDate VARCHAR(10),@EndDate VARCHAR(10), @QCBillDate DATE', 
@BtypeID, @DeptID, @ElyID, @BillTypeID, @BillCode, @Summary, @Description, @BeginDate, @EndDate, @QCBillDate


GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询采购明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryOrdBuyDetails]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@AuQtyFlag INT= 0,
	@DID Int = 0,
	@OperatorID INT = 1
)

AS
SET NOCOUNT ON

Declare @Sql varchar(max)='',@SqlUnit1 varchar(500)='',@SqlUnit2 varchar(500)='',@SqlUnit3 varchar(500)='',@SqlWhs varchar(500)='',@SqlDept varchar(500)=''
		,@SqlEly varchar(500)='',@SqlCreator varchar(500)='',@SqlPost varchar(500)='',@SqlBSUnit varchar(500)='',@SqlUnit varchar(500)='',@SqlGoods varchar(500)=''
		,@SqlBtype varchar(500)='',@SqlPpt1 varchar(500)='',@SqlPpt2 varchar(500)=''

Select @Sql += ' select bill.BillNo,Bill.BillDate,101 as BillTypeID,''采购入库单'' as BillName,BillCode,BTypeID,DeptID,ElyID,detail.WhsID,Creator as CreatorID,CreateTime,PosElyID,PosTime,Summary,Description,
		detail.GoodsID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,detail.Discount,Case When Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty,Case When Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,detail.Price,Case When Red = 2 then detail.Total * -1 Else detail.Total End as Total,detail.DiscPrice,Case when Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal,detail.Remark
		,detail.Freight,detail.InPrice,Case When Bill.Red = 2 Then detail.InTotal*-1 Else detail.InTotal End as  InTotal,detail.BatchNumber,detail.ProductDate,detail.EndDate ,detail.goodsno as BtypeGoodsNo
		from PD_PchDetail detail  Left Join PD_PchBill bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red=0 And IsDraft = 0
		Union All
		select bill.BillNo,Bill.BillDate,101 as BillTypeID,''采购入库单'' as BillName,BillCode,BTypeID,DeptID,ElyID,detail.WhsID,Creator as CreatorID,CreateTime,PosElyID,PosTime,Summary,Description,
		detail.GoodsID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,detail.Discount,Case When Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty,Case When Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,detail.Price,Case When Red = 2 then detail.Total * -1 Else detail.Total End as Total,detail.DiscPrice,Case when Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal,detail.Remark  
		,detail.Freight,detail.InPrice,Case When Bill.Red = 2 Then detail.InTotal*-1 Else detail.InTotal End as  InTotal,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.goodsno as BtypeGoodsNo  
		from PD_PchDetail_His detail Left Join PD_PchBill_His bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red=0 And IsDraft = 0
		'
SELECT @sql= '
;WITH Bill AS 
('	+@sql+'
),
 PagingData AS
 (
	select bill.BillNo,Bill.BillDate,BillTypeID,BillName,BillCode,bill.BTypeID,DeptID,bill.ElyID,WhsID,CreatorID,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,PosElyID,CONVERT(varchar(100), PosTime, 120) AS PosTime,Summary,Description,
		bill.GoodsID,bill.Ppt1ID,bill.Ppt2ID,BSUnitID,UnitID,bill.Convfactor,Discount,bill.Qty,bill.BSQty,Price,Total,DiscPrice,DiscTotal,bill.Remark,G.GoodsNo,G.GoodsName,Freight,InPrice,InTotal,BatchNumber,ProductDate,EndDate  ,BtypeGoodsNo
		from Bill bill LEFT JOIN BD_GOODS G on bill.GoodsID = G.GoodsID 
 )'
 
IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 2 --全部仓库权限
	SET @SqlWhs = N'SELECT WhsID AS WID ,WhsNO,WhsName from BD_Whs '
ELSE
	SET @SqlWhs = N'SELECT WhsID AS WID ,CASE LimitID WHEN 0 THEN ''***'' ELSE WhsNO END AS WhsNO, CASE LimitID WHEN 0 THEN ''***'' ELSE WhsName END AS  WhsName FROM 
						(SELECT BW.WhsID, WhsNo, WhsName, ISNULL(KL.WhsID, 0) AS LimitID FROM BD_Whs BW LEFT JOIN DBO.UF_BD_KtypeLimit(@OperatorID) KL ON BW.WhsID = KL.WhsID) WhsLimit'
	
	
SET @SqlDept = N'SELECT DeptID AS DID,DeptCode,DeptName from BD_Dept'
SET @SqlEly = N'SELECT ElyID AS EID,ElyCode,ElyName from BD_Employee'
SET @SqlCreator = N'SELECT ElyID AS CEID,ElyName as Creator from BD_Employee'
SET @SqlPost = N'SELECT ElyID AS PEID,ElyName as PostName from BD_Employee'
SET @SqlBSUnit = N'SELECT UnitID as BSUNID,GoodsID as BSGDID,Unit as BSUnit from BD_Goods_Price '
-- 增加列条码
SET @SqlUnit = N'SELECT UnitID as UNID,GoodsID as GDID,Unit,BarCode from BD_Goods_Price '
SET @SqlBtype = N'SELECT BtypeID as BID,BTypeCode,BTypeName from BD_Btype '
SET @SqlPpt1 = N'SELECT Ppt1ID as P1ID,Value as Ppt1Name from BD_Goods_Ppt1 GP1 '
SET @SqlPpt2 = N'SELECT Ppt2ID as P2ID,Value as Ppt2Name from BD_Goods_Ppt2 GP2 '
-- 增加列型号、简名、品牌、规格
SET @SqlGoods = N'SELECT GoodsID as G1ID,Spec,Model,GoodsAbbName,Brand FROM BD_Goods '
 if(@AuQtyFlag <> 0)
begin
	Set @SqlUnit1 = N'SELECT Unit as Unit1,Convfactor as Convfactor1,GoodsID as GDID1 From BD_Goods_Price where UnitID = 1'
	Set @SqlUnit2 = N'SELECT Unit as Unit2,ISNULL(Convfactor,1) as Convfactor2,GoodsID as GDID2 From BD_Goods_Price where UnitID = 2'
	Set @SqlUnit3 = N'SELECT Unit as Unit3,ISNULL(Convfactor,1) as Convfactor3,GoodsID as GDID3 From BD_Goods_Price where UnitID = 3'
end
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DID', 'Int', @DID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID', 'Int', @OperatorID)
if(@AuQtyFlag <> 0)
begin
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice1', 'Data.GoodsID = _DATA_GPrice1.GDID1 ', @SqlUnit1)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice2', 'Data.GoodsID = _DATA_GPrice2.GDID2 ', @SqlUnit2)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice3', 'Data.GoodsID = _DATA_GPrice3.GDID3 ', @SqlUnit3)
end
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Whs', 'Data.WhsID = _DATA_Whs.WID', @SqlWhs)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Dept', 'Data.DeptID = _DATA_Dept.DID', @SqlDept)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ely', 'Data.ElyID = _DATA_Ely.EID', @SqlEly)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_CEly', 'Data.CreatorID = _DATA_CEly.CEID', @SqlCreator)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_PEly', 'Data.PosElyID = _DATA_PEly.PEID', @SqlPost)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice', 'Data.UnitID = _DATA_GPrice.UNID and Data.GoodsID = _DATA_GPrice.GDID', @SqlUnit)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_BSGPrice', 'Data.BSUnitID = _DATA_BSGPrice.BSUNID and Data.GoodsID = _DATA_BSGPrice.BSGDID', @SqlBSUnit)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ppt1', 'Data.Ppt1ID = _DATA_Ppt1.P1ID', @SqlPpt1)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ppt2', 'Data.Ppt2ID = _DATA_Ppt2.P2ID', @SqlPpt2)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Btype', 'Data.BtypeID = _DATA_Btype.BID', @SqlBtype)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Goods', 'Data.GoodsID = _DATA_Goods.G1ID', @SqlGoods)
EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'PosTime,GoodsNo','',BillNo,1,1

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryOrderDetailList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryOrderDetailList]
GO
/****** Object:  StoredProcedure [UP_PD_QueryOrderDetailList]    Script Date: 08/04/2014 15:49:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/8/4
-- Description:	 (订单\采购销售单)选择明细
-- =============================================
CREATE PROCEDURE UP_PD_QueryOrderDetailList(
     @BillNo INT = 0, --单据ID
     @BillType INT = 0, --单据类型（采购入库单:101 销售出库单:201 采购退货单:102 销售退货单:202）
	 @GoodsNo VARCHAR(50) = '', --商品编号
	 @GoodsName VARCHAR(100) = ''  --商品名称
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @OrdDetailTable NVARCHAR(20), @OrdBillType INT,@feildsql VARCHAR(max)='',@joinsql VARCHAR(max)='',
	        @DIDAlias NVARCHAR(100) = 'OrdDID',
	        @ClauseWhere  NVARCHAR(100) = ''
	SET @joinsql=' LEFT JOIN BD_Goods_CustomVal C ON C.BaseID=detail.GoodsID '
	SELECT @joinsql+= CASE WHEN SourceType=1 THEN ' ' 
		WHEN SourceType=2 AND SOURCE=1 THEN ' LEFT JOIN BD_Goods G'+CAST(CustItemID AS VARCHAR)+' ON G'+CAST(CustItemID AS VARCHAR)+'.GoodsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=2 THEN ' LEFT JOIN BD_BType B'+CAST(CustItemID AS VARCHAR)+' ON B'+CAST(CustItemID AS VARCHAR)+'.BTypeID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=2 AND SOURCE=3 THEN ' LEFT JOIN BD_Whs W'+CAST(CustItemID AS VARCHAR)+' ON W'+CAST(CustItemID AS VARCHAR)+'.WhsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=4 THEN ' LEFT JOIN BD_Dept D'+CAST(CustItemID AS VARCHAR)+' ON D'+CAST(CustItemID AS VARCHAR)+'.DeptID=C.CustVal'+CAST(CustItemID AS VARCHAR)  
		WHEN SourceType=2 AND SOURCE=5 THEN ' LEFT JOIN BD_Employee E'+CAST(CustItemID AS VARCHAR)+' ON E'+CAST(CustItemID AS VARCHAR)+'.ElyID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=3 THEN ' LEFT JOIN BD_Custom C'+CAST(CustItemID AS VARCHAR) +' ON C'+CAST(CustItemID AS VARCHAR) +'.CustID=C.CustVal'+CAST(CustItemID AS VARCHAR)     
		END,
		@feildsql += CASE WHEN SourceType=1 THEN ' ,C.CustVal'+CAST(CustItemID AS VARCHAR)     
		WHEN SourceType=2 AND SOURCE=1 THEN ' ,G'+CAST(CustItemID AS VARCHAR)+'.GoodsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=2 THEN ' ,B'+CAST(CustItemID AS VARCHAR)+'.BTypeName AS CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=2 AND SOURCE=3 THEN ' ,W'+CAST(CustItemID AS VARCHAR)+'.WhsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=4 THEN ' ,D'+CAST(CustItemID AS VARCHAR)+'.DeptName AS CustVal'+CAST(CustItemID AS VARCHAR)  
		WHEN SourceType=2 AND SOURCE=5 THEN ' ,E'+CAST(CustItemID AS VARCHAR)+'.ElyName AS CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=3 THEN ',C'+CAST(CustItemID AS VARCHAR) +'.CustName AS CustVal'+CAST(CustItemID AS VARCHAR)     
		END
	FROM dbo.BD_Goods_CustomItem

	IF @BillType = 101
	    SET @OrdBillType = 100;
	ELSE IF @BillType = 201
	    SET @OrdBillType = 200;
	ELSE IF @BillType = 102
	    SET @OrdBillType = 101;
	ELSE IF @BillType = 202
	    SET @OrdBillType = 201;
	IF @BillType = 102 OR @BillType = 202
	BEGIN
	    SET @feildsql += ' ,detail.BatchNumber, detail.ProductDate, detail.EndDate, detail.CostPrice AS GoodsCostPrice '
		IF @BillType = 102
		BEGIN
			SET @DIDAlias = 'PchDID'
			SET @feildsql += ' ,CAST(1 AS BIT) AS IsSelectBatch '
		END
		ELSE
		BEGIN
			SET @DIDAlias = 'SellDID'
			SET @feildsql += ' ,detail.IsSelectBatch AS IsSelectBatch '
		END
	END
	ELSE
	BEGIN
	    SET @ClauseWhere = ' AND detaiL.StopTag = 0 '
	    SET @feildsql += ' ,detail.Stt, detail.StopTag '
	END
	SELECT @OrdDetailTable = BillDetail FROM PD_BillType WHERE BillTypeID = @OrdBillType
	   
	IF @OrdDetailTable IS NOT NULL
	    BEGIN
			SET @Sql = 'SELECT detail.DID AS ' + @DIDAlias + ', detail.BillNo, detail.BarCode, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, 
							   detail.WhsID, detail.WhsPtID, detail.UnitID, detail.Convfactor, detail.Price, detail.DiscPrice, 
							   detail.TaxPrice, detail.Qty, detail.BSQty, detail.Total, detail.DiscTotal, detail.TaxTotal, 
							   detail.Discount, detail.TaxRate, detail.Tax, detail.ComQty, whspt.WhsPtName,
							   CAST(detail.Gift AS BIT) AS Gift, detail.Remark, goods.GoodsNo, goods.GoodsName, 
							   goods.Spec, goods.Model, price.Unit, ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name,
							   price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1, price1.Convfactor AS Convfactor1,
							   price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, price2.Convfactor AS Convfactor2,
							   price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3, price3.Convfactor AS Convfactor3,
							   goods.IsSerial, goods.CostMethod, goods.DateType, goods.ValidDays, goods.NearbyDays,goods.Brand,goods.KG '
							   +@feildsql+'
                         FROM ' + @OrdDetailTable + ' detail
                         LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
                         LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID AND price.UnitID = detail.UnitID 
                         LEFT JOIN BD_Goods_Price price1 ON price1.GoodsID = detail.GoodsID AND price1.UnitID = 1
                         LEFT JOIN BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID AND price2.UnitID = 2
                         LEFT JOIN BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID AND price3.UnitID = 3
                         LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
                         LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
                         LEFT JOIN BD_Whs_Position whspt ON whspt.WhsPtID = detail.WhsPtID'
                         +@joinsql+' 
                         WHERE detail.BillNo = @BillNo AND detaiL.BSQty > detaiL.ComQty ' + @ClauseWhere --完成数量(基本单位), 引用数量(基本数量)
			IF @GoodsNo <> ''
				SET @Sql += 'AND goods.GoodsNo LIKE ''%' + @GoodsNo + '%'' '  
			IF @GoodsName <> ''
				SET @Sql += 'AND goods.GoodsName LIKE ''%' + @GoodsName + '%'' '
			SET @Sql += 'ORDER BY detail.DID'
		    --PRINT @Sql
	        EXEC sp_executesql @Sql, N'@BillNo INT, @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100)', @BillNo, @GoodsNo, @GoodsName
        END                  
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryOrderList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryOrderList]
GO
/****** Object:  StoredProcedure [UP_PD_QueryOrderList]    Script Date: 06/09/2014 14:16:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/6/9
-- Description:	 (订单\采购销售单)选择
-- Update: sunzhiyuan 增加查询采购订单的时候排除待审核 审核中 审核不通过的单据
-- Update: sunzhiyuan 增加查询采购订单的时候排除未生效的单据
-- =============================================
CREATE PROCEDURE UP_PD_QueryOrderList(
     @PageNo INT = 0,
     @PageSize INT = 0,
     @BillCode VARCHAR(50) = '', --单据编号
	 @BTypeID INT = 0,  --往来单位
	 @DeptID VARCHAR(1000) = '',  --部门
	 @ElyID VARCHAR(1000) = '',  --经手人
	 @WhsID VARCHAR(1000) = '',  --仓库
	 @GoodsNo VARCHAR(50)= '',  --商品编号
	 @GoodsName VARCHAR(100)= '',  --商品编号
     @Summary VARCHAR(50)= '',  --摘要
	 @Description VARCHAR(50)= '',  --说明
	 @BillStartDate DATETIME, --录单日期查询开始时间
	 @BillEndDate  DATETIME,  --录单日期查询结束时间
	 @OperatorID INT = 0, --操作员ID
     @BillType INT = 0, --单据类型（采购入库单:101 销售出库单:201 采购退货单:102 销售退货单:202）
	 @VipCardNO  VARCHAR(25)='',          --会员卡员
	 @VipCardNOMatch INT=1,               --会员卡员匹配方式 0:包含 1:等于
	 @VipCardTypeID VARCHAR(MAX)='',      --会员卡类型
	 @VipName  VARCHAR(50)='',            --会员名称
	 @VipNameMatch INT=0,                 --会员名称匹配方式 0:包含 1:等于
	 @CardHolder  VARCHAR(50)='',         --持卡人
	 @CardHolderMatch INT=0,              --持卡人匹配方式 0:包含 1:等于
	 @Tel  VARCHAR(20)='',                --电话
	 @TelMatch INT=0                      --电话匹配方式 0:包含 1:等于
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @OrdMainTable NVARCHAR(20), @OrdDetailTable NVARCHAR(20), @OrdBillType INT,
			-- 过滤掉未生效或未过账的单据
	        @SqlParam NVARCHAR(MAX) = ' WHERE a.IsDraft = 0 AND a.BillDate BETWEEN @BillStartDate AND @BillEndDate ',
	        @BtypeLimit INT = 0, 
	        @KtypeLimit INT = 0,
	        @MainCols NVARCHAR(500) = '',
	        @ClauseWhere  NVARCHAR(100) = '',
	        @VipSql NVARCHAR(1000) = '',
	        @VipJoinSql NVARCHAR(1000) = ''
    DECLARE @TVP_Dept AS [TVP_Type]
	IF @BillType = 101
	    SET @OrdBillType = 100;
	ELSE IF @BillType = 201
	    SET @OrdBillType = 200;
	ELSE IF @BillType = 102
	    SET @OrdBillType = 101;
	ELSE IF @BillType = 202
	    SET @OrdBillType = 201;
	IF @BillType = 101 OR @BillType = 201
	BEGIN
		SET @MainCols += ' ,a.DlvDate '
	    SET @SqlParam += ' AND a.StopTag = 0 '
	    SET @ClauseWhere += ' AND detaiL.StopTag = 0 '
	END
	ELSE
	BEGIN
	    SET @SqlParam += ' AND a.Red = 0 '
		IF @BillType = 202
		BEGIN
			SET @MainCols += ' ,a.VipCardID '
			IF (@VipCardNO <> '' OR @VipCardTypeID <> '' OR @VipName <> '' OR @CardHolder <> '' OR @Tel <> '')
			BEGIN			
				SET @MainCols += ' ,VipCard.VipCardTypeID, VipCard.VipCardNO, VipCard.VipName, VipCard.CardHolder, VipCard.Tel '
				SET @VipSql = ' , _DATA_Vip AS (SELECT VipCardTypeID AS VCTID, TypeName FROM dbo.VS_VipCardType) '
				SET @VipJoinSql = ' LEFT JOIN _DATA_Vip ON Data.VipCardTypeID =  _DATA_Vip.VCTID '
			END
			ELSE
			BEGIN
				SET @VipSql = ' ,_DATA_Vip AS (SELECT Card.VipCardID AS VCID, Card.VipCardTypeID, Card.VipCardNO, Card.VipName, Card.CardHolder, Card.Tel, CardType.TypeName 
				                                 FROM dbo.VS_VipCard Card INNER JOIN dbo.VS_VipCardType CardType
				                                 ON Card.VipCardTypeID = CardType.VipCardTypeID) '
				SET @VipJoinSql = ' LEFT JOIN _DATA_Vip ON Data.VipCardID =  _DATA_Vip.VCID '
			END
		END
	END
	SELECT @OrdMainTable = BillTable, @OrdDetailTable = BillDetail FROM PD_BillType WHERE BillTypeID = @OrdBillType
    IF @OrdMainTable IS NOT NULL
		BEGIN
			SET @Sql = ' ;WITH PagingData AS 
						 (SELECT a.BillNo, a.BillCode, a.BillDate, a.BTypeID, a.ElyID, a.DeptID,
								 a.WhsID, a.Summary, a.[Description]' + @MainCols + ' FROM ' + @OrdMainTable + ' a '
		                         
			--仓库权限   
			SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)       
			        
			IF @KtypeLimit = 1 --部份权限
			   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON a.WhsID = rWhs.WhsID '
		            
			IF @BillCode <> ''   
			   SET @SqlParam +=' AND a.BillCode LIKE ''%'' + @BillCode + ''%'''
			 
			--往来单位权限
			SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID)
			                    
			IF @BtypeLimit = 1  --部份权限
			   SET @Sql +=' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID = a.BTypeID ' 
			      
			IF @BTypeID <> ''
			   SET @SqlParam +=' AND a.BTypeID = @BTypeID'
		       
			IF @DeptID <> ''
			   BEGIN
				 SET @Sql +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = a.DeptID '
				 INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
				 SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
					 INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
					 WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
			   END
		              
			IF @ElyID <> ''
			   SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = a.ElyID'
		       
			IF @WhsID <> ''
			   SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = a.WhsID'
		       
			IF @GoodsNo <> '' OR @GoodsName <> ''
			   BEGIN
				 SET @SqlParam +=' AND EXISTS (SELECT detail.DID FROM ' + @OrdDetailTable + ' detail
								   INNER JOIN BD_Goods goods on goods.GoodsID = detail.GoodsID
								   WHERE detaiL.BillNo = a.BillNo AND detaiL.BSQty > detaiL.ComQty ' + @ClauseWhere  		             
				 IF @GoodsNo <> ''
				  SET @SqlParam +=' AND goods.GoodsNo  LIKE ''%''+@GoodsNo+''%'''  
				             
				 IF @GoodsName <> ''
				  SET @SqlParam +=' AND goods.GoodsName  LIKE ''%''+@GoodsName+''%''' 
		          
				  SET @SqlParam +=')'
			   END
			ELSE
			   SET @SqlParam +=' AND EXISTS (SELECT detail.DID FROM ' + @OrdDetailTable + ' detail 
							     WHERE detaiL.BillNo = a.BillNo AND detaiL.BSQty > detaiL.ComQty ' + @ClauseWhere +' )'  
		                  
			IF @Summary <> ''
			   SET @SqlParam +=' AND a.Summary LIKE ''%''+@Summary+''%'''
		                  
			IF @Description <> ''
			   SET @SqlParam +=' AND a.Description LIKE ''%''+@Description+''%'''
			   
			--销售退货单引用原单增加会员相关的查询条件
			IF @BillType = 202 AND (@VipCardNO <> '' OR @VipCardTypeID <> '' OR @VipName <> '' OR @CardHolder <> '' OR @Tel <> '')
			BEGIN
				SET @Sql+=' INNER JOIN dbo.VS_VipCard VipCard ON a.VipCardID = VipCard.VipCardID ' 
				IF @VipCardNO <> ''
					SET @SqlParam += ' AND VipCard.VipCardNO ' + CASE @VipCardNOMatch WHEN 0 THEN ' Like ''%''+@VipCardNO+''%''' ELSE ' = @VipCardNO ' END
				IF @VipCardTypeID <> ''
					SET @Sql+=' INNER JOIN dbo.UF_OT_Split_INT(@VipCardTypeID,'','') VCT ON VipCard.VipCardTypeID = VCT.typeid ' 
				IF @VipName <> ''
					SET @SqlParam += ' AND VipCard.VipName ' + CASE @VipNameMatch WHEN 0 THEN ' Like ''%''+@VipName+''%''' ELSE ' =@VipName ' END
				IF @CardHolder <> ''
					SET @SqlParam += ' AND VipCard.CardHolder ' + CASE @CardHolderMatch WHEN 0 THEN ' Like ''%''+@CardHolder+''%''' ELSE ' =@CardHolder ' END
				IF @Tel <> ''
					SET @SqlParam += ' AND VipCard.Tel ' + CASE @TelMatch WHEN 0 THEN ' Like ''%''+@Tel+''%''' ELSE ' =@Tel ' END
			END	
   
			SET @Sql= N'SET NOCOUNT ON;'
					 + @Sql + @SqlParam + ' )' +
					 N', _DATA_Btype AS (SELECT BTypeID AS BID, BTypeCode, BTypeName, ISNULL(PaidCircle, 0) AS PaidCircle from BD_Btype)
					   , _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName from BD_Employee)
					   , _DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName from BD_Whs)
					   , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName from BD_Dept) '
					   + @VipSql +
					   ' , DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
								  CROSS JOIN
								 (SELECT ROW_NUMBER() OVER(ORDER BY BillNo) AS ROWID,* FROM PagingData) B
								  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
					   SELECT * FROM DATA LEFT JOIN _DATA_Btype ON Data.BTypeID = _DATA_Btype.BID
										  LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID
										  LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID
										  LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID ' + @VipJoinSql + ' ORDER BY ROWID '
										  
			IF @BtypeLimit = 0 OR @KtypeLimit = 0
				SET @Sql = N' SELECT * FROM ' + @OrdMainTable + ' WHERE 1 <> 1'
				
			--print @sql

			EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillCode VARCHAR(50), @BTypeID INT, @DeptID VARCHAR(1000),
									   @ElyID VARCHAR(1000), @WhsID VARCHAR(1000), @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100),
									   @Summary VARCHAR(50), @Description VARCHAR(50), @BillStartDate DATETIME, @BillEndDate DATETIME,
									   @OperatorID INT, @TVP_Dept TVP_Type READONLY, @VipCardNO VARCHAR(25),
									   @VipCardTypeID VARCHAR(MAX), @VipName VARCHAR(50), @CardHolder VARCHAR(50),@Tel VARCHAR(20)', 
									   @PageNo, @PageSize, @BillCode, @BTypeID, @DeptID, @ElyID, @WhsID, @GoodsNo, @GoodsName,
									   @Summary, @Description, @BillStartDate, @BillEndDate, @OperatorID, @TVP_Dept, @VipCardNO, 
									   @VipCardTypeID, @VipName, @CardHolder, @Tel
		END		 
END
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询销售明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryOrdSaleDetails]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@AuQtyFlag INT= 0,
	@DID Int = 0,
	@OperatorID INT = 1
)

AS
SET NOCOUNT ON

Declare @Sql varchar(max)='',@SqlUnit1 varchar(500)='',@SqlUnit2 varchar(500)='',@SqlUnit3 varchar(500)='',@SqlWhs varchar(500)='',@SqlDept varchar(500)=''
		,@SqlEly varchar(500)='',@SqlCreator varchar(500)='',@SqlPost varchar(500)='',@SqlBSUnit varchar(500)='',@SqlUnit varchar(500)='',@SqlGoods varchar(500)=''
		,@SqlBtype varchar(500)='',@SqlPpt1 varchar(500)='',@SqlPpt2 varchar(500)=''

Select @Sql += ' select bill.BillNo,Bill.BillDate,201 as BillTypeID,''销售出库单'' as BillName,BillCode,bill.BTypeID,bill.DeptID,bill.ElyID,detail.WhsID,Creator as CreatorID,CreateTime,PosElyID,PosTime,Summary,Description,
		detail.GoodsID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,detail.Discount,Case When Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty,Case When Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,detail.Price,Case When Red = 2 then detail.Total * -1 Else detail.Total End as Total,detail.DiscPrice,Case when Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal,detail.Remark,detail.CostPrice,Case When Red = 2 then detail.GoodsCostTotal * -1 Else detail.GoodsCostTotal End as GoodsCostTotal,
		Case When Red = 2 then (detail.DiscTotal-detail.GoodsCostTotal)*-1 Else (detail.DiscTotal-detail.GoodsCostTotal) End as Profit,Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.goodsno as BtypeGoodsNo
		from PD_SellDetail detail  Left Join PD_SellBill bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red=0 And IsDraft = 0
		Union All
		select bill.BillNo,Bill.BillDate,201 as BillTypeID,''销售出库单'' as BillName,BillCode,bill.BTypeID,bill.DeptID,bill.ElyID,detail.WhsID,Creator as CreatorID,CreateTime,PosElyID,PosTime,Summary,Description,
		detail.GoodsID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,detail.Discount,Case When Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty,Case When Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,detail.Price,Case When Red = 2 then detail.Total * -1 Else detail.Total End as Total,detail.DiscPrice,Case when Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal,detail.Remark,detail.CostPrice,Case When Red = 2 then detail.GoodsCostTotal * -1 Else detail.GoodsCostTotal End as GoodsCostTotal,
		Case When Red = 2 then (detail.DiscTotal-detail.GoodsCostTotal)*-1 Else (detail.DiscTotal-detail.GoodsCostTotal) End as Profit,Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.goodsno as BtypeGoodsNo
		from PD_SellDetail_His detail Left Join PD_SellBill_His bill on detail.BillNo = bill.BillNo where detail.OrdDID = @DID And Red=0 And IsDraft = 0
		'
SELECT @sql= '
;WITH Bill AS 
('	+@sql+'
),
 PagingData AS
 (
	select bill.BillNo,Bill.BillDate,BillTypeID,BillName,BillCode,bill.BTypeID,DeptID,bill.ElyID,WhsID,CreatorID,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,PosElyID,CONVERT(varchar(100), PosTime, 120) AS PosTime,Summary,Description,
		bill.GoodsID,bill.Ppt1ID,bill.Ppt2ID,BSUnitID,UnitID,bill.Convfactor,Discount,bill.Qty,bill.BSQty,Price,Total,DiscPrice,DiscTotal,CostPrice,bill.Remark
		,bill.GoodsCostTotal,Profit,ProfitMargin,G.GoodsNo,G.GoodsName ,BatchNumber,ProductDate,EndDate ,BtypeGoodsNo
		from Bill bill LEFT JOIN BD_GOODS G on bill.GoodsID = G.GoodsID 
 )'

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 2 --全部仓库权限
	SET @SqlWhs = N'SELECT WhsID AS WID ,WhsNO,WhsName from BD_Whs '
ELSE
	SET @SqlWhs = N'SELECT WhsID AS WID ,CASE LimitID WHEN 0 THEN ''***'' ELSE WhsNO END AS WhsNO, CASE LimitID WHEN 0 THEN ''***'' ELSE WhsName END AS  WhsName FROM 
						(SELECT BW.WhsID, WhsNo, WhsName, ISNULL(KL.WhsID, 0) AS LimitID FROM BD_Whs BW LEFT JOIN DBO.UF_BD_KtypeLimit(@OperatorID) KL ON BW.WhsID = KL.WhsID) WhsLimit'
	
SET @SqlDept = N'SELECT DeptID AS DID,DeptCode,DeptName from BD_Dept'
SET @SqlEly = N'SELECT ElyID AS EID,ElyCode,ElyName from BD_Employee'
SET @SqlCreator = N'SELECT ElyID AS CEID,ElyName as Creator from BD_Employee'
SET @SqlPost = N'SELECT ElyID AS PEID,ElyName as PostName from BD_Employee'
SET @SqlBSUnit = N'SELECT UnitID as BSUNID,GoodsID as BSGDID,Unit as BSUnit from BD_Goods_Price '
-- 增加列条码
SET @SqlUnit = N'SELECT UnitID as UNID,GoodsID as GDID,Unit,BarCode from BD_Goods_Price '
SET @SqlBtype = N'SELECT BtypeID as BID,BTypeCode,BTypeName from BD_Btype '
SET @SqlPpt1 = N'SELECT Ppt1ID as P1ID,Value as Ppt1Name from BD_Goods_Ppt1 GP1 '
SET @SqlPpt2 = N'SELECT Ppt2ID as P2ID,Value as Ppt2Name from BD_Goods_Ppt2 GP2 '
-- 增加列型号、简名、品牌、规格
SET @SqlGoods = N'SELECT GoodsID as G1ID,Spec,Model,GoodsAbbName,Brand FROM BD_Goods '
 if(@AuQtyFlag <> 0)
begin
	Set @SqlUnit1 = N'SELECT Unit as Unit1,Convfactor as Convfactor1,GoodsID as GDID1 From BD_Goods_Price where UnitID = 1'
	Set @SqlUnit2 = N'SELECT Unit as Unit2,ISNULL(Convfactor,1) as Convfactor2,GoodsID as GDID2 From BD_Goods_Price where UnitID = 2'
	Set @SqlUnit3 = N'SELECT Unit as Unit3,ISNULL(Convfactor,1) as Convfactor3,GoodsID as GDID3 From BD_Goods_Price where UnitID = 3'
end
DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DID', 'Int', @DID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID', 'Int', @OperatorID)
if(@AuQtyFlag <> 0)
begin
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice1', 'Data.GoodsID = _DATA_GPrice1.GDID1 ', @SqlUnit1)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice2', 'Data.GoodsID = _DATA_GPrice2.GDID2 ', @SqlUnit2)
	INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice3', 'Data.GoodsID = _DATA_GPrice3.GDID3 ', @SqlUnit3)
end
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Whs', 'Data.WhsID = _DATA_Whs.WID', @SqlWhs)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Dept', 'Data.DeptID = _DATA_Dept.DID', @SqlDept)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ely', 'Data.ElyID = _DATA_Ely.EID', @SqlEly)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_CEly', 'Data.CreatorID = _DATA_CEly.CEID', @SqlCreator)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_PEly', 'Data.PosElyID = _DATA_PEly.PEID', @SqlPost)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_GPrice', 'Data.UnitID = _DATA_GPrice.UNID and Data.GoodsID = _DATA_GPrice.GDID', @SqlUnit)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_BSGPrice', 'Data.BSUnitID = _DATA_BSGPrice.BSUNID and Data.GoodsID = _DATA_BSGPrice.BSGDID', @SqlBSUnit)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ppt1', 'Data.Ppt1ID = _DATA_Ppt1.P1ID', @SqlPpt1)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Ppt2', 'Data.Ppt2ID = _DATA_Ppt2.P2ID', @SqlPpt2)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Btype', 'Data.BtypeID = _DATA_Btype.BID', @SqlBtype)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_Goods', 'Data.GoodsID = _DATA_Goods.G1ID', @SqlGoods)
--print @sql
EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'PosTime,GoodsNo','',BillNo--,1,1

GO



/****** Object:  StoredProcedure [UP_PD_QueryOtherOutBilllData]    Script Date: 06/25/2014 16:17:55 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryOtherOutBilllData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryOtherOutBilllData]
GO

/****** Object:  StoredProcedure [UP_PD_QueryOtherOutBilllData]    Script Date: 06/25/2014 16:17:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		liuke
-- Create date:  2014-06-17
-- Modify date:  2015-02-09
-- Description:	 查询其他出库单数据
-- =============================================
CREATE PROCEDURE [UP_PD_QueryOtherOutBilllData]
(
	@BillNo INT=0
) 
AS
BEGIN
	IF EXISTS (SELECT 1 FROM PD_InOutWhsBill b WHERE b.BillNo=@BillNo)
	BEGIN		--当前数据
		SELECT TOP 1 
			p.IsDraft,p.Red
			,p.BillNo,p.BillDate,p.BillCode
			,p.BTypeID,b.BTypeName
			,p.ElyID,e.ElyName
			,p.DeptID,d.DeptName
			,p.WhsID,w.WhsName
			,p.Summary,p.[Description]
			,p.Creator[CreatorID],e1.ElyName[CreatorName],e2.ElyName AS PosName
			,p.BillQty,p.Total,p.AuditStatus 
		FROM PD_InOutWhsBill p 
		LEFT JOIN BD_Btype b ON p.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON p.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON p.DeptID=d.DeptID 
		INNER JOIN BD_Whs w ON p.WhsID=w.WhsID 
		LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID 
		LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
		WHERE p.BillNo=@BillNo 
		
		SELECT  p.DID,p.GoodsID,g.GoodsNo,g.GoodsName
				,p.BarCode
				,g.Spec,g.Model
				,p.Ppt1ID,p1.Value[Ppt1Name]
				,p.Ppt2ID,p2.Value[Ppt2Name]
				,p.WhsID,p.WhsPtID,wp.WhsPtName
				,p.Qty,p.BSQty
				,p.UnitID,gp.Unit
				,p.Convfactor
				,p.CostPrice[GoodsCostPrice],p.CostPrice*p.Convfactor[Price],p.CostPrice,p.GoodsCostTotal,p.Remark
				,gp1.Convfactor[Convfactor1]
				,ISNULL(gp2.Convfactor,1)[Convfactor2]
				,ISNULL(gp3.Convfactor,1)[Convfactor3]
				--,case when gp3.Convfactor is null then 1 else gp3.Convfactor end [Convfactor3]
				,gp1.BarCode[BarCode1],gp2.BarCode[BarCode2],gp3.BarCode[BarCode3]
				,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3],
				g.IsSerial,
				p.BatchNumber,
				p.ProductDate,
				p.EndDate,p.InPutPrice,g.DateType,g.CostMethod,p.IsSelectBatch		 
		FROM PD_InOutWhsDetail p 
		INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID 
		LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
		LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID 
		INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID 
		INNER JOIN BD_Goods_Price gp ON p.GoodsID=gp.GoodsID AND p.UnitID=gp.UnitID 
		LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND 1=gp1.UnitID 
		LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND 2=gp2.UnitID 
		LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND 3=gp3.UnitID 
		WHERE p.BillNo=@BillNo 
		
		-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_InOutWhsSerial ps Inner Join PD_InOutWhsDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
	ELSE
	BEGIN
		SELECT TOP 1 
			p.IsDraft,p.Red
			,p.BillNo,p.BillDate,p.BillCode
			,p.BTypeID,b.BTypeName
			,p.ElyID,e.ElyName
			,p.DeptID,d.DeptName
			,p.WhsID,w.WhsName
			,p.Summary,p.[Description]
			,p.Creator[CreatorID],e1.ElyName[CreatorName],e2.ElyName AS PosName
			,p.BillQty,p.Total ,p.AuditStatus
		FROM PD_InOutWhsBill_His p 
		LEFT JOIN BD_Btype b ON p.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON p.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON p.DeptID=d.DeptID 
		INNER JOIN BD_Whs w ON p.WhsID=w.WhsID 
		LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID 
		LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
		WHERE p.BillNo=@BillNo 
		
		SELECT  p.DID,p.GoodsID,g.GoodsNo,g.GoodsName
				,p.BarCode
				,g.Spec,g.Model
				,p.Ppt1ID,p1.Value[Ppt1Name]
				,p.Ppt2ID,p2.Value[Ppt2Name]
				,p.WhsID,p.WhsPtID,wp.WhsPtName
				,p.Qty,p.BSQty
				,p.UnitID,gp.Unit
				,p.Convfactor
				,p.CostPrice[GoodsCostPrice],p.Price,p.CostPrice,p.GoodsCostTotal,p.Remark
				,gp1.Convfactor[Convfactor1]
				,ISNULL(gp2.Convfactor,1)[Convfactor2]
				,ISNULL(gp3.Convfactor,1)[Convfactor3]
				--,case when gp3.Convfactor is null then 1 else gp3.Convfactor end [Convfactor3]
				,gp1.BarCode[BarCode1],gp2.BarCode[BarCode2],gp3.BarCode[BarCode3]
				,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3],
				g.IsSerial,
				p.BatchNumber,
				p.ProductDate,
				p.EndDate,p.InPutPrice,g.DateType,g.CostMethod		 
		FROM PD_InOutWhsDetail_His p 
		INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID 
		LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
		LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID 
		INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID 
		INNER JOIN BD_Goods_Price gp ON p.GoodsID=gp.GoodsID AND p.UnitID=gp.UnitID 
		LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND 1=gp1.UnitID 
		LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND 2=gp2.UnitID 
		LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND 3=gp3.UnitID 
		WHERE p.BillNo=@BillNo 
		
			-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_InOutWhsSerial_His ps Inner Join PD_InOutWhsDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
END

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryPayRecBillData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryPayRecBillData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2014-06-17
	描述：查询收付款单数据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryPayRecBillData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS

DECLARE @TableIndex NVARCHAR(100) = '', @TableDetail NVARCHAR(100) = '', @TableList NVARCHAR(100) = ''
DECLARE @IndexSql NVARCHAR(MAX) = '', @DetailSql NVARCHAR(MAX) = '', @ListSql NVARCHAR(MAX) = '', @BuyFeeBill NVARCHAR(MAX)= ''
DECLARE @BuyBill NVARCHAR(MAX) = '', @BuyBackBill NVARCHAR(MAX) = '', @SaleBill NVARCHAR(MAX) = '', @SaleBackBill NVARCHAR(MAX) = ''
DECLARE @FeeRecBill NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = '', @QCBill NVARCHAR(MAX) = '', @SaleFeeBill NVARCHAR(MAX) = '' 
DECLARE @BtypeName VARCHAR(100)='', @QCBillDate DATE = '1900-01-01', @BillType INT, @IsDraft BIT = 0, @PaidTotal NVARCHAR(MAX) = ''

SELECT @QCBillDate = StartDate FROM SS_MonthProc WHERE Period = 1

IF EXISTS(SELECT 1 FROM MF_PayRecBill_His WHERE BillNo = @BillNo)
BEGIN
	SET @TableIndex = ' MF_PayRecBill_His '
	SET @TableDetail = ' MF_PayRecDetail_His '
	SET @TableList = ' MF_PayRecList_His '
	SELECT @BillType = BillTypeID FROM MF_PayRecBill_His WHERE BillNo = @BillNo
	SELECT @BtypeName = B.BTypeName FROM MF_PayRecBill_His PR 
	INNER JOIN  BD_Btype B ON PR.BTypeID = B.BTypeID 
	WHERE PR.BillNo = @BillNo 
END ELSE
BEGIN
	SET @TableIndex = ' MF_PayRecBill '
	SET @TableDetail = ' MF_PayRecDetail '
	SET @TableList = ' MF_PayRecList '
	SELECT @BillType = BillTypeID, @IsDraft = IsDraft FROM MF_PayRecBill WHERE BillNo = @BillNo
	SELECT @BtypeName = B.BTypeName FROM MF_PayRecBill PR 
	INNER JOIN  BD_Btype B ON PR.BTypeID = B.BTypeID 
	WHERE PR.BillNo = @BillNo 
END

IF @IsDraft = 0 SET @PaidTotal = ' + P.PaidTotal '

--单据索引
SET @IndexSql = '
SELECT	  TOP 1
		  BillCode ,
		  BillDate ,
		  BillNo,
		  p.BTypeID ,
		  b.BTypeName,
		  p.DeptID ,
		  d.DeptName,
		  p.ElyID ,
		  e.ElyName,
		  BPTotal ,
		  Privilege ,
		  Total ,
		  Summary ,
		  [Description] ,
		  Red ,
		  StlTag ,
		  IsDraft,
		  p.Creator AS CreatorID,
		  e1.ElyName AS CreatorName,
		  e2.ElyName AS PosName,
		  p.AuditStatus
FROM '+ @TableIndex +' p
INNER JOIN BD_Btype b ON p.BtypeID = b.BTypeID
INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
LEFT  JOIN BD_Employee e1 ON p.Creator=e1.ElyID
LEFT  JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
INNER JOIN BD_Dept d ON p.DeptId = d.DeptId
WHERE BillNo= @BillNo '

SET @DetailSql = '
SELECT  BillNo, 
		p.FinanceID, 
		f.FinanceNO,
		f.FinanceName,
		Total, 
		p.Remark	
FROM '+ @TableDetail +' p
INNER JOIN BD_Finance f ON p.FinanceID = f.FinanceID
WHERE BillNo=@BillNo
'

IF @BillType = 401
BEGIN
	--采购单
	SET @BuyBill = '
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_PchBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 0
	UNION ALL 
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_PchBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 0'
	--采购退货单
	SET @BuyBackBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,
				B.Summary,		B.Description,	B.Total*(-1) AS Total,			(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege ' + @PaidTotal + ' )*(-1)  AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_PchRetBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 102
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,
				B.Summary,		B.Description,	B.Total*(-1) AS Total,			(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege ' + @PaidTotal + ')*(-1)  AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_PchRetBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 102'
	--一般费用单
	SET @FeeRecBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_FeeRecBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 404
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_FeeRecBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 404'
	--应付增加、减少
	SET @ARAPBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 503 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		B.Description,	
				CASE P.BillTypeID WHEN 503 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 503 THEN (B.Total - B.PaidTotal ' + @PaidTotal + ') ELSE (B.Total - B.PaidTotal ' + @PaidTotal + ')*(-1) END AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_ARAPBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (503, 504)
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 503 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		B.Description,	
				CASE P.BillTypeID WHEN 503 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 503 THEN (B.Total - B.PaidTotal ' + @PaidTotal + ') ELSE (B.Total - B.PaidTotal ' + @PaidTotal + ')*(-1) END AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_ARAPBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (503, 504)'
	--销售单物流运费
	SET @SaleFeeBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		''【物流运费】''+B.Summary,
				B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_SellBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND P.Tag = 1
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		''【物流运费】''+B.Summary,
				B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_SellBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND P.Tag = 1'
	
	--采购单物流运费
	SET @BuyFeeBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		''【物流运费】''+B.Summary,
				B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_PchBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 1
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		''【物流运费】''+B.Summary,
				B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_PchBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 1'
	
	--期初应付
	SET @QCBill = '
	UNION ALL
	SELECT		P.BillTypeID,  P.BillNo ,		P.PaidTotal,	P.Tag,			1 AS GroupID,		''本年期初应付'' AS BillCode,	@QCBillDate AS BillDate,
				''【' +@BtypeName+'】本年期初应付'' AS Summary,		'''' AS Description,	QcAP AS Total,	(QcAP - APPaidTotal ' + @PaidTotal + ') AS  BalanceTotal 
	FROM '+@TableList+' P INNER JOIN BD_ARAP B ON P.BillNo = B.ARAPID
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 999'
END ELSE
IF @BillType = 402
BEGIN
	--销售出库单
	SET @SaleBill = '
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal - B.Privilege ' + @PaidTotal + ')  BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_SellBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND P.Tag = 0
	UNION ALL 
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_SellBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND P.Tag = 0'
	--销售退货单
	SET @SaleBackBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total*(-1) AS Total,			(Total - b.PaidTotal - b.PayRecTotal - b.Privilege ' + @PaidTotal + ')*(-1)  AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_SellRetBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 202
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total*(-1) AS Total,			(Total - b.PaidTotal - b.PayRecTotal - b.Privilege ' + @PaidTotal + ')*(-1)  AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN PD_SellRetBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 202'
	--其他收入单
	SET @FeeRecBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_FeeRecBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 405
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		
				B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal ' + @PaidTotal + ') AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_FeeRecBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 405'
	--应收增加、减少
	SET @ARAPBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 501 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		B.Description,	
				CASE P.BillTypeID WHEN 501 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 501 THEN (Total - B.PaidTotal ' + @PaidTotal + ') ELSE (Total - B.PaidTotal ' + @PaidTotal + ')*(-1) END AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_ARAPBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (501, 502)
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 501 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		B.Summary,		B.Description,	
				CASE P.BillTypeID WHEN 501 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 502 THEN (Total - B.PaidTotal ' + @PaidTotal + ') ELSE (Total - B.PaidTotal ' + @PaidTotal + ')*(-1) END AS BalanceTotal
	FROM '+@TableList+' P INNER JOIN MF_ARAPBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (501, 502)'
	--期初应收
	SET @QCBill = '
	UNION ALL
	SELECT		P.BillTypeID,  P.BillNo ,		P.PaidTotal,	P.Tag,			1 AS GroupID,		''本年期初应收'' AS BillCode,	@QCBillDate AS BillDate,
			   ''【' +@BtypeName+'】本年期初应付'' AS Summary,	'''' AS Description,	QcAR AS Total,	(QcAR - ARPaidTotal' + @PaidTotal + ') AS  BalanceTotal 
	FROM '+@TableList+' P INNER JOIN BD_ARAP B ON P.BillNo = B.ARAPID
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 998'
END

SET @ListSql += '
SELECT	BD.BillTypeID,		BillNo,			PaidTotal,		Tag,	GroupID,	BD.BillCode,	BillDate,
		Summary,			Description,	Total,			BalanceTotal,		BT.BillName	
FROM ( ' + @BuyBill + @SaleBill + @BuyBackBill + @SaleBackBill + @FeeRecBill + @ARAPBill + @SaleFeeBill + @BuyFeeBill + @QCBill  +'
	) BD INNER JOIN PD_BillType BT ON BD.BillTypeID = BT.BillTypeID
	ORDER BY BillDate, GroupID
'
--print @listsql
exec sp_executesql @IndexSql , N'@BillNo INT', @BillNo
exec sp_executesql @DetailSql , N'@BillNo INT', @BillNo
exec sp_executesql @ListSql, N'@BillNo INT, @QCBillDate DATE', @BillNo, @QCBillDate
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryPayRecData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QueryPayRecData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2014-09-05
	描述：查询收付款单结算数据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryPayRecData]
(
	@BillNo INT=0, --收付款单号
	@PayRecType INT --收付类型
) 
AS
DECLARE @Sql NVARCHAR(MAX) = ''
DECLARE @BuyBill NVARCHAR(MAX) = '', @BuyBackBill NVARCHAR(MAX) = '', @SaleBill NVARCHAR(MAX) = '', @SaleBackBill NVARCHAR(MAX) = ''
DECLARE @FeeRecBill NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = '', @QCBill NVARCHAR(MAX) = '', @SaleFeeBill NVARCHAR(MAX) = '' 
DECLARE @BtypeName VARCHAR(100), @QCBillDate DATE = '1900-01-01', @BuyFeeBill NVARCHAR(MAX) = ''

SELECT @BtypeName = B.BTypeName FROM MF_PayRecBill PR 
INNER JOIN  BD_Btype B ON PR.BTypeID = B.BTypeID 
WHERE PR.BillNo = @BillNo 

SELECT @QCBillDate = StartDate FROM SS_MonthProc WHERE Period = 1

IF @PayRecType = 401 --付款
BEGIN
	--采购单
	SET @BuyBill = '
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,		
				B.Summary,		B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_PchBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 0
	UNION ALL 
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_PchBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 0
	'
	--采购退货单
	SET @BuyBackBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				B.Summary,		B.Description,	B.Total*(-1) AS Total,			(Total - b.PaidTotal - b.PayRecTotal - b.Privilege + P.PaidTotal )*(-1)  AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_PchRetBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 102
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	B.Total*(-1) AS Total,			(Total - b.PaidTotal - b.PayRecTotal - b.Privilege + P.PaidTotal)*(-1)  AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_PchRetBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 102
	'
	--一般费用单
	SET @FeeRecBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				B.Summary,		B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_FeeRecBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 404
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_FeeRecBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 404
	'
	--应付增加、减少
	SET @ARAPBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 503 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				B.Summary,		B.Description,	CASE P.BillTypeID WHEN 503 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 503 THEN (Total - B.PaidTotal + P.PaidTotal) ELSE (Total - B.PaidTotal + P.PaidTotal)*(-1) END AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_ARAPBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (503, 504)
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 503 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	CASE P.BillTypeID WHEN 503 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 503 THEN (Total - B.PaidTotal + P.PaidTotal) ELSE (Total - B.PaidTotal + P.PaidTotal)*(-1) END AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_ARAPBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (503, 504)
	'
	--销售单物流运费
	SET @SaleFeeBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				''【物流运费】''+B.Summary,		B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_SellBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND P.Tag = 1
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				''【物流运费】''+B.Summary,		B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_SellBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND P.Tag = 1
	'
	
	--采购单物流运费
	SET @BuyFeeBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				''【物流运费】''+B.Summary,		B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_PchBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 1
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			6 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				''【物流运费】''+B.Summary,		B.Description,	B.Freight AS Total,	(Freight - B.FreightPaidTotal - FreightTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_PchBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 101 AND P.Tag = 1
	'
	
	--期初应付
	SET @QCBill = '
	UNION ALL
	SELECT		P.BillTypeID,  P.BillNo ,		P.PaidTotal,	P.Tag,			1 AS GroupID,		''本年期初应付'' AS BillCode,	@QCBillDate AS BillDate,	0 AS IsHistory,	
			   ''【' +@BtypeName+'】本年期初应付'' AS Summary,	'''' AS Description,	QcAP AS Total,	QcAP - APPaidTotal+ P.PaidTotal AS  BalanceTotal 
	FROM MF_PayRecList P INNER JOIN BD_ARAP B ON P.BillNo = B.ARAPID
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 999
	'
END ELSE
IF @PayRecType = 402 --收款
BEGIN
	--销售出库单
	SET @SaleBill = '
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				B.Summary,		B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal - B.Privilege + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_SellBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND p.Tag = 0
	UNION ALL 
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			2 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	B.Total,		(B.Total - B.PaidTotal - B.PayRecTotal - B.Privilege + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_SellBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 201 AND p.Tag = 0
	'
	--销售退货单
	SET @SaleBackBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				B.Summary,		B.Description,	B.Total*(-1) AS Total,			(Total - b.PaidTotal - b.PayRecTotal - b.Privilege + P.PaidTotal)*(-1)  AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_SellRetBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 202
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal*(-1) AS PaidTotal,	P.Tag,			3 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	B.Total*(-1) AS Total,			(Total - b.PaidTotal - b.PayRecTotal - b.Privilege + P.PaidTotal)*(-1)  AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN PD_SellRetBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 202
	'
	--其他收入单
	SET @FeeRecBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				B.Summary,		B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_FeeRecBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 405
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		P.PaidTotal,	P.Tag,			5 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	B.Total,		(Total - B.PaidTotal - B.PayRecTotal + P.PaidTotal) AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_FeeRecBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 405
	'
	--应收增加、减少
	SET @ARAPBill = '
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 501 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		0 AS IsHistory,
				B.Summary,		B.Description,	CASE P.BillTypeID WHEN 501 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 501 THEN (Total - B.PaidTotal + P.PaidTotal) ELSE (Total - B.PaidTotal + P.PaidTotal)*(-1) END AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_ARAPBill B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (501, 502)
	UNION ALL
	SELECT		P.BillTypeID ,	P.BillNo ,		CASE P.BillTypeID WHEN 501 THEN P.PaidTotal ELSE P.PaidTotal * (-1) END AS PaidTotal,	
				P.Tag,			4 AS GroupID,		B.BillCode,		B.BillDate,		1 AS IsHistory,
				B.Summary,		B.Description,	CASE P.BillTypeID WHEN 501 THEN B.Total ELSE B.Total*(-1) END AS Total,
				CASE P.BillTypeID WHEN 501 THEN (Total - B.PaidTotal + P.PaidTotal) ELSE (Total - B.PaidTotal + P.PaidTotal)*(-1) END AS BalanceTotal
	FROM MF_PayRecList P INNER JOIN MF_ARAPBill_His B ON P.BillNo = B.BillNo
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID IN (501, 502)
	'
	--期初应收
	SET @QCBill = '
	UNION ALL
	SELECT		P.BillTypeID,  P.BillNo ,		P.PaidTotal,	P.Tag,			1 AS GroupID,		''本年期初应收'' AS BillCode,	@QCBillDate AS BillDate,	0 AS IsHistory,	
			   ''【' +@BtypeName+'】本年期初应付'' AS Summary,	'''' AS Description,	QcAR AS Total,	QcAR - ARPaidTotal+ P.PaidTotal AS  BalanceTotal 
	FROM MF_PayRecList P INNER JOIN BD_ARAP B ON P.BillNo = B.ARAPID
	WHERE P.PayRecBillNo = @BillNo AND P.BillTypeID = 998
	'
END

SET @Sql = '
SELECT		BD.BillTypeID,		BillNo,			PaidTotal,		Tag,	GroupID,	BD.BillCode,	BillDate,	IsHistory,
			Summary,			Description,	Total,			BalanceTotal,		BT.BillName	
FROM (
	'+ @BuyBill + @SaleBill + @BuyBackBill + @SaleBackBill + @FeeRecBill + @ARAPBill + @QcBill + @SaleFeeBill + @BuyFeeBill + '
	) BD INNER JOIN PD_BillType BT ON BD.BillTypeID = BT.BillTypeID
	ORDER BY BillDate, GroupID

'
exec sp_executesql @Sql , N'@BillNo INT, @QCBillDate DATE', @BillNo, @QCBillDate
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryPchOrdBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryPchOrdBill]
GO
/****** Object:  StoredProcedure [UP_PD_QueryPchOrdBill]    Script Date: 06/16/2014 11:22:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/6/16
-- Description:	 查询采购订单
-- Update:增加IsDraft字段检索（确认生效状态）
-- =============================================
CREATE PROCEDURE [UP_PD_QueryPchOrdBill](
     @BillNo INT = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SqlMain NVARCHAR(4000), @SqlDetail NVARCHAR(4000), @ExtCol NVARCHAR(40) = ', AuditStatus',
	        @MainTable NVARCHAR(40) = 'PD_PchOrdBill', @DetailTable NVARCHAR(40) = 'PD_PchOrdDetail'
	IF NOT EXISTS (SELECT 1 FROM PD_PchOrdBill WHERE BillNo = @BillNo)
		BEGIN
			SET @MainTable += '_His'
			SET @DetailTable += '_His'
			SET @ExtCol = ''
		END
	SET @SqlMain = 'SELECT ord.BillNo, ord.BillCode, ord.BillDate, ord.DlvDate, ord.BTypeID, ord.DeptID, ord.ElyID, ord.WhsID, ord.BillQty, 
						   ord.BTDTotal, ord.Total, creator.ElyName AS CreatorName, ord.CreateTime, ord.Summary, ord.[Description], ord.Stt,ord.IsDraft,
						   ord.StopTag, ord.Creator AS CreatorID, whs.WhsName, dept.DeptName, ely.ElyName, btype.BTypeName ' + @ExtCol +
						 ' FROM ' + @MainTable + ' ord
						   LEFT JOIN BD_Whs whs ON ord.WhsID = whs.WhsID
						   LEFT JOIN BD_Dept dept ON ord.DeptID = dept.DeptID
						   LEFT JOIN BD_Employee ely ON ord.ElyID = ely.ElyID 
						   LEFT JOIN BD_Employee creator ON ord.Creator = creator.ElyID
						   LEFT JOIN BD_Btype btype ON ord.BTypeID = btype.BTypeID
					 WHERE ord.BillNo = @BillNo'  --查询主表
						
	EXEC sp_executesql @SqlMain, N'@BillNo INT', @BillNo
     
     
     SET @SqlDetail = 'SELECT detail.DID, detail.BillNo, detail.BarCode, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.PriceID,
							detail.WhsID, detail.WhsPtID, detail.UnitID, detail.Convfactor, detail.Price, detail.DiscPrice, 
							detail.TaxPrice, detail.Qty, detail.BSQty, detail.Total, detail.DiscTotal, detail.TaxTotal,
							detail.Discount, detail.TaxRate, detail.Tax, detail.ComQty, CAST(detail.Gift AS BIT) AS Gift, 
							detail.StopTag, detail.Stt, detail.Remark, goods.GoodsNo, goods.GoodsName, goods.Spec,  
							goods.Model, price.Unit, ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name,
						   (SELECT COUNT(1) FROM PD_PchDetail d 
											   INNER JOIN PD_PchBill b ON d.BillNo = b.BillNo
											   WHERE d.OrdDID = detail.DID AND b.Red = 0) AS SelectQty,
						   (SELECT COUNT(1) FROM PD_PchDetail_His d 
											   INNER JOIN PD_PchBill_His b ON d.BillNo = b.BillNo
											   WHERE d.OrdDID = detail.DID AND b.Red = 0) AS HisSelectQty,
							price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1,
							case when price1.Convfactor IS null then 1 else price1.Convfactor end  AS Convfactor1,
							price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, 
							case when price2.Convfactor IS null then 1 else price2.Convfactor end  AS Convfactor2,
							price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3, 
							case when price3.Convfactor IS null then 1 else price3.Convfactor end  AS Convfactor3  ,
							detail.goodsno AS BtypeGoodsNo,goods.Brand,goods.KG	   
							FROM ' + @DetailTable + ' detail
							LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
							LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID
							LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
							LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
							LEFT JOIN BD_Goods_Price price1 ON price1.GoodsID = detail.GoodsID
							LEFT JOIN BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID And price2.UnitID = 2
							LEFT JOIN BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID And price3.UnitID = 3
					  WHERE detail.BillNo = @BillNo AND price.UnitID = detail.UnitID
							AND price1.UnitID = 1
					   ORDER BY detail.DID'  --查询明细
						
	EXEC sp_executesql @SqlDetail, N'@BillNo INT', @BillNo
                                                      
END
GO




/****** Object:  StoredProcedure [UP_PD_QuerySACDTLSum]    Script Date: 05/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySACDTLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySACDTLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySACDTLSum]    Script Date: 05/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-06
	描述：调拨验收(明细)Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySACDTLSum]
(
	@BillNo BIGINT=0		--单据编号
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@HisStr VARCHAR(20)='_His'
IF EXISTS (SELECT 1 FROM PD_AllotBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''
SET @Sql='SET NOCOUNT ON; 
SELECT ISNULL(SUM(dtl.AllotTotal),0)[FHTotal] 
FROM PD_AllotDetail'+@HisStr+' dtl 
INNER JOIN PD_AllotBill'+@HisStr+' b ON b.BillNo = dtl.BillNo 
WHERE dtl.BillNo=@BillNo AND b.InspectTag=1'

--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillNo BIGINT',@BillNo

GO






/****** Object:  StoredProcedure [UP_PD_QuerySACLSum]    Script Date: 05/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySACLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySACLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySACLSum]    Script Date: 05/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-05
	描述：调拨验收Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySACLSum]
(
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@InWhsID VARCHAR(1000)='',		--要货仓库
	@OutWhsID VARCHAR(1000)='',		--发货仓库
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@GoodsID VARCHAR(1000)='',		--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@InspectTag INT=9,				--验收状态
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql_One NVARCHAR(MAX)='',@Sql_Two NVARCHAR(MAX)='',@Sql_BN VARCHAR(200)='',@Sql_BN_His VARCHAR(200)=''
		,@SqlJoin NVARCHAR(MAX)='',@SqlJoin_BN VARCHAR(200)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)=''
		,@SqlJoin_KT_In VARCHAR(100)='',@SqlJoin_KT_Out VARCHAR(100)='',@KtypeLimit INT=2 
IF @DeptID <> ''
	SET @SqlJoin +='
		INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @InWhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@InWhsID, '','') _Whs0 ON _Whs0.typeid = b.InWhsID '
IF @OutWhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@OutWhsID, '','') _Whs1 ON _Whs1.typeid = b.OutWhsID '
IF @InWhsID = '' AND @OutWhsID = ''
BEGIN
	/*权限使用公用方法*/
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF( @KtypeLimit = 1 ) --部份权限
	BEGIN
		SET @SqlJoin_KT_Out = '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs2 ON rWhs2.WhsID=b.OutWhsID '
		SET @SqlJoin_KT_In = '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs1 ON rWhs1.WhsID=b.InWhsID '
	END
END

SET @SqlParam = '
		WHERE 1=1 '
IF @BillCode <> ''
	SET @SqlParam +='
		AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
		AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @Description <> ''
	SET @SqlParam +='
		AND b.[Description] Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='
		AND b.Summary Like ''%''+@Summary+''%'' '
SET @SqlParam_His = @SqlParam
IF @InspectTag <> 9
	SET @SqlParam +='
		AND b.InspectTag=@InspectTag '

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
IF @BarCode <> ''      --商品条码
   BEGIN 
	   IF @BarCodeMatch = 0
		   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
	   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID '
   END    
/*end*/
IF @GoodsID <> '' OR @ClauseParam <> ''
BEGIN
	IF @GoodsID <> ''
		SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
	SET @SqlParam_His += '
		AND EXISTS (SELECT 1 FROM PD_AllotDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
	SET @SqlParam += '
		AND EXISTS (SELECT 1 FROM PD_AllotDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' )'
END

SET @Sql_BN += '
		SELECT b.BillNo 
		FROM PD_AllotBill b '
SET @Sql_BN_His += '
		SELECT b.BillNo 
		FROM PD_AllotBill_His b '
SET @Sql_One = '
	SELECT 1[a] '
IF @InWhsID = '' AND @OutWhsID = ''
BEGIN
	IF @KtypeLimit = 1	--部份权限
	BEGIN
		SET @SqlJoin_BN = '
		INNER JOIN BillNoList bn ON bn.BillNo = b.BillNo '
		IF @IsHistory = 1 AND @InspectTag <> 0
		BEGIN
			SET @Sql_One = '
	SELECT DISTINCT o.* FROM ( ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_In + @SqlParam + '
		UNION ALL ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_Out + @SqlParam + '
		UNION ALL ' + @Sql_BN_His + @SqlJoin + @SqlJoin_KT_In + @SqlParam_His + '
		UNION ALL ' + @Sql_BN_His + @SqlJoin + @SqlJoin_KT_Out + @SqlParam_His + '
	) AS o'
		END
		ELSE
		BEGIN
			SET @Sql_One = '
	SELECT DISTINCT o.* FROM ( ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_In + @SqlParam + '
		UNION ALL ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_Out + @SqlParam + '
	) AS o'
		END
	END
END
IF LEN(@SqlJoin_BN) > 0 
BEGIN
	SET @SqlJoin = ''
	SET @SqlParam = ''
	SET @SqlParam_His = ''
END 
SET @Sql_Two = '
		SELECT b.BillNo,b.Total[FHTotal] 
		FROM PD_AllotBill b ' + @SqlJoin_BN + @SqlJoin + @SqlParam
IF @IsHistory = 1 AND @InspectTag <> 0 AND LEN(@SqlJoin_BN) = 0
BEGIN
	SET @Sql_Two += '
		UNION ALL
		SELECT b.BillNo,b.Total[FHTotal] 
		FROM PD_AllotBill_His b ' + @SqlJoin_BN + @SqlJoin + @SqlParam_His
END

SET @Sql = 'IF OBJECT_ID(''tempdb..#tempbo'',''U'') IS NOT NULL DROP TABLE #tempbo 
SET NOCOUNT ON; 
;WITH BillNoList AS( ' + @Sql_One + '
)
,BillData AS( ' + @Sql_Two + '
)'
SET @Sql += '
SELECT ISNULL(SUM(FHTotal),0)[FHTotal] FROM BillData '

IF @KtypeLimit = 0 
	SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

EXEC SP_EXECUTESQL @Sql,N'@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@BillCode VARCHAR(50),@InWhsID VARCHAR(1000),@OutWhsID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@InspectTag INT=9,@OperatorID INT',@BillStartDate,@BillEndDate,@BillCode,@InWhsID,@OutWhsID,@DeptID,@ElyID,@GoodsID,@Description,@Summary,@InspectTag,@OperatorID

END

GO






/****** Object:  StoredProcedure [UP_PD_QuerySaleBackBillData]    Script Date: 06/28/2014 16:51:59 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySaleBackBillData]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySaleBackBillData]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleBackBillData]    Script Date: 06/28/2014 16:51:59 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-06-17
	描述：查询销售退货单数据
	update sunzhiyuan 多账户查询
	update sunzhiyuan 增加AuditStatus字段检索
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleBackBillData]
(
	@BillNo INT=0
) 
AS
BEGIN			
	DECLARE @IsAccounts INT = 0
	IF EXISTS(SELECT 1 FROM PD_MulAccounts WHERE BillTypeID = 202 AND BillNo = @BillNo)
		SELECT @IsAccounts = 1
		
	IF EXISTS (SELECT 1 FROM PD_SellRetBill b WHERE b.BillNo=@BillNo)
	BEGIN		--当前数据	
		SELECT TOP 1 
			p.IsDraft,p.Red
			,p.BillNo,p.BillCode,p.BillDate
			,p.BTypeID,b.BTypeName
			,p.ElyID,e.ElyName
			,p.DeptID,d.DeptName
			,p.WhsID,w.WhsName
			,p.Summary,p.[Description]
			,p.Creator[CreatorID],e1.ElyName[CreatorName]
			,e1.ElyName[PosName]
			,p.BillQty,p.BTDTotal,PaidTotal,p.Total,
			CASE @IsAccounts WHEN 0 THEN p.FinanceID ELSE -100 end as FinanceID,
			CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '【多账户】' end as FinanceName
			--,p.FinanceID,f.FinanceName
			,p.PayRecTotal,p.Total-p.Privilege[AfterPrivilege],p.Privilege,p.IsOS ,@IsAccounts as IsAccounts,
			p.AuditStatus,p.IsInvoice,
			   p.IsDeduction,
			   p.DeductionCent,
			   p.ExchangeCent,
			   p.VipCardID,
			   Vt.TypeName + ' 会员卡号：'+v.VipCardNO+' 会员名称：'+V.VipName+' 持卡人：' + CardHolder  AS VipCardInfo,
			   p.BeforeARTotal,
			   ISNULL(P.BeforeARTotal,0)-((ISNULL(P.total,0)-ISNULL(P.Privilege,0)-ISNULL(P.PayRecTotal,0))) AS CurARTotal
		FROM PD_SellRetBill p 
		INNER JOIN BD_Btype b ON p.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON p.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON p.DeptId=d.DeptId 
		INNER JOIN BD_Whs w ON p.WhsID=w.WhsID 
		LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID 
		LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID 
		LEFT JOIN BD_Finance f ON p.FinanceID = f.FinanceID 
		LEFT JOIN VS_VipCard V ON p.VipCardID = v.VipCardID
		LEFT JOIN VS_VipCardType Vt ON v.VipCardTypeID = Vt.VipCardTypeID
		WHERE p.BillNo=@BillNo 
		
		SELECT  p.DID,p.GoodsID,g.GoodsNo,g.GoodsName
				,p.BarCode
				,g.Spec,g.Model
				,p.Ppt1ID,p1.Value[Ppt1Name]
				,p.Ppt2ID,p2.Value[Ppt2Name]
				,p.WhsID,p.WhsPtID,wp.WhsPtName
				,p.UnitID,gp.Unit
				,p.Convfactor,p.Price,p.GoodsCostTotal,p.Qty,p.BSQty,p.Total,p.Discount,p.DiscPrice,p.DiscTotal
				,case p.BSQty when 0 then 0 else (p.GoodsCostTotal/ p.BSQty) end as GoodsCostPrice
				,p.TaxRate,p.Tax,p.TaxPrice,p.TaxTotal,cast(p.Gift AS BIT) Gift,p.PriceID,p.Remark
				,p.BatchNumber,p.ProductDate,p.EndDate
				,gp1.Convfactor[Convfactor1]
				,ISNULL(gp2.Convfactor,1)[Convfactor2]
				,ISNULL(gp3.Convfactor,1)[Convfactor3]
				,gp1.BarCode[BarCode1],gp2.BarCode[BarCode2],gp3.BarCode[BarCode3]
				,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3] ,p.IsSelectBatch,
				g.IsSerial,p.BatchNumber,p.ProductDate,p.EndDate,p.SellDID,op.BillCode,p.InPutPrice,g.DateType,g.ValidDays,g.CostMethod			
				--,case when gp2.Unit is null then '' else gp2.Unit end [Unit2]
				--,case when gp3.Unit is null then '' else gp3.Unit end [Unit3] 
				,p.goodsno AS BtypeGoodsNo,
				g.Brand,
				g.KG	
		FROM PD_SellRetDetail p 
		INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID 
		LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
		LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
		INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID 
		LEFT JOIN 
			(
				SELECT BillCode,DID 
				FROM PD_SellDetail D
				INNER JOIN PD_SellBill b ON d.BillNo = b.BillNo
				UNION ALL
				SELECT BillCode,DID 
				FROM PD_SellDetail_His D
				INNER JOIN PD_SellBill_His b ON d.BillNo = b.BillNo
			) op ON op.DID= p.SellDID
		INNER JOIN BD_Goods_Price gp ON p.GoodsID=gp.GoodsID AND p.UnitID=gp.UnitID 
		LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND 1=gp1.UnitID 
		LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND 2=gp2.UnitID 
		LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND 3=gp3.UnitID
		WHERE p.BillNo=@BillNo 
		
		-- 查询多账户信息
		SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 202 and BillNo = @BillNo
		
		-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_SellRetSerial ps Inner Join PD_SellRetDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
	ELSE
	BEGIN
		SELECT TOP 1 
			p.IsDraft,p.Red
			,p.BillNo,p.BillCode,p.BillDate
			,p.BTypeID,b.BTypeName
			,p.ElyID,e.ElyName
			,p.DeptID,d.DeptName
			,p.WhsID,w.WhsName
			,p.Summary,p.[Description]
			,p.Creator[CreatorID],e1.ElyName[CreatorName]
			,e1.ElyName[PosName]
			,p.BillQty,p.BTDTotal,PaidTotal,p.Total,
			CASE @IsAccounts WHEN 0 THEN p.FinanceID ELSE -100 end as FinanceID,
			CASE @IsAccounts WHEN 0 THEN f.FinanceName ELSE '【多账户】' end as FinanceName
			--,p.FinanceID,f.FinanceName
			,p.PayRecTotal,p.Total-p.Privilege[AfterPrivilege],p.Privilege,p.IsOS ,@IsAccounts as IsAccounts
			,p.IsInvoice,
			   p.IsDeduction,
			   p.DeductionCent,
			   p.ExchangeCent,
			   p.VipCardID,
			   '会员卡类型：'+ Vt.TypeName + ' 会员卡号：'+v.VipCardNO+' 会员名称：'+V.VipName+' 持卡人：' + CardHolder + ' 会员卡状态' AS VipCardInfo,
			     p.BeforeARTotal,
			     ISNULL(P.BeforeARTotal,0)-((ISNULL(P.total,0)-ISNULL(P.Privilege,0)-ISNULL(P.PayRecTotal,0))) AS CurARTotal
				
		FROM PD_SellRetBill_His p 
		INNER JOIN BD_Btype b ON p.BtypeID=b.BTypeID 
		INNER JOIN BD_Employee e ON p.ElyID=e.ElyID 
		INNER JOIN BD_Dept d ON p.DeptId=d.DeptId 
		INNER JOIN BD_Whs w ON p.WhsID=w.WhsID 
		LEFT JOIN BD_Employee e1 ON p.Creator=e1.ElyID 
		LEFT JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID 
		LEFT JOIN BD_Finance f ON p.FinanceID = f.FinanceID 
		LEFT JOIN VS_VipCard V ON p.VipCardID = v.VipCardID
		LEFT JOIN VS_VipCardType Vt ON v.VipCardTypeID = Vt.VipCardTypeID
		WHERE p.BillNo=@BillNo 
		
		SELECT  p.DID,p.GoodsID,g.GoodsNo,g.GoodsName
				,p.BarCode
				,g.Spec,g.Model
				,p.Ppt1ID,p1.Value[Ppt1Name]
				,p.Ppt2ID,p2.Value[Ppt2Name]
				,p.WhsID,p.WhsPtID,wp.WhsPtName
				,p.UnitID,gp.Unit
				,p.Convfactor,p.Price,p.GoodsCostTotal,p.Qty,p.BSQty,p.Total,p.Discount,p.DiscPrice,p.DiscTotal
				,case p.BSQty when 0 then 0 else (p.GoodsCostTotal/ p.BSQty) end as GoodsCostPrice
				,p.TaxRate,p.Tax,p.TaxPrice,p.TaxTotal,cast(p.Gift AS BIT) Gift,p.Remark
				,p.BatchNumber,p.ProductDate,p.EndDate
				,gp1.Convfactor[Convfactor1]
				,ISNULL(gp2.Convfactor,1)[Convfactor2]
				,ISNULL(gp3.Convfactor,1)[Convfactor3]
				,gp1.BarCode[BarCode1],gp2.BarCode[BarCode2],gp3.BarCode[BarCode3]
				,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3] ,
				g.IsSerial,p.BatchNumber,p.ProductDate,p.EndDate,p.SellDID,op.BillCode,p.InPutPrice,g.DateType,g.ValidDays,g.CostMethod					
				--,case when gp2.Unit is null then '' else gp2.Unit end [Unit2]
				--,case when gp3.Unit is null then '' else gp3.Unit end [Unit3] 
				,p.goodsno AS BtypeGoodsNo,
				g.Brand,
				g.KG
		FROM PD_SellRetDetail_His p 
		INNER JOIN BD_Goods g ON p.GoodsID=g.GoodsID 
		LEFT JOIN BD_Goods_Ppt1 p1 ON p.Ppt1ID = p1.Ppt1ID 
		LEFT JOIN BD_Goods_Ppt2 p2 ON p.Ppt2ID = p2.Ppt2ID
		INNER JOIN BD_Whs_Position wp ON p.WhsPtID=wp.WhsPtID 
		LEFT JOIN 
			(
				SELECT BillCode,DID 
				FROM PD_SellDetail D
				INNER JOIN PD_SellBill b ON d.BillNo = b.BillNo
				UNION ALL
				SELECT BillCode,DID 
				FROM PD_SellDetail_His D
				INNER JOIN PD_SellBill_His b ON d.BillNo = b.BillNo
			) op ON op.DID= p.SellDID
		INNER JOIN BD_Goods_Price gp ON p.GoodsID=gp.GoodsID AND p.UnitID=gp.UnitID 
		LEFT JOIN BD_Goods_Price gp1 ON p.GoodsID=gp1.GoodsID AND 1=gp1.UnitID 
		LEFT JOIN BD_Goods_Price gp2 ON p.GoodsID=gp2.GoodsID AND 2=gp2.UnitID 
		LEFT JOIN BD_Goods_Price gp3 ON p.GoodsID=gp3.GoodsID AND 3=gp3.UnitID 
		WHERE p.BillNo=@BillNo 
		
		-- 查询多账户信息
		SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 202 and BillNo = @BillNo
		
		-- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_SellRetSerial_His ps Inner Join PD_SellRetDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
	END
END




GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-7-15
	描述：查询销售明细
	××××××××××××××××××
	修改：sunzhiyuan
	日期：2015-3-27
	修改描述：24行：增加@DateType（时间类型）参数；
			 202行：判断时间类型
			 修改参数@BeginDate、@EndDate为DateTime类型
			 73行：取消归档数据判断
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleDetails]
(
	@PageNo INT=0,                       --页码
	@PageSize INT=0,                     --分页数
	@DateType INT=0,                     --单据日期类型 0 业务日期 1 制单日期 2 过账日期
	@BeginDate DATETIME,                 --单据开始日期
	@EndDate DATETIME,                   --单据结束日期
	@SaleBill Int = 1,                   --销售出库单勾选状态
	@SaleBackBill Int = 1,               --销售退货单勾选状态
	@BTypeID VARCHAR(max)='',            --往来单位
	@DeptID VARCHAR(max)='',             --部门
	@ElyID VARCHAR(max)='',              --经手人
	@CreatorID VARCHAR(max)='',          --制单人
	@WhsID VARCHAR(max)='',
	@BillCode VARCHAR(100)='',
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100)='',
	@UserCodeMatch INT=0,
	@UserCode VARCHAR(100)='',
	@FullNameMatch INT=0,
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	@Ppt1 VARCHAR(100)='',
	@Ppt1Match INT=0,
	@Ppt2 VARCHAR(100)='',
	@Ppt2Match INT=0,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=0,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=0,
	@Remark VARCHAR(100)='',
	@RemarkMatch INT=0,
	@GiftFlag INT=0,
	@OrderType1 Varchar(50)='PosTime',				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额
	@OrderSeq1 Int=1,  --排序类型 1=升序，2=降序
	@OrderType2 Varchar(50)='GoodsNo',				--排序条件一:0=单据编号,1=单据类型,2=录单日期,3=制单日期,4=过账日期,5=往来单位编号,6=往来单位名称,7=商品编号,8=商品名称,9=数量,10=单价,11=金额,12=折扣,13=折后单价,14=折后金额			
	@OrderSeq2 Int=1,  --排序类型 1=升序，2=降序
	@AuQtyFlag INT= 0,
	@IsRedFlag Int = 0,
	@OperatorID INT = 0,
	@ClassID1 Int = 0,		--汇总条件一，ID
	@ClassType1 Int = 0,	--汇总条件一类型 1为商品汇总，2为往来单位汇总，3为仓库汇总，4为地区汇总，5为部门汇总，6为职员汇总
	@ClaseFlag1 Int = 0,	--汇总条件一分类 0为非分类，1为分类汇总
	@ClassID2 Int = 0,		--汇总条件二，ID
	@ClassType2 Int = 0,	--汇总条件二类型 1为商品汇总，2为往来单位汇总，3为仓库汇总，4为地区汇总，5为部门汇总，6为职员汇总
	@ClaseFlag2 Int = 0,		--汇总条件二分类 0为非分类，1为分类汇总
	@isHistory INT=0,				--是否包含历史数据
	@ClickFlag Int =0,
	@GoodsDataFile1 varchar(100) ='', --商品自定义字段1
	@GoodsDataFile2 varchar(100) ='', --商品自定义字段2
	@GoodsDataFile3 varchar(100) ='', --商品自定义字段3
	@GoodsDataFile4 varchar(100) ='', --商品自定义字段4
	@GoodsDataFile5 varchar(100) ='', --商品自定义字段5
	@GoodsCFlag1 int = 0, --商品自定义字段1选中标识
	@GoodsCFlag2 int = 0, --商品自定义字段2选中标识
	@GoodsCFlag3 int = 0, --商品自定义字段3选中标识
	@GoodsCFlag4 int = 0, --商品自定义字段4选中标识
	@GoodsCFlag5 int = 0, --商品自定义字段5选中标识
	@BtypeDataFile1 varchar(100) ='', --往来单位自定义字段1
	@BtypeDataFile2 varchar(100) ='', --往来单位自定义字段2
	@BtypeDataFile3 varchar(100) ='', --往来单位自定义字段3
	@BtypeDataFile4 varchar(100) ='', --往来单位自定义字段4
	@BtypeDataFile5 varchar(100) ='',  --往来单位自定义字段5	
	@BtypeCFlag1 int = 0, --往来单位自定义字段1选中标识
	@BtypeCFlag2 int = 0, --往来单位自定义字段2选中标识
	@BtypeCFlag3 int = 0, --往来单位自定义字段3选中标识
	@BtypeCFlag4 int = 0, --往来单位自定义字段4选中标识
	@BtypeCFlag5 int = 0 --往来单位自定义字段5选中标识
)

AS
SET NOCOUNT ON
	-- 如果单据日期类型为业务日期 则检查是否存在归档数据
	IF @DateType = 0
	BEGIN
		DECLARE @re int 
		execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
		if( @re=1 )return @re;
	END
set @OrderType1 = isnull(@OrderType1,'')	
set @OrderType2 = isnull(@OrderType2,'')
if((@OrderType1='' or @OrderType1 = null) and (@OrderType2='' or @OrderType2 = null))
Begin
	Set @OrderType1='PosTime'
End
DECLARE @sql nvarchar(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlMatch varchar(max)='',@SqlWhs nvarchar(max),
		@SqlDept nvarchar(max),@SqlEly nvarchar(max),@SqlPost nvarchar(max),@SqlUnit nvarchar(2000),
		@SqlAuUnit nvarchar(Max)='',@SqlBtype nvarchar(max)='',@SqlCreator nvarchar(max),@SqlIn nvarchar(Max)='',@SqlOut nVarchar(max)='',@OrderName nvarchar(100)='',
		@OrderColumn varchar(max)='',@OrderTable varchar(max)='',@GoodsTable varchar(max)='',@GoodsMath varchar(max)='', 
		@SqlGoods Nvarchar(1000)='',@SqlPpt1 nvarchar(1000),@SqlPpt2 nvarchar(1000), @LimitKtypeSql NVARCHAR(MAX) = '', @LimitBtypeSql NVARCHAR(MAX) = '',@RedStr varchar(100)='',@Red varchar(100)=''
		,@SqlClass1 varchar(500)='',@SqlClass2 varchar(500)='',@SqlBSUnit nvarchar(1000)='',@SqlBase varchar(max)='',
		@saleStr varchar(max)='bill.BillNo,DID',@saleRetStr varchar(max)='bill.BillNo,DID',
		@pageDataStr varchar(max)=' BillNo,BillTypeID,DiD',@outSql varchar(max)=''
		,@SqlInStr nvarchar(Max)='',@SqlOutStr nVarchar(max)=''	,@OutStr varchar(max)='',@OutRetStr varchar(max)='',@BtypeLimit INT=0,@KtypeLimit INT=0
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
End
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
Select @SqlCreateTable+= ' Declare @GoodsTypeID Int,@BtypeTypeID Int,@WhsTypeID int,@AreaTypeID Int,@DeptID Int
		if @ClassID1 <> 0
		Begin			
			if(@ClassType1 = 1 and @ClaseFlag1 = 1)
				Select @GoodsTypeID = @ClassID1
			if(@ClassType1 = 2 and @ClaseFlag1 = 1)
				Select @BtypeTypeID = @ClassID1
			if(@ClassType1 = 3 and @ClaseFlag1 = 1)
				Select @WhsTypeID = @ClassID1
			if(@ClassType1 = 4)
				Select @AreaTypeID = @ClassID1
			if(@ClassType1 = 5)
				Select @DeptID = @ClassID1
		END
		if @ClassID2 <> 0
		Begin
			if(@ClassType2 = 1 and @ClaseFlag2 = 1)
				Select @GoodsTypeID = @ClassID2
			if(@ClassType2 = 2 and @ClaseFlag2 = 1)
				Select @BtypeTypeID = @ClassID2
			if(@ClassType2 = 3 and @ClaseFlag2 = 1)
				Select @WhsTypeID = @ClassID2
			if(@ClassType2 = 4)
				Select @AreaTypeID = @ClassID2
			if(@ClassType2 = 5)
				Select @DeptID = @ClassID2
		END '
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID1,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON bill.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON bill.ElyID=E.TypeID ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' INNER JOIN @CreateEType CE ON bill.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	SET @SqlTable+=' INNER JOIN @KType W ON bill.WhsID=W.TypeID ' 
END	

IF @ClassID1 <> 0
Begin
	SET @SqlClass1 +=' DECLARE @CTb1  as Table(typeid int) INSERT INTO @CTb1(typeid) '
	Set @SqlCreateTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass1 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass1 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then ' And detail.GoodsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on detail.GoodsID = C1.TypeID' end 
											when 2 then case @ClaseFlag1 when 0 then ' And bill.BtypeID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.BtypeID = C1.TypeID' end
											when 3 then case @ClaseFlag1 when 0 then ' And bill.WhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.WhsID = C1.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb1 C1 on BB.AreaID = C1.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb1 C1 on EE.DeptId = C1.TypeID'
											when 6 then ' And bill.ElyID = @ClassID1 '  
											When 7 then ' And bill.Creator = @ClassID1' end 	
	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType1 = 4 and @ClassID1 = 0 
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END

IF @ClassID2 <> 0
Begin
	SET @SqlClass2 +=' DECLARE @CTb2  as Table(typeid int) INSERT INTO @CTb2(typeid) '
	Set @SqlCreateTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass2 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass2 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then ' And detail.GoodsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on detail.GoodsID = C2.TypeID' end 
											when 2 then case @ClaseFlag2 when 0 then ' And bill.BtypeID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.BtypeID = C2.TypeID' end
											when 3 then case @ClaseFlag2 when 0 then ' And bill.WhsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.WhsID = C2.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb2 C2 on BB.AreaID = C2.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb2 C2 on EE.DeptId = C2.TypeID'
											when 6 then ' And bill.ElyID = @ClassID2 '  
											When 7 then ' And bill.Creator = @ClassID2' end 	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType2 = 4 and @ClassID2 = 0
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END

-- 判断单据时间类型
if @DateType = 0
	set @SqlDTStr = 'detail.BillDate'
IF @DateType=1
	SET @SqlDTStr='bill.CreateTime'	
IF @DateType=2
	SET @SqlDTStr='bill.PosTime'

if(@Summary <> '')
	Set @SqlMatch += ' And Summary ' + case @SummaryMatch when 0 then ' Like ''%''+@Summary+''%''' Else ' =@Summary ' End
if(@Description <> '')
	Set @SqlMatch += ' And Description ' + case @DescriptionMatch when 0 then ' Like ''%''+@Description+''%''' Else ' =@Description ' END
if(@Remark <> '')
	Set @SqlMatch += ' And Remark ' + case @RemarkMatch when 0 then ' Like ''%''+@Remark+''%''' Else ' =@Remark ' END
if(@BillCode <> '')
	Set @SqlMatch += ' And BillCode ' + case @BillCodeMatch when 0 then ' Like ''%''+@BillCode+''%''' Else ' =@BillCode ' END	
if(@FullName <> '' or @UserCode <> '' or @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> '')
Begin
	if(@FullName <> '')
		Set @GoodsMath += ' And G.GoodsName ' + case @FullNameMatch when 0 then ' Like ''%''+@FullName+''%''' Else ' =@FullName ' END
	if(@UserCode <> '')
		Set @GoodsMath += ' And G.GoodsNo ' + case @UserCodeMatch when 0 then ' Like ''%''+@UserCode+''%''' Else ' =@UserCode ' END
	--商品型号
	IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @GoodsMath += N' AND G.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @GoodsMath += N' AND G.Model = @Model ' 
	END   
	--商品简名    
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @GoodsMath += N' AND G.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @GoodsMath += N' AND G.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @GoodsMath += N' AND G.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @GoodsMath += N' AND G.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
		
	   IF @SpecMatch = 0
		   SET @GoodsMath += N' AND G.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @GoodsMath += N' AND G.Spec = @Spec '  
	END
	
	Select @GoodsTable += ' And exists(select 1 from BD_GOODS G Where detail.GoodsID = G.GoodsID '+@GoodsMath+')'
End
--商品条码
	IF @BarCode <> ''      
	BEGIN 
		Set @SqlTable += ' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID and pri.UnitID = 1 '
		
	   SET @GoodsTable += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = detail.GoodsID '
	   IF @BarCodeMatch = 0
		   SET @GoodsTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @GoodsTable += N' AND pri.BarCode = @BarCode ' 
	   SET @GoodsTable += ' ) '
	END 
if(@Ppt1 <> '' or (@ClickFlag = 1 and  @Ppt1Match = 1))
BEGIN
	if(@Ppt1 <> '')
	Begin
		Set @GoodsMath = ' And GP1.Value ' + case @Ppt1Match when 0 then ' Like ''%''+@Ppt1+''%''' Else ' =@Ppt1 ' END
		Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt1 GP1 Where detail.Ppt1ID = GP1.Ppt1ID '+@GoodsMath+')'
	End
	Else
		Select @GoodsTable += ' And Ppt1ID = 0 ' 
END
if(@Ppt2 <> '' or (@ClickFlag = 1 and  @Ppt2Match = 1))
BEGIN
	if(@Ppt2 <> '')
	Begin
		Set @GoodsMath = ' And GP2.Value ' + case @Ppt2Match when 0 then ' Like ''%''+@Ppt2+''%''' Else ' =@Ppt2 ' END	
		Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt2 GP2 Where detail.Ppt2ID = GP2.Ppt2ID '+@GoodsMath+')'
	End
	Else
		Select @GoodsTable += ' And Ppt2ID = 0 ' 
END

--自定义字段汇总查询明细
IF(@GoodsDataFile1 <> '' OR (@ClickFlag = 1 And @GoodsCFlag1 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG1 ON detail.GoodsID = BG1.BaseID '
	Set @SqlMatch += ' And BG1.CustVal1 = @GoodsDataFile1 '
END
IF(@GoodsDataFile2 <> '' OR (@ClickFlag = 1 And @GoodsCFlag2 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG2 ON detail.GoodsID = BG2.BaseID '
	Set @SqlMatch += ' And BG2.CustVal2 = @GoodsDataFile2 '
END
IF(@GoodsDataFile3 <> '' OR (@ClickFlag = 1 And @GoodsCFlag3 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG3 ON detail.GoodsID = BG3.BaseID '
	Set @SqlMatch += ' And BG3.CustVal3 = @GoodsDataFile3 '
END
IF(@GoodsDataFile4 <> '' OR (@ClickFlag = 1 And @GoodsCFlag4 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG4 ON detail.GoodsID = BG4.BaseID '
	Set @SqlMatch += ' And BG4.CustVal4 = @GoodsDataFile4 '
END
IF(@GoodsDataFile5 <> '' OR (@ClickFlag = 1 And @GoodsCFlag5 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG5 ON detail.GoodsID = BG5.BaseID '
	Set @SqlMatch += ' And BG5.CustVal5 = @GoodsDataFile5 '
END
IF(@BtypeDataFile1 <> '' OR (@ClickFlag = 1 And @BtypeCFlag1 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB1 ON bill.BtypeID = BB1.BaseID '
	Set @SqlMatch += ' And BB1.CustVal1 = @BtypeDataFile1 '
END
IF(@BtypeDataFile2 <> '' OR (@ClickFlag = 1 And @BtypeCFlag2 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB2 ON bill.BtypeID = BB2.BaseID '
	Set @SqlMatch += ' And BB2.CustVal2 = @BtypeDataFile2 '
END
IF(@BtypeDataFile3 <> '' OR (@ClickFlag = 1 And @BtypeCFlag3 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB3 ON bill.BtypeID = BB3.BaseID '
	Set @SqlMatch += ' And BB3.CustVal3 = @BtypeDataFile3 '
END
IF(@BtypeDataFile4 <> '' OR (@ClickFlag = 1 And @BtypeCFlag4 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB4 ON bill.BtypeID = BB4.BaseID '
	Set @SqlMatch += ' And BB4.CustVal4 = @BtypeDataFile4 '
END
IF(@BtypeDataFile5 <> '' OR (@ClickFlag = 1 And @BtypeCFlag5 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB5 ON bill.BtypeID = BB5.BaseID '
	Set @SqlMatch += ' And BB5.CustVal5 = @BtypeDataFile5 '
END

if(@IsRedFlag = 0)
Begin
	Set @Red = ' And Red = 0 '
End
Else
	Set @RedStr = ',Red'
--按排序条件拼接首次需要查询的数据
if(@OrderType1 <> '')
Begin
	Select @saleStr += Case when @OrderType1 in ('BTypeCode','BTypeName') then ',BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') then ',detail.GoodsID'
							When @OrderType1 = 'Profit' then ',(detail.DiscTotal-detail.GoodsCostTotal) as Profit'
							When @OrderType1 = 'ProfitMargin' then ',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin'
							When @OrderType1 = 'BillTypeID' then '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
							When @OrderType1 = 'BillDate' then ',bill.'+@OrderType1
							else ',detail.'+@OrderType1 end
	Select @saleRetStr += Case when @OrderType1 in ('BTypeCode','BTypeName') then ',BTypeID '
						When @OrderType1 in ('GoodsNo','GoodsName') then ',detail.GoodsID'
						When @OrderType1 = 'Profit' then ',(detail.DiscTotal-detail.GoodsCostTotal)*-1 as Profit'
						When @OrderType1 = 'ProfitMargin' then ',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin'
						When @OrderType1 in ('Qty','Total','DiscTotal','CostPrice') then ',detail.'+@OrderType1+'*-1'
						When @OrderType1 = 'BillTypeID' then '' 
						When @OrderType1 in ('BillCode','CreateTime','PosTime') then ','+@OrderType1
						When @OrderType1 = 'BillDate' then ',bill.'+@OrderType1
						else ',detail.'+@OrderType1 end
	Select @pageDataStr += Case When @OrderType1 in ('BTypeCode','BTypeName') then ',bill.BTypeID '
						When @OrderType1 in ('GoodsNo','GoodsName') then ',bill.GoodsID'
						When @OrderType1 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
						When @OrderType1 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
						When @OrderType1 = 'BillTypeID' then '' 
						Else ','+@OrderType1 End
End		
if(@OrderType2 <> '')
Begin			
	Select @saleStr += Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',BTypeID ' End 
							When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',detail.GoodsID' end
							When @OrderType2 = 'Profit' then ',(detail.DiscTotal-detail.GoodsCostTotal) as Profit'
							When @OrderType2 = 'ProfitMargin' then ',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin'
							When @OrderType2 = 'BillTypeID' then '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
							When @OrderType2 = 'BillDate' then ',bill.'+@OrderType2
							else ',detail.'+@OrderType2 end
	Select @saleRetStr += Case when @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',BTypeID ' End 
						When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',detail.GoodsID' end
						When @OrderType2 = 'Profit' then ',(detail.DiscTotal-detail.GoodsCostTotal)*-1 as Profit'
						When @OrderType2 = 'ProfitMargin' then ',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin'
						When @OrderType2 in ('Qty','Total','DiscTotal','CostPrice') then ',detail.'+@OrderType2+'*-1'
						When @OrderType2 = 'BillTypeID' then '' 
						When @OrderType2 in ('BillCode','CreateTime','PosTime') then ','+@OrderType2
						When @OrderType2 = 'BillDate' then ',bill.'+@OrderType2
						else ',detail.'+@OrderType2 end		
	Select @pageDataStr += Case When @OrderType2 in ('BTypeCode','BTypeName') then Case When @OrderType1 in ('BTypeCode','BTypeName') then '' else ',bill.BTypeID ' End	
						When @OrderType2 in ('GoodsNo','GoodsName') then Case When @OrderType1 in ('GoodsNo','GoodsName') then '' else ',bill.GoodsID' end 
						When @OrderType2 = 'CreateTime' then ',CONVERT(varchar(100), CreateTime, 120) AS CreateTime'
						When @OrderType2 = 'PosTime' then ',CONVERT(varchar(100), PosTime, 120) AS PosTime'
						When @OrderType2 = 'BillTypeID' then '' 
						Else ','+@OrderType2 End				
End				

	
--拼接查询字段
Select @OutStr +=',bill.BillDate,BillCode,bill.BTypeID,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,detail.GoodsID,detail.Discount
	,Case When Bill.Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty,detail.Price
	,Case When Bill.Red = 2 then detail.Total * -1 Else detail.Total End as Total,detail.DiscPrice
	,Case when Bill.Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal,detail.CostPrice
	,Case When Bill.Red = 2 then detail.GoodsCostTotal * -1 Else detail.GoodsCostTotal End as GoodsCostTotal
	,Case When Bill.Red = 2 then (detail.DiscTotal-detail.GoodsCostTotal)*-1 Else (detail.DiscTotal-detail.GoodsCostTotal) End as Profit
	,Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin	'
Select @OutRetStr +=',bill.BillDate,BillCode,bill.BTypeID,CONVERT(varchar(100), CreateTime, 120) AS CreateTime,CONVERT(varchar(100), PosTime, 120) AS PosTime,detail.GoodsID,detail.Discount
  ,Case When Bill.Red = 2 then detail.Qty Else detail.Qty*-1 End as Qty,detail.Price
  ,Case When Bill.Red = 2 Then detail.Total Else detail.Total*-1 End as Total,detail.DiscPrice
  ,Case When Bill.Red = 2 Then detail.DiscTotal Else detail.DiscTotal*-1 End as  DiscTotal,detail.CostPrice
  ,Case When Bill.Red = 2 Then detail.GoodsCostTotal Else detail.GoodsCostTotal*-1 End as GoodsCostTotal
  ,Case When Bill.Red = 2 Then (detail.DiscTotal-detail.GoodsCostTotal) Else (detail.DiscTotal-detail.GoodsCostTotal)*-1 End as Profit
  ,Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin  '
select @OutStr = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@OutStr,',bill.BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@OutStr,',detail.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@OutStr,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@OutStr,',bill.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@OutStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@OutStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@OutStr,',detail.Price','') 
					When @OrderType1 = 'Total' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Total * -1 Else detail.Total End as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@OutStr,',detail.Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@OutStr,',detail.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@OutStr,',Case when Bill.Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal','') 
					When @OrderType1 = 'GoodsCostTotal' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.GoodsCostTotal * -1 Else detail.GoodsCostTotal End as GoodsCostTotal','') 
					When @OrderType1 = 'CostPrice' then REPLACE(@OutStr,',detail.CostPrice','') 
					When @OrderType1 = 'Profit' then REPLACE(@OutStr,',Case When Bill.Red = 2 then (detail.DiscTotal-detail.GoodsCostTotal)*-1 Else (detail.DiscTotal-detail.GoodsCostTotal) End as Profit','') 
					When @OrderType1 = 'ProfitMargin' then REPLACE(@OutStr,',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin','') 
					Else @OutStr end
select @OutStr = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@OutStr,',bill.BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@OutStr,',detail.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@OutStr,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@OutStr,',bill.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@OutStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@OutStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Qty * -1 Else detail.Qty End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@OutStr,',detail.Price','') 
					When @OrderType2 = 'Total' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.Total * -1 Else detail.Total End as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@OutStr,',detail.Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@OutStr,',detail.DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@OutStr,',Case when Bill.Red = 2 Then detail.DiscTotal * -1 Else detail.DiscTotal End as DiscTotal','') 
					When @OrderType2 = 'GoodsCostTotal' then REPLACE(@OutStr,',Case When Bill.Red = 2 then detail.GoodsCostTotal * -1 Else detail.GoodsCostTotal End as GoodsCostTotal','') 
					When @OrderType2 = 'CostPrice' then REPLACE(@OutStr,',detail.CostPrice','') 
					When @OrderType2 = 'Profit' then REPLACE(@OutStr,',Case When Bill.Red = 2 then (detail.DiscTotal-detail.GoodsCostTotal)*-1 Else (detail.DiscTotal-detail.GoodsCostTotal) End as Profit','') 
					When @OrderType2 = 'ProfitMargin' then REPLACE(@OutStr,',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin','')
					Else @OutStr end
select @OutRetStr = case when @OrderType1 in ('BTypeCode','BTypeName') then REPLACE(@OutRetStr,',bill.BTypeID','')
					when @OrderType1 in ('GoodsNo','GoodsName') then REPLACE(@OutRetStr,',detail.GoodsID','')
					When @OrderType1 = 'BillCode' then REPLACE(@OutRetStr,',BillCode','') 
					When @OrderType1 = 'BillDate' then REPLACE(@OutRetStr,',bill.BillDate','') 
					When @OrderType1 = 'CreateTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 then detail.Qty Else detail.Qty*-1 End as Qty','') 
					When @OrderType1 = 'Price' then REPLACE(@OutRetStr,',detail.Price','') 
					When @OrderType1 = 'Total' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.Total Else detail.Total*-1 End as Total','') 
					When @OrderType1 = 'Discount' then REPLACE(@OutRetStr,',detail.Discount','') 
					When @OrderType1 = 'DiscPrice' then REPLACE(@OutRetStr,',detail.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.DiscTotal Else detail.DiscTotal*-1 End as  DiscTotal','') 
					When @OrderType1 = 'GoodsCostTotal' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.GoodsCostTotal Else detail.GoodsCostTotal*-1 End as GoodsCostTotal','') 
					When @OrderType1 = 'CostPrice' then REPLACE(@OutRetStr,',detail.CostPrice','') 
					When @OrderType1 = 'Profit' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then (detail.DiscTotal-detail.GoodsCostTotal) Else (detail.DiscTotal-detail.GoodsCostTotal)*-1 End as Profit','') 
					When @OrderType1 = 'ProfitMargin' then REPLACE(@OutRetStr,',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin','') 
					Else @OutRetStr end
select @OutRetStr = case when @OrderType2 in ('BTypeCode','BTypeName') then REPLACE(@OutRetStr,',bill.BTypeID','')
					when @OrderType2 in ('GoodsNo','GoodsName') then REPLACE(@OutRetStr,',detail.GoodsID','')
					When @OrderType2 = 'BillCode' then REPLACE(@OutRetStr,',BillCode','') 
					When @OrderType2 = 'BillDate' then REPLACE(@OutRetStr,',bill.BillDate','') 
					When @OrderType2 = 'CreateTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' then REPLACE(@OutRetStr,',CONVERT(varchar(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 then detail.Qty Else detail.Qty*-1 End as Qty','') 
					When @OrderType2 = 'Price' then REPLACE(@OutRetStr,',detail.Price','') 
					When @OrderType2 = 'Total' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.Total Else detail.Total*-1 End as Total','') 
					When @OrderType2 = 'Discount' then REPLACE(@OutRetStr,',detail.Discount','') 
					When @OrderType2 = 'DiscPrice' then REPLACE(@OutRetStr,',detail.DiscPrice','') 
					When @OrderType2 = 'DiscTotal' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.DiscTotal Else detail.DiscTotal*-1 End as  DiscTotal','') 
					When @OrderType2 = 'GoodsCostTotal' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then detail.GoodsCostTotal Else detail.GoodsCostTotal*-1 End as GoodsCostTotal','') 
					When @OrderType2 = 'CostPrice' then REPLACE(@OutRetStr,',detail.CostPrice','') 
					When @OrderType2 = 'Profit' then REPLACE(@OutRetStr,',Case When Bill.Red = 2 Then (detail.DiscTotal-detail.GoodsCostTotal) Else (detail.DiscTotal-detail.GoodsCostTotal)*-1 End as Profit','') 
					When @OrderType2 = 'ProfitMargin' then REPLACE(@OutRetStr,',Case detail.DiscTotal when 0 then 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 End as ProfitMargin','') 
					Else @OutRetStr end
--拼接主表查询字段语句					
select  @SqlIn += ' select 201 as BillTypeID,detail.goodsno as BtypeGoodsNo, '+@saleStr+@RedStr
		+' ,detail.UnitID from PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
select @SqlOut += ' select 202 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleRetStr+@RedStr
		+' ,detail.UnitID from PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
--拼接排序后语句字段
Select @SqlInStr += ' Select A.*,'''+'销售出库单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,Summary,Description,detail.Remark ' +@OutStr
		+' from #tempTable A Inner Join PD_SellBill bill On a.BillNo = bill.BillNo INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 201 '
Select @SqlOutStr += ' Select A.*,'''+'销售退货单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 Then detail.BSQty Else detail.BSQty*-1 End as BSQty,Summary,Description,detail.Remark ' +@OutRetStr
		+' from #tempTable A Inner Join PD_SellRetBill bill On a.BillNo = bill.BillNo INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 202 '
if(@IsRedFlag <> 0)
Begin
	select  @SqlIn += '
		Union All
		select 201 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleStr+@RedStr
		+' ,detail.UnitID from PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable	
	select  @SqlIn += '
		Union All
		 select 201 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleRetStr+@RedStr  
		+' ,detail.UnitID from PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 202 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleRetStr+@RedStr  
		+' ,detail.UnitID from PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 202 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleStr+@RedStr  
		+' ,detail.UnitID from PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
End

IF @isHistory=1
Begin
	select  @SqlIn += '
		UNION ALL
	 select 201 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleStr+@RedStr  
		+' ,detail.UnitID from PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0 '  + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End +
		 +@SqlMatch + @GoodsTable
	select @SqlOut += '
		UNION ALL
	 select 202 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleRetStr+@RedStr  
		+' ,detail.UnitID from PD_SellRetBill_his bill INNER JOIN PD_SellRetDetail_his detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=0' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End +
		+@SqlMatch + @GoodsTable
	--拼接排序后语句字段
Select @SqlInStr += ' 
		UNION ALL
		Select A.*,'''+'销售出库单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 then detail.BSQty * -1 else detail.BSQty end BSQty,Summary,Description,detail.Remark ' + @OutStr
		+' from #tempTable A Inner Join PD_SellBill_His bill On a.BillNo = bill.BillNo INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 201 '
Select @SqlOutStr += ' 
		UNION ALL
		Select A.*,'''+'销售退货单' +''' as BillName,bill.DeptID,bill.ElyID,PosElyID,detail.BatchNumber,detail.ProductDate,detail.EndDate
		,detail.WhsID,Creator as CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 as BSUnitID,detail.UnitID,Convfactor,
		Case When Bill.Red = 2 Then detail.BSQty Else detail.BSQty*-1 End as BSQty,Summary,Description,detail.Remark ' +@OutRetStr
		+' from #tempTable A Inner Join PD_SellRetBill_His bill On a.BillNo = bill.BillNo INNER JOIN PD_SellRetDetail_His detail on bill.BillNo = detail.BillNo and a.DID = detail.DID
		where a.BillTypeID = 202 '
  if(@IsRedFlag <> 0)
  Begin
	select  @SqlIn += '
		Union All
		select 201 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleStr+@RedStr    
		+' ,detail.UnitID from PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable	
	select  @SqlIn += '
		Union All
		 select 201 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleRetStr+@RedStr 
		+' ,detail.UnitID from PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 202 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleRetStr+@RedStr   
		+' ,detail.UnitID from PD_SellRetBill_His bill INNER JOIN PD_SellRetDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=1 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
		Union All
		select 202 as BillTypeID,detail.goodsno as BtypeGoodsNo,'+@saleStr+@RedStr    
		+' ,detail.UnitID from PD_SellRetBill_His bill INNER JOIN PD_SellRetDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate And IsDraft = 0 And Red=2 ' + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End + 
		+@SqlMatch + @GoodsTable
  End
End
	
if (@SaleBill = 1)  
begin  
 if(@SaleBackBill = 1)  
 Begin
  Select @Sql += @SqlIn+ ' UNION ALL ' ;  
  Select @outSql += @SqlInStr+ ' UNION ALL ' ;  
 End
 else  
 Begin
  Select @Sql += @SqlIn ;  
  Select @outSql += @SqlInStr ;  
 End
end  
if (@SaleBackBill = 1)  
Begin
 Select @Sql += @SqlOut;  
 Select @outSql += @SqlOutStr;  
End

if (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
Begin
	Set @OrderColumn += ',BT.BTypeCode,BT.BTypeName '
	Set @OrderTable +=' Inner JOIN BD_Btype BT ON bill.BTypeID = BT.BTypeID '
END 
if (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
Begin
	Set @OrderColumn += ',G.GoodsNo,G.GoodsName,G.Model,G.GoodsAbbName,G.Brand,G.Spec,pri.BarCode,bill.BtypeGoodsNo '
	Set @OrderTable +=' Inner JOIN BD_GOODS G on bill.GoodsID = G.GoodsID '
	Set @OrderTable +=' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = bill.GoodsID and pri.UnitID = bill.UnitID  '
END 

SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
),
 PagingData AS
 (
	select '+@pageDataStr+@OrderColumn+@RedStr+'  
		from Bill bill '+@OrderTable
 set @sql +=' )
'

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

---排序字段
IF @OrderType1 <> ''
BEGIN
	IF @OrderSeq1 = 1 SET @OrderName = @OrderType1+' ASC' ELSE SET @OrderName = @OrderType1 +' DESC'
END
IF @OrderType2 <> ''
BEGIN
	IF @OrderName <> '' SET @OrderName +=', '
	IF @OrderSeq2 = 1 SET @OrderName += @OrderType2+' ASC' ELSE SET @OrderName += @OrderType2 +' DESC'
END						

------------------添加参数---------------------------------------
if Not (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
Begin	
	Select @SqlBtype+= ' Inner JOIN BD_Btype B ON Data.BtypeID = B.BtypeID '
	Select @SqlBase +=' ,B.BTypeCode,B.BTypeName '
End
if Not (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
Begin
	Select @SqlGoods+= ' Inner JOIN BD_Goods G ON Data.GoodsID = G.GoodsID '
	Select @SqlGoods+= ' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = Data.GoodsID and pri.UnitID = Data.UnitID '
	Select @SqlBase +=' ,G.GoodsNo,G.GoodsName,G.Model,G.GoodsAbbName,G.Brand,G.Spec,pri.BarCode '
End
if(@AuQtyFlag <> 0)
begin
	Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP1 on Data.GoodsID=BGP1.GoodsID And BGP1.UnitID=1 '
	Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP2 on Data.GoodsID=BGP2.GoodsID And BGP2.UnitID = 2'
	Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP3 on Data.GoodsID=BGP3.GoodsID And BGP3.UnitID = 3'
	Select @SqlBase += ' ,BGP1.Unit as Unit1,BGP1.Convfactor as Convfactor1 '
	Select @SqlBase += ' ,BGP2.Unit as Unit2,case when BGP2.Convfactor IS NULL then 1 else BGP2.Convfactor end as Convfactor2'
	Select @SqlBase += ' ,BGP3.Unit as Unit3,case when BGP3.Convfactor IS NULL then 1 else BGP3.Convfactor end as Convfactor3'
end

SELECT @sql += ',DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderName+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	select * into #tempTable from DATA
	--select * from DATA
	'
select @sql +=' select Data.*,WhsNO,WhsName,DeptCode,DeptName,E.ElyCode,E.ElyName as ElyName,EC.ElyName as Creator,EP.ElyName as PostName,Gpc.Unit,BSGpc.Unit as BSUnit
	,GP1.Value as Ppt1Name,GP2.Value as Ppt2Name '+@SqlBase+'
	 from ('+@outSql+') Data  
	Inner Join BD_Whs W On Data.WhsID = W.WhsID
	Left JOIN BD_Dept D ON Data.DeptID = D.DeptID  
	LEFT JOIN BD_Employee E ON Data.ElyID = E.ElyID 
	LEFT JOIN BD_Employee EC ON Data.CreatorID = EC.ElyID 
	LEFT JOIN BD_Employee EP ON Data.PosElyID = EP.ElyID 
	Inner Join BD_Goods_Price Gpc On Data.UnitID = Gpc.UnitID and Data.GoodsID = Gpc.GoodsID 
	Inner Join BD_Goods_Price BSGpc On Data.BSUnitID = BSGpc.UnitID and Data.GoodsID = BSGpc.GoodsID 
	Left Join BD_Goods_Ppt1 GP1 ON Data.Ppt1ID = GP1.Ppt1ID 
	Left Join BD_Goods_Ppt2 GP2 ON Data.Ppt2ID = GP2.Ppt2ID 
	' + @SqlBtype + @SqlGoods + @SqlAuUnit
select @sql += ' ORDER BY ROWID '
Select @sql += ' drop table #tempTable '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  
--Set @EndDate = CASE WHEN @DateType=0 THEN @EndDate ELSE DATEADD(day,1,@EndDate) END
--insert into #tempTable 

print(@Sql)

exec sp_executesql @Sql,N'@PageNo Int,@PageSize Int,@DateType Int,@BeginDate DateTime,@EndDate DateTime,@OperatorID Int,@ClassID1 Int,@ClassType1 Int,@ClaseFlag1 Int,
			@ClassID2 Int,@ClassType2 Int,@ClaseFlag2 Int,@BTypeID VarChar(MAX),@DeptID1 VarChar(MAX)
			,@ElyID VarChar(MAX),@CreatorID VarChar(MAX),@WhsID VarChar(MAX),@BillCode VarChar(MAX),@FullName VarChar(100),@UserCode VarChar(50),@Ppt1 VarChar(100),@Ppt2 VarChar(100)
			,@Summary VarChar(256),@Description VarChar(100),@Remark VarChar(256)
			,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT
			, @GoodsDataFile1 Varchar(100),@GoodsDataFile2 varchar(100),@GoodsDataFile3 varchar(100),@GoodsDataFile4 varchar(100),@GoodsDataFile5 varchar(100)
			, @BtypeDataFile1 Varchar(100),@BtypeDataFile2 varchar(100),@BtypeDataFile3 varchar(100),@BtypeDataFile4 varchar(100),@BtypeDataFile5 varchar(100)'
			,@PageNo,@PageSize,@DateType,@BeginDate,@EndDate,@OperatorID,@ClassID1,@ClassType1,@ClaseFlag1,@ClassID2,@ClassType2,@ClaseFlag2,
			@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@BillCode,@FullName,
			@UserCode,@Ppt1,@Ppt2,@Summary,@Description,@Remark,
			@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
			,@GoodsDataFile1,@GoodsDataFile2 ,@GoodsDataFile3 ,@GoodsDataFile4 ,@GoodsDataFile5
			,@BtypeDataFile1 ,@BtypeDataFile2 ,@BtypeDataFile3 ,@BtypeDataFile4 ,@BtypeDataFile5  
--select * from #tempTable
			
GO



/****** Object:  StoredProcedure [UP_PD_QuerySaleInvoice]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySaleInvoice]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySaleInvoice]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleInvoice]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：销售单据开票情况查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleInvoice]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@BTypeID VARCHAR(1000)='',		--往来单位
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@BillCode VARCHAR(50)='',		--单据编号
	@BillType INT=9,				--单据类型 9=全部,1=销售出库单,2=销售退货单
	@InvoiceState INT=9,			--开票状态 9=全部,2=已开票,0=未开票,1=部分开票
	@GoodsNoMatch INT = 0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',		--商品编号
	@GoodsNameMatch INT = 0,		--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',	--商品名称
	@SummaryMatch INT = 0,			--摘要配置模式:0=包含,1=等于
	@Summary VARCHAR(100) = '',		--摘要
	@DescriptionMatch INT = 0,		--说明配置模式:0=包含,1=等于
	@Description VARCHAR(100) = '',	--说明
	@PriceStart decimal(20,8),      --单价范围开始
	@PriceEnd  decimal(20,8),       --单价范围结束
	@TotalStart decimal(20,8),      --金额范围开始
	@TotalEnd  decimal(20,8),       --金额范围结束
	@IsShowRed INT=0,				--是否包含红冲数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@ClickFlag INT=0				--是否跳转
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql_SB VARCHAR(450)='',@Sql_SB_His VARCHAR(450)='',@Sql_SRB VARCHAR(450)='',@Sql_SRB_His VARCHAR(450)=''
		,@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@BtypeLimit INT=0,@SqlDetailParam NVARCHAR(MAX)='',@SqlDetailJoin NVARCHAR(MAX)=''
		,@SqlDetailSB NVARCHAR(MAX)='',@SqlDetailSRB NVARCHAR(MAX)='',@SqlDetailSB_His NVARCHAR(MAX)='',@SqlDetailSRB_His NVARCHAR(MAX)=''
IF @BTypeID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BTypeID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
IF @DeptID <> ''
	SET @SqlJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '

SET @SqlParam = '
	WHERE b.IsDraft=0 '
IF @IsShowRed = 0
	SET @SqlParam += '
	AND b.Red=0 '
IF @BillCode <> ''
	SET @SqlParam +='
	AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
	AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
-- 摘要
IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 0
		SET @SqlParam += 'AND b.Summary Like ''%''+@Summary+''%'' '  
	IF @SummaryMatch = 1
		SET @SqlParam += 'AND b.Summary = @Summary '  
END
-- 说明
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 0
		SET @SqlParam += 'AND b.Description Like ''%''+@Description+''%'' '  
	IF @DescriptionMatch = 1
		SET @SqlParam += 'AND b.Description = @Description '  
END


IF @GoodsName <> '' OR @GoodsNo <> ''
BEGIN
	SET @SqlDetailJoin += ' INNER JOIN BD_Goods _goods ON _goods.GoodsID = dtl.GoodsID '
END
-- 商品名称
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsNo Like ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsNo = @GoodsNo '  
END
-- 商品名称
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsName Like ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsName = @GoodsName '  
END
-- 商品单价从--到
IF @PriceEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Price BETWEEN @PriceStart AND @PriceEnd '
END
-- 商品金额从--到
IF @TotalEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Total BETWEEN @TotalStart AND @TotalEnd '
END
IF @GoodsName <> '' OR @GoodsNo <> '' OR @PriceEnd <> 0 OR @TotalEnd <> 0
BEGIN
	SET @SqlDetailSB += '  AND EXISTS (SELECT 1 FROM PD_SellDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailSRB += '  AND EXISTS (SELECT 1 FROM PD_SellRetDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailSB_His += '  AND EXISTS (SELECT 1 FROM PD_SellDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailSRB_His += '  AND EXISTS (SELECT 1 FROM PD_SellRetDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
END
IF @InvoiceState <> 9
BEGIN
	IF @InvoiceState = 2
		SET @SqlParam +='
	AND ABS(b.InvoiceTotal)>=b.Total '
	IF @InvoiceState = 0
		SET @SqlParam +='
	AND b.InvoiceTotal=0 '
	IF @InvoiceState = 1
		SET @SqlParam +='
	AND b.InvoiceTotal<>0 AND ABS(b.InvoiceTotal)<b.Total '
END
SET @SqlParam += ' AND b.IsInvoice = 1 ' --只查询是否开票为是的单据
SET @Sql_SB += '
	SELECT 201[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_SellBill b '
SET @Sql_SRB += '
	SELECT 202[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_SellRetBill b '
SET @Sql_SB_His += '
	SELECT 201[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_SellBill_His b '
SET @Sql_SRB_His += '
	SELECT 202[BillTypeID],b.BillNo,b.BTypeID,b.BillCode,b.BillDate,b.DeptID,b.ElyID
		,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal]
		,b.InvoiceMode,b.Summary,b.[Description],b.Red 
	FROM PD_SellRetBill_His b '
IF @IsHistory = 1
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_SB + @SqlJoin + @SqlParam + @SqlDetailSB + '
	UNION ALL ' + @Sql_SB_His + @SqlJoin + @SqlParam +  @SqlDetailSB_His 
	ELSE IF @BillType = 2
		SET @Sql = @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB + '
	UNION ALL ' + @Sql_SRB_His + @SqlJoin + @SqlParam + @SqlDetailSRB_His
	ELSE
		SET @Sql = @Sql_SB + @SqlJoin + @SqlParam + @SqlDetailSB + '
	UNION ALL ' + @Sql_SB_His + @SqlJoin + @SqlParam + @SqlDetailSB_His + '
	UNION ALL ' + @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB + '
	UNION ALL ' + @Sql_SRB_His + @SqlJoin + @SqlParam + @SqlDetailSRB_His
END
ELSE
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_SB + @SqlJoin + @SqlParam + @SqlDetailSB
	ELSE IF @BillType = 2
		SET @Sql = @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB
	ELSE
		SET @Sql = @Sql_SB  + @SqlJoin + @SqlParam + @SqlDetailSB + '
	UNION ALL ' + @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB
END

SET @Sql = 'IF OBJECT_ID(''tempdb..#tempbo'',''U'') IS NOT NULL DROP TABLE #tempbo 
SET NOCOUNT ON; 
;WITH BillData AS( ' + @Sql + '
)'
SET @Sql += '
SELECT * INTO #tempbo 
FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillCode) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
WHERE B.ROWID>(@PageNo-1)*@PageSize AND B.ROWID<=@PageNo*@PageSize 
SELECT o.*,b1.BTypeName,d.DeptName,e.ElyName
	,CASE WHEN BillTypeID=201 THEN ''销售出库单'' ELSE ''销售退货单'' END[BillType]
	,CASE WHEN InvoiceMode=1 THEN ''按商品开票'' WHEN InvoiceMode=2 THEN ''按单据开票'' ELSE '''' END[InvoiceModeShow]
FROM #tempbo o 
INNER JOIN BD_Btype b1 ON b1.BTypeID = o.BTypeID 
INNER JOIN BD_Dept d ON d.DeptID = o.DeptID 
INNER JOIN BD_Employee e ON e.ElyID = o.ElyID 
ORDER BY o.ROWID 
DROP TABLE #tempbo '

IF @BtypeLimit = 0 
	SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
	
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END

EXEC SP_EXECUTESQL @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@BillCode VARCHAR(50),@OperatorID INT,
						  @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),@SummaryMatch INT, @Summary VARCHAR(100), @DescriptionMatch INT, @Description VARCHAR(100),
						  @PriceStart DECIMAL(20,8),@PriceEnd DECIMAL(20,8), @TotalStart DECIMAL(20,8), @TotalEnd DECIMAL(20,8)',
						  @PageNo,@PageSize,@BillStartDate,@BillEndDate,@BTypeID,@DeptID,@ElyID,@BillCode,@OperatorID,
						  @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName, @SummaryMatch, @Summary, @DescriptionMatch, @Description,
						  @PriceStart, @PriceEnd, @TotalStart, @TotalEnd
END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QuerySaleInvoiceData]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_QuerySaleInvoiceData
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-02-13
	描述：查询销售发票数据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleInvoiceData]
(
	@BillNo DECIMAL(18,0)=0
) 
AS

DECLARE @TableIndex NVARCHAR(100) = '', @TableDetail NVARCHAR(100) = '', @TableContent NVARCHAR(100) = '', @IsHis NVARCHAR(10) = ''
DECLARE @IndexSql NVARCHAR(MAX) = '', @DetailSql NVARCHAR(MAX) = '', @ListSql NVARCHAR(MAX) = '',  @InvoiceMode TINYINT = 1
DECLARE @PSql NVARCHAR(MAX) = '', @PRetSql NVARCHAR(MAX)= '', @P_HisSql NVARCHAR(MAX)= '', @PRet_HisSql NVARCHAR(MAX)=''



IF EXISTS(SELECT 1 FROM MF_SellInvoiceBill_His WHERE BillNo = @BillNo)
BEGIN
	SELECT @InvoiceMode = InvoiceMode FROM MF_SellInvoiceBill_His WHERE BillNo = @BillNo
	SET @IsHis = '_His '
END ELSE
BEGIN
	SELECT @InvoiceMode = InvoiceMode FROM MF_SellInvoiceBill WHERE BillNo = @BillNo
	SET @IsHis = ' '
END

SET @TableIndex = ' MF_SellInvoiceBill'+ @IsHis
SET @TableDetail = ' MF_SellInvoiceDetail' + @IsHis
SET @TableContent = ' MF_SellInvoiceContent' + @IsHis
	
--单据索引
SET @IndexSql = '
SELECT	  TOP 1
		  BillCode ,
		  BillDate ,
		  BillNo,
		  p.BTypeID ,
		  b.BTypeName,
		  p.DeptID ,
		  d.DeptName,
		  p.ElyID ,
		  e.ElyName,
		  InvoiceCode,
		  InvoiceType ,
          InvoiceMode ,
          InvoiceTotal ,
		  Summary ,
		  IsDraft,
		  [Description] ,
		  p.Creator AS CreatorID,
		  e1.ElyName AS CreatorName,
		  e2.ElyName AS PosName
FROM '+ @TableIndex +' p
INNER JOIN BD_Btype b ON p.BtypeID = b.BTypeID
INNER JOIN BD_Employee e ON p.ElyID = e.ElyID
LEFT  JOIN BD_Employee e1 ON p.Creator=e1.ElyID
LEFT  JOIN BD_Employee e2 ON p.PosElyID=e2.ElyID
INNER JOIN BD_Dept d ON e.DeptId = d.DeptId
WHERE BillNo= @BillNo '

--单据明细
IF @InvoiceMode = 1
BEGIN
	SET @PSql = '
		SELECT SD.BillNo ,		SellBillNo ,			SB.BillCode,	SB.BillDate,
           SB.Summary,	SB.Description,	SD.SellDID ,			PSD.GoodsID,	P.GoodsNo,
           P.GoodsName,	PSD.Ppt1ID,		P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,
           PSD.Qty,		PSD.Total,		PSD.Price,				PSD.UnitID,		GP.Unit,
           SD.BillType,	SD.InvoiceQty ,	SD.InvoiceTotal ,
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty - ISNULL(PY.YInvoiceQty, 0) AS NInvoiceQty,
           PSD.Total - ISNULL(PY.YInvoiceTotal, 0)  AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellBill SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_SellDetail PSD ON SD.SellDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT SellDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal 
				FROM '+ @TableDetail +'  D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
				GROUP BY SellDID
				) PY ON PY.SellDID = SD.SellDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 201
	'
	SET @PRetSql = '
	SELECT SD.BillNo ,						SellBillNo ,			SB.BillCode,	SB.BillDate,
           SB.Summary,			SB.Description,			SD.SellDID ,			PSD.GoodsID,	P.GoodsNo,
           P.GoodsName,			PSD.Ppt1ID,				P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,
           PSD.Qty*(-1) AS Qty,	PSD.Total*(-1) AS Total,PSD.Price,				PSD.UnitID,		GP.Unit,
           SD.BillType,			SD.InvoiceQty ,			SD.InvoiceTotal ,
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty*(-1) - ISNULL(PY.YInvoiceQty,0)  AS NInvoiceQty,
           PSD.Total*(-1) - ISNULL(PY.YInvoiceTotal,0) AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellRetBill SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_SellRetDetail PSD ON SD.SellDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT SellDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal 
				FROM '+ @TableDetail +'  D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
				GROUP BY SellDID
				) PY ON PY.SellDID = SD.SellDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 202
	'
	SET @P_HisSql = '
	SELECT SD.BillNo ,		SellBillNo ,			SB.BillCode,	SB.BillDate,
           SB.Summary,	SB.Description,	SD.SellDID ,			PSD.GoodsID,	P.GoodsNo,
           P.GoodsName,	PSD.Ppt1ID,		P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,
           PSD.Qty,		PSD.Total,		PSD.Price,				PSD.UnitID,		GP.Unit,
           SD.BillType,	SD.InvoiceQty ,	SD.InvoiceTotal ,
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty - ISNULL(PY.YInvoiceQty, 0) AS NInvoiceQty,
           PSD.Total - ISNULL(PY.YInvoiceTotal, 0)  AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellBill_His SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_SellDetail_His PSD ON SD.SellDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT SellDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal 
				FROM '+ @TableDetail +'  D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
				GROUP BY SellDID
				) PY ON PY.SellDID = SD.SellDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 201
	'
	
	SET @PRet_HisSql = '
	SELECT SD.BillNo ,						SellBillNo ,			SB.BillCode,	SB.BillDate,
           SB.Summary,			SB.Description,			SD.SellDID ,			PSD.GoodsID,	P.GoodsNo,
           P.GoodsName,			PSD.Ppt1ID,				P1.Value AS Ppt1Name,	PSD.Ppt2ID,		P2.Value AS Ppt2Name,
           PSD.Qty*(-1) AS Qty,	PSD.Total*(-1) AS Total,PSD.Price,				PSD.UnitID,		GP.Unit,
           SD.BillType,			SD.InvoiceQty ,			SD.InvoiceTotal ,
           ISNULL(PY.YInvoiceQty, 0)  AS YInvoiceQty,
           ISNULL(PY.YInvoiceTotal, 0)  AS YInvoiceTotal,
           PSD.Qty*(-1) - ISNULL(PY.YInvoiceQty,0)  AS NInvoiceQty,
           PSD.Total*(-1) - ISNULL(PY.YInvoiceTotal,0) AS NInvoiceTotal,
           SD.Remark
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellRetBill_His SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_SellRetDetail_His PSD ON SD.SellDID = PSD.DID
    INNER JOIN BD_Goods P ON PSD.GoodsID = P.GoodsID
    LEFT JOIN BD_Goods_Ppt1 P1 ON PSD.Ppt1ID = P1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 P2 ON PSD.Ppt2ID = P2.Ppt2ID
    INNER JOIN BD_Goods_Price GP ON PSD.GoodsID = GP.GoodsID AND PSD.UnitID = GP.UnitID
    LEFT JOIN (SELECT SellDID, SUM(InvoiceQty) AS YInvoiceQty, SUM(D.InvoiceTotal) AS YInvoiceTotal 
				FROM '+ @TableDetail +'  D 
				INNER JOIN '+ @TableIndex +' I
				ON D.BillNo = I.BillNo WHERE I.IsDraft = 0 	
				GROUP BY SellDID
				) PY ON PY.SellDID = SD.SellDID  
	WHERE SD.BillNo = @BillNo AND SD.BillType = 202
	'
	SET @DetailSql =  @PSql +' UNION ALL '+ @PRetSql +' UNION ALL '+@P_HisSql +' UNION ALL '+ @PRet_HisSql
END ELSE
IF @InvoiceMode = 2
BEGIN
	SET @DetailSql = '
		SELECT BillNo ,
           BillDate ,
           GoodsMsg ,
           InvoiceTotal ,
           Remark
    FROM '+ @TableContent +' WHERE BillNo = @BillNo
	'
	
	SET @ListSql = '
	SELECT SD.BillNo ,
           SB.BillDate ,
           SellBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           SellDID ,
           SD.BillType,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellBill SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 201
	UNION ALL
	SELECT SD.BillNo ,
           SB.BillDate ,
           SellBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           SellDID ,
           SD.BillType,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total*(-1) AS Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total*(-1) - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellRetBill SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 202
	UNION ALL
	SELECT SD.BillNo ,
           SB.BillDate ,
           SellBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           SellDID ,
           SD.BillType,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellBill_His SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 201
	UNION ALL
	SELECT SD.BillNo ,
           SB.BillDate ,
           SellBillNo ,
           SB.BillCode,
           SB.BillDate,
           SB.Summary,
           SB.Description,
           SellDID ,
           SD.BillType,
           BT.BillName,
           SD.InvoiceTotal ,
           Remark,
           SB.Total*(-1) AS Total,
           SB.InvoiceTotal AS YInvoiceTotal,
           SB.Total*(-1) - SB.InvoiceTotal AS NInvoiceTotal
    FROM '+ @TableDetail +' SD
    INNER JOIN PD_SellRetBill_His SB ON SD.SellBillNo = SB.BillNo
    INNER JOIN PD_BillType BT ON SD.BillType = BT.BillTypeID
	WHERE SD.BillNo = @BillNo AND SD.BillType = 202
	'
END ELSE
IF @InvoiceMode = 3
BEGIN
	SET @DetailSql = '
	SELECT BillNo ,
           BillDate ,
           GoodsMsg ,
           InvoiceTotal ,
           Remark
    FROM '+ @TableContent +' WHERE BillNo = @BillNo
	'
END

--PRINT (@DetailSql)
exec sp_executesql @IndexSql , N'@BillNo INT', @BillNo
exec sp_executesql @DetailSql , N'@BillNo INT', @BillNo
exec sp_executesql @ListSql, N'@BillNo INT', @BillNo
GO




/****** Object:  StoredProcedure [UP_PD_QuerySaleInvoiceDetail]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySaleInvoiceDetail]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySaleInvoiceDetail]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleInvoiceDetail]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：销售单据开票情况查询(明细)
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleInvoiceDetail]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillNo BIGINT=0,				--单据编号
	@BillTypeID INT=101				--单据类型
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@Sql0 NVARCHAR(MAX)='',@Sql1 NVARCHAR(MAX)='',@Sql2 NVARCHAR(MAX)='',@TableName VARCHAR(20)='',@HisStr VARCHAR(20)='_His'
		,@Sqla NVARCHAR(MAX),@Sqlb NVARCHAR(MAX),@Sqlc NVARCHAR(MAX),@Sqld NVARCHAR(MAX)
IF EXISTS (SELECT 1 FROM MF_SellInvoiceDetail dtl WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql1='
		SELECT dtl.SellBillNo,dtl.SellDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_SellInvoiceDetail dtl
		WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY SellBillNo,SellDID,BillType '
IF EXISTS (SELECT 1 FROM MF_SellInvoiceDetail_His dtl WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql2='
		SELECT dtl.SellBillNo,dtl.SellDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_SellInvoiceDetail_His dtl
		WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY SellBillNo,SellDID,BillType '
IF @Sql1<>'' AND @Sql2<>''
	SET @Sql0 = @Sql1 +'
		UNION ALL ' + @Sql2
ELSE IF @Sql1<>'' AND @Sql2='' SET @Sql0 = @Sql1
ELSE IF @Sql1='' AND @Sql2<>'' SET @Sql0 = @Sql2
IF @BillTypeID = 201
BEGIN
	SET @TableName = 'PD_SellDetail'
	IF EXISTS (SELECT 1 FROM PD_SellDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='
;WITH PagingData AS 
( 
	SELECT dtl.DID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,dtl.Qty,dtl.UnitID,dtl.TaxTotal,pidtl.InvoiceQty,dtl.Qty-pidtl.InvoiceQty[NoInvoiceQty],pidtl.InvoiceTotal,dtl.TaxTotal-ISNULL(pidtl.InvoiceTotal,0)[NoInvoiceTotal],dtl.Remark 
	FROM '+@TableName+@HisStr+' dtl 
	LEFT JOIN ( '+@Sql0+'
	) AS pidtl ON SellBillNo = dtl.BillNo AND pidtl.SellDID = dtl.DID AND BillType=@BillTypeID 
	WHERE dtl.BillNo=@BillNo 
) '
END
ELSE
BEGIN
	SET @TableName = 'PD_SellRetDetail'
	IF EXISTS (SELECT 1 FROM PD_SellRetDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='
;WITH PagingData AS 
( 
	SELECT dtl.DID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,dtl.Qty*-1[Qty],dtl.UnitID,dtl.TaxTotal*-1[TaxTotal],pidtl.InvoiceQty,dtl.Qty*-1-pidtl.InvoiceQty[NoInvoiceQty],pidtl.InvoiceTotal,dtl.TaxTotal*-1-ISNULL(pidtl.InvoiceTotal,0)[NoInvoiceTotal],dtl.Remark 
	FROM '+@TableName+@HisStr+' dtl 
	LEFT JOIN ( '+@Sql0+'
	) AS pidtl ON SellBillNo = dtl.BillNo AND pidtl.SellDID = dtl.DID AND BillType=@BillTypeID 
	WHERE dtl.BillNo=@BillNo 
) '
END

/***********定义要关联的基础资料sql***********/
SET @Sqla=N'SELECT GoodsID[G1ID],GoodsNo,GoodsName,Spec,Model FROM BD_Goods'
SET @Sqlb=N'SELECT Ppt1ID[P1ID],Value[Ppt1Name] FROM BD_Goods_Ppt1'
SET @Sqlc=N'SELECT Ppt2ID[P2ID],Value[Ppt2Name] FROM BD_Goods_Ppt2'
SET @Sqld=N'SELECT GoodsID[G2ID],UnitID[UID],Unit FROM BD_Goods_Price'

DECLARE @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillNo','BIGINT',@BillNo)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillTypeID','INT',@BillTypeID)

/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsID=_DATA_a.G1ID',@Sqla)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_b','Data.Ppt1ID=_DATA_b.P1ID',@Sqlb)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_c','Data.Ppt2ID=_DATA_c.P2ID',@Sqlc)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_d','Data.GoodsID=_DATA_d.G2ID AND Data.UnitID=_DATA_d.UID',@Sqld)

EXEC UP_OT_Paging @Sql,@TVP,@PageNo,@PageSize,'DID','','',1,0

GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2015-2-10
	描述：查询销售开票明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleInvoiceStatistical]
(
	@PageNo INT=0,
	@PageSize INT=0,
	--@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillType Int=0,  --单据类型
	@BTypeID VARCHAR(max)='',
	@OrderType1 Varchar(100)='BTypeCode',	--排序条件
	@OrderSeq1 Int=1,  --排序类型 1=升序，2=降序
	@IsManual INT=0,  --是否勾选手工开票单独列示
	@IsRedFlag INT=0,				--是否包含红冲单据数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID Int=0
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;
set @OrderType1 = isnull(@OrderType1,'')	
if(@OrderType1='')
Begin
	Set @OrderType1='BTypeCode'
End


DECLARE @Sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',
		@OrderName nvarchar(100)='', @LimitBtypeSql NVARCHAR(MAX) = '',@OutStr varchar(max)='',@outRetStr varchar(max)=''
		,@outSql varchar(max)='',@BtypeLimit INT=0,@RedStr varchar(100)=''
		,@InvoiceSql varchar(max)='',@InvoiceModeSql varchar(max)='',@InvoiceOutModeSql varchar(Max)=''
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
--SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
--IF @KtypeLimit = 1
--Begin
--	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
--	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
--End
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
if @IsRedFlag = 0
	select @RedStr = ' And Red=0 '
SET @RedStr += ' AND IsInvoice = 1 ' --只查询是否开票为是的单据
---------------计算单据金额列信息----------------
Select @OutStr +=' select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
Select @outRetStr +=' select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellRetBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
select @InvoiceSql += ' select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_SellInvoiceBill bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0 group by BTypeID'
if @IsHistory = 1
begin
	Select @OutStr +='
		Union All
		 select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	Select @outRetStr +=' 
		Union All
		select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellRetBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	select @InvoiceSql += '
		Union All
	 select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_SellInvoiceBill_His bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0  group by BTypeID'
end
if @BillType = 0
	Select @Sql += @OutStr + ' Union All ' + @outRetStr
else if @BillType =1
	Select @Sql += @OutStr 
else
	Select @Sql += @outRetStr 
-----------拼接排序条件-----------------
select @OrderName += @OrderType1 + Case when @OrderSeq1 = 2 then ' Desc ' else ' ' end
-----------不同的显示方式计算未结金额和超额金额-----------
if @IsManual = 1 
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal2,SUM(UserTotal1) as UserTotal2,sum(Total) - sum(BillTotal1) as NoInvoiceTotal '
	Select @InvoiceOutModeSql +=' data.BtypeID,Total,BillTotal2,UserTotal2,NoInvoiceTotal'
End
else
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal1,SUM(UserTotal1) as UserTotal1,
					sum(Total) - sum(BillTotal1) - SUM(UserTotal1) as NoInvoiceTotal,sum(BillTotal1) + SUM(UserTotal1)- sum(Total) as OutInvoiceTotal '
	Select @InvoiceOutModeSql +=' data.BtypeID,Total,BillTotal1,UserTotal1,
								case when total >= 0 then (case when NoInvoiceTotal<=0 then 0 else NoInvoiceTotal end) else (case when NoInvoiceTotal > 0 then 0 else NoInvoiceTotal end) end as NoInvoiceTotal
								,case When total >= 0 then (Case When OutInvoiceTotal <=0 then 0 else OutInvoiceTotal end) Else (Case When OutInvoiceTotal >= 0 then 0 else OutInvoiceTotal end) End as OutInvoiceTotal'
End
	
SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
),BillTotal as(
	Select BTypeID,sum(Total) as Total,sum(InvoiceTotal) as BillTotal1,0 as UserTotal1 from Bill Group By BTypeID
),InvoiceTotal as(
' +@InvoiceSql+ '
),AllData AS
 (
	select BTypeID,Total,BillTotal1,UserTotal1 from BillTotal
	Union All
	select BTypeID,Total,BillTotal1,UserTotal1 from InvoiceTotal
 ),PagingData AS(
	Select AD.BTypeID,B.BTypeCode,B.BTypeName,sum(Total) as Total '+@InvoiceModeSql+' 
	from AllData Ad Inner Join BD_Btype B on Ad.BTypeID = B.BtypeID Group By Ad.BTypeID,B.BtypeCode,B.BTypeName
 )
'


IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

------------------添加参数---------------------------------------

SELECT @sql += ',DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderName+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	'
select @sql +=' select [ROWCOUNT],ROWID,'+@InvoiceOutModeSql+',BTypeCode,BTypeName
	 from DATA data '
select @sql += ' ORDER BY ROWID '
IF @BtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Btype WHERE 1 <> 1'
DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
exec sp_executesql @Sql,N'@PageNo Int,@PageSize Int,@BeginDate Date,@EndDate Date,@OperatorID Int,@BTypeID VarChar(MAX)'
			,@PageNo,@PageSize,@BeginDate,@EndDate,@OperatorID,@BTypeID

GO



/****** Object:  StoredProcedure [UP_PD_QuerySaleOrderDetail]    Script Date: 07/01/2014 15:11:36 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('[UP_PD_QuerySaleOrderDetail]') AND TYPE IN ('P', 'PC'))
	DROP PROCEDURE [UP_PD_QuerySaleOrderDetail]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleOrderDetail]    Script Date: 07/28/2014 11:08:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-30
	描述：销售订单明细查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleOrderDetail]
(
     @PageNo INT = 0,						--页码
     @PageSize INT = 0,						--页大小
	 @BillDateType INT = 1,					--日期类型 1=录单日期,2=制单日期
	 @BillStartDate DATETIME,				--开始日期
	 @BillEndDate DATETIME,					--结束日期
     @BillCodeMatch INT = 0,				--单据编号匹配方式:0=包含,1=等于
     @BillCode VARCHAR(100) = '',			--单据编号
	 @BTypeID VARCHAR(1000) = '',			--往来单位
	 @DeptID VARCHAR(1000) = '',			--部门
	 @ElyID VARCHAR(1000) = '',				--经手人
	 @WhsID VARCHAR(1000) = '',				--仓库
	 @GoodsNoMatch INT=0,					--商品编号配置模式:0=包含,1=等于
	 @GoodsNo VARCHAR(50) = '',				--商品编号
	 @GoodsNameMatch INT=0,					--商品名称配置模式:0=包含,1=等于
	 @GoodsName VARCHAR(100) = '',			--商品名称
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	 @Ppt1Match INT=0,						--属性1配置模式:0=包含,1=等于
	 @Ppt1 VARCHAR(10) = '',				--属性1
	 @Ppt2Match INT=0,						--属性2配置模式:0=包含,1=等于
	 @Ppt2 VARCHAR(10) = '',				--属性2
	 @SummaryMatch INT=0,					--摘要配置模式:0=包含,1=等于
	 @Summary VARCHAR(256) = '',			--摘要
	 @DescriptionMatch INT=0,				--说明配置模式:0=包含,1=等于
	 @Description VARCHAR(100) = '',		--说明
	 @RemarkMatch INT=0,					--明细备注配置模式:0=包含,1=等于
	 @Remark VARCHAR(100) = '',				--明细备注
	 @GiftStt INT = 1,						--赠品状态 9=全部,1=是,0=否
	 @Stt_1 BIT = 1,						--订单状态 未调用
	 @Stt_2 BIT = 1,						--订单状态 部分调用
	 @Stt_3 BIT = 1,						--订单状态 已完成
	 @StopTag INT = 1,						--中止状态 9=全部,1=已中止,0=未中止
	 @OrderStr VARCHAR(50) = '',			--排序字符串
	 @IsHistory INT=0,						--是否包含历史数据
	 @OperatorID INT = 0,					--操作员ID
-----------------------以下参数在由销售订单汇总查看明细时用到----------------------------
	 @GoodsTypeID_mx INT = 0,					--商品分类ID
	 @GoodsID_mx INT = 0,						--商品ID
	 @BtypeTypeID_mx INT = 0,					--往来单位分类ID
	 @BTypeID_mx INT = 0,						--往来单位ID
	 @WhsTypeID_mx INT = 0,						--仓库分类ID
	 @WhsID_mx INT = 0,							--仓库ID
	 @AreaID_mx INT = 0,						--地区ID
	 @DeptID_mx INT = 0,						--部门ID
	 @ElyID_mx INT = 0							--职员ID
------------------------------------------------------------------------------------------
   ) 
AS
SET NOCOUNT ON
BEGIN

	DECLARE @Re INT 
	EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
	IF( @Re=1 )RETURN @Re;
	
	DECLARE @HeadSql NVARCHAR(2000)='',
			@HeadSql_His NVARCHAR(2000)='',
			@Sql NVARCHAR(MAX)='',@SqlParam VARCHAR(1000)='',@DataSql VARCHAR(2000)='',@BaseSql VARCHAR(2000)='',
			@BtypeLimit INT=0,@KtypeLimit INT=0
    DECLARE @TVP_Com AS [TVP_Type] 
    DECLARE @TVP_Depart AS [TVP_Type] 
    SET @HeadSql = 'SELECT ord.BillNo, ord.BillCode, ord.BTypeID, ord.DeptID, ord.ElyID, ord.WhsID, ord.BillDate
					       , ord.CreateTime, ord.Creator AS CreatorID, ord.Summary, ord.[Description]
					       , detail.DID, detail.Ppt1ID, detail.Ppt2ID, detail.GoodsID, detail.Gift 
					       , detail.UnitID, detail.BSQty, detail.ComQty, detail.ComTotal, detail.TaxPrice, detail.TaxTotal, detail.Remark 
					       , detail.StopTag, goods.GoodsNo, goods.GoodsName, creator.ElyName AS Creator
					       , btype.BTypeCode, btype.BTypeName,detail.goodsno as BtypeGoodsNo '
						 
			SET @Sql += 'INNER JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID 
						 LEFT JOIN BD_Employee creator ON creator.ElyID = ord.Creator 
						 INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID '
	
    IF @BillDateType = 1
       SET @SqlParam = 'WHERE detail.BillDate BETWEEN @BillStartDate AND @BillEndDate  And ord.IsDraft = 0 '
    ELSE
       SET @SqlParam = 'WHERE ord.CreateTime BETWEEN @BillStartDate AND @BillEndDate  And ord.IsDraft = 0 '
       
    IF @BTypeID <> '' AND @BTypeID_mx = 0	--往来单位
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = ord.BTypeID '
	   
    IF @DeptID <> '' AND @DeptID_mx = 0		--部门
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Depart _dept ON _dept.ChildTypeID = ord.DeptID '
		INSERT INTO @TVP_Depart([TypeID],[ChildTypeID]) 
		SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
		INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	END
	   
    IF @ElyID <> '' AND @ElyID_mx = 0		--经手人
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = ord.ElyID '
	   
    IF @WhsID <> '' AND @WhsID_mx = 0		--仓库
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = ord.WhsID '
	/*权限使用公用方法*/
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
	IF( @BtypeLimit=1 ) --部份权限
		SET @Sql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=ord.BTypeID '
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF( @KtypeLimit=1 ) --部份权限
		SET @Sql += 'INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=ord.WhsID '
	/*权限使用非公用方法*/
	/*
	IF @OperatorID <> 1 
	BEGIN
		IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
		BEGIN
			SET @Sql +='
			INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=ord.BTypeID '
		END
		IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
		BEGIN
			SET @Sql +='
			INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=ord.WhsID '
		END
	END
	*/

	-----------------------以下参数在由销售订单汇总查看明细时用到----------------------------
    IF @GoodsTypeID_mx <> 0		--商品分类
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Com _goodsType ON _goodsType.ChildTypeID = goods.GoodsTypeID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM  BD_Goods_Type gt
		INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
	    WHERE gt.GoodsTypeID = @GoodsTypeID_mx AND cgt.SonNum = 0
	END
    IF @GoodsID_mx <> 0			--商品
		SET @SqlParam += 'AND detail.GoodsID=@GoodsID_mx '
    IF @BtypeTypeID_mx <> 0		--往来单位分类
	BEGIN
		SET @Sql +=' INNER JOIN @TVP_Com _btypeType ON _btypeType.ChildTypeID = btype.BtypeTypeID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT bt.BtypeTypeID, cbt.BtypeTypeID FROM BD_Btype_Type bt       
		INNER JOIN BD_Btype_Type cbt ON cbt.[Path] Like bt.[Path] + '%'
		WHERE bt.BtypeTypeID = @BtypeTypeID_mx AND cbt.SonNum = 0
	END
    IF @BTypeID_mx <> 0			--往来单位
		SET @SqlParam += 'AND ord.BTypeID=@BTypeID_mx '
    IF @WhsTypeID_mx <> 0		--仓库分类
	BEGIN
		SET @Sql +=' INNER JOIN @TVP_Com _whsType ON _whsType.ChildTypeID = ord.WhsID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT cwt.WhsTypeID, w.WhsID FROM BD_Whs w
		INNER JOIN BD_Whs_Type cwt ON w.WhsTypeID = cwt.WhsTypeID         
		INNER JOIN BD_Whs_Type wt ON cwt.[Path] Like wt.[Path] + '%'
		WHERE wt.WhsTypeID = @WhsTypeID_mx AND cwt.SonNum = 0
	END
    IF @WhsID_mx <> 0			--仓库
		SET @SqlParam += 'AND ord.WhsID=@WhsID_mx '
	IF @AreaID_mx <> 0			--地区
	BEGIN
		SET @Sql +=' INNER JOIN @TVP_Com _area ON _area.ChildTypeID = btype.AreaID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT a.AreaID, ca.AreaID FROM BD_Area a
		INNER JOIN BD_Area ca ON ca.[Path] Like a.[Path] + '%'
		WHERE a.AreaID = @AreaID_mx AND ca.SonNum = 0
	END
    IF @DeptID_mx <> 0			--部门
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Com _dept ON _dept.ChildTypeID = ord.DeptID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
		INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		WHERE d.DeptID=@DeptID_mx AND cd.SonNum = 0
	END
    IF @ElyID_mx <> 0			--职员
		SET @SqlParam += 'AND ord.ElyID=@ElyID_mx '
	------------------------------------------------------------------------------------------
	
	IF @BillCode <> ''   --单据编号
	BEGIN 
		IF @BillCodeMatch = 0
			SET @SqlParam += 'AND ord.BillCode LIKE ''%''+@BillCode+''%'' '
		IF @BillCodeMatch = 1
			SET @SqlParam += 'AND ord.BillCode=@BillCode ' 
	END
	
	IF @GoodsTypeID_mx = 0 AND @GoodsID_mx = 0   --有商品分类和商品ID，条件就不用重复筛选了。
	BEGIN
		IF @GoodsNo <> ''		--商品编号 
		BEGIN
			IF @GoodsNoMatch=0 SET @SqlParam += 'AND goods.GoodsNo LIKE ''%''+@GoodsNo+''%'' '
			IF @GoodsNoMatch=1 SET @SqlParam += 'AND goods.GoodsNo=@GoodsNo '
		END
		IF @GoodsName <> ''		--商品名称 
		BEGIN
			IF @GoodsNameMatch=0 SET @SqlParam += 'AND goods.GoodsName LIKE ''%''+@GoodsName+''%'' '
			IF @GoodsNameMatch=1 SET @SqlParam += 'AND goods.GoodsName=@GoodsName '
		END
		
		IF @Model <> ''      --商品型号
		BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
		END       
		IF @GoodsAbbName <> ''    --商品简名
		BEGIN 
		   IF @GoodsAbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
		   ELSE IF @GoodsAbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
		END       
		IF @Brand <> ''      --商品品牌
		BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
		END
		--商品规格    
		IF @Spec <> ''        
		BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
		END
		--商品条码
		IF @BarCode <> ''      
		BEGIN 
		   SET @Sql += ' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID AND pri.UnitID = 1 '
		   
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=detail.GoodsID) '
		   ELSE IF @BarCodeMatch = 1 
	           SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=detail.GoodsID)'
		END
		
		IF @Ppt1 <> ''			--属性一 
		BEGIN 
			SET @Sql += ' INNER JOIN BD_Goods_Ppt1 ppt1 ON detail.Ppt1ID = ppt1.Ppt1ID  '
			IF @Ppt1Match=0 SET @SqlParam += 'AND ppt1.Value LIKE ''%''+@Ppt1+''%'' '
			IF @Ppt1Match=1 SET @SqlParam += 'AND ppt1.Value=@Ppt1 ' 
		END 
		   
		IF @Ppt2 <> ''			--属性二
		BEGIN 
			SET @Sql += ' INNER JOIN BD_Goods_Ppt2 ppt2 ON detail.Ppt2ID = ppt2.Ppt2ID  '
			IF @Ppt2Match=0 SET @SqlParam += 'AND ppt2.Value LIKE ''%''+@Ppt2+''%'' '
			IF @Ppt2Match=1 SET @SqlParam += 'AND ppt2.Value=@Ppt2 ' 
		END 
	       							
		IF @Summary <> ''		--摘要
		BEGIN
			IF @SummaryMatch=0 SET @SqlParam += 'AND ord.Summary LIKE ''%''+@Summary+''%'' '
			IF @SummaryMatch=1 SET @SqlParam += 'AND ord.Summary=@Summary '
		END
		   
		IF @Description <> ''	--说明
		BEGIN
			IF @DescriptionMatch=0 SET @SqlParam += 'AND ord.[Description] LIKE ''%''+@Description+''%'' '
			IF @DescriptionMatch=1 SET @SqlParam += 'AND ord.[Description]=@Description '
		END
	       							
		IF @Remark <> ''		--明细备注
		BEGIN
			IF @RemarkMatch=0 SET @SqlParam += 'AND detail.Remark LIKE ''%''+@Remark+''%'' '
			IF @RemarkMatch=1 SET @SqlParam += 'AND detail.Remark=@Remark '
		END
	END

    IF @GiftStt <> 9			--赠品 
       SET @SqlParam += 'AND detail.Gift = @GiftStt '
       
	--IF @Stt_1 <> 1 OR @Stt_2 <> 1 OR @Stt_3 <> 1   --订单状态 未调用 部分调用 已完成
	--BEGIN
	--	IF @Stt_1 = 1
	--		SET @SttParam += 'OR (detail.ComQty = 0 AND detail.StopTag <> 1) '
	--	IF @Stt_2 = 1
	--		SET @SttParam += 'OR (detail.ComQty > 0 AND detail.ComQty < detail.BSQty AND detail.StopTag <> 1) '
	--	IF @Stt_3 = 1
	--		SET @SttParam += 'OR (detail.ComQty >= detail.BSQty OR detail.StopTag = 1) '
	--	SET @SqlParam += 'AND ( ' + SUBSTRING(@SttParam, 4, LEN(@SttParam) - 3) + ' ) '
	--END
	
	IF @Stt_1 <> 1 OR @Stt_2 <> 1 OR @Stt_3 <> 1   --订单状态 未调用 部分调用 已完成
	BEGIN
		IF @Stt_1 = 1 AND @Stt_2 = 1 AND @Stt_3 = 1
			SET @SqlParam += ''
		ELSE
		BEGIN
			IF @Stt_1 = 1 AND @Stt_2 = 1 AND @Stt_3 <> 1	--勾选：未调用和部分调用
				SET @SqlParam += 'AND NOT (detail.ComQty >= detail.BSQty OR detail.StopTag = 1) '
			IF @Stt_1 = 1 AND @Stt_2 <> 1 AND @Stt_3 = 1	--勾选：未调用和已完成
				SET @SqlParam += 'AND NOT (detail.ComQty > 0 AND detail.ComQty < detail.BSQty AND detail.StopTag <> 1) '
			IF @Stt_1 <> 1 AND @Stt_2 = 1 AND @Stt_3 = 1	--勾选：部分调用和已完成
				SET @SqlParam += 'AND NOT (detail.ComQty = 0 AND detail.StopTag <> 1) '
			IF @Stt_1 = 1 AND @Stt_2 <> 1 AND @Stt_3 <> 1	--勾选：未调用
				SET @SqlParam += 'AND (detail.ComQty = 0 AND detail.StopTag <> 1) '
			IF @Stt_1 <> 1 AND @Stt_2 = 1 AND @Stt_3 <> 1	--勾选：部分调用
				SET @SqlParam += 'AND (detail.ComQty > 0 AND detail.ComQty < detail.BSQty AND detail.StopTag <> 1) '
			IF @Stt_1 <> 1 AND @Stt_2 <> 1 AND @Stt_3 = 1	--勾选：已完成
				SET @SqlParam += 'AND (detail.ComQty >= detail.BSQty OR detail.StopTag = 1) '
		END
	END
	
	IF @StopTag <> 9 
		SET @SqlParam += 'AND detail.StopTag = @StopTag '
       
    SET @BaseSql += ',_DATA_Price AS (SELECT GoodsID AS GoodsID1, UnitID AS UnitID1, Unit,BarCode FROM BD_Goods_Price)
					  ,_DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName FROM BD_Dept)
					  ,_DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName FROM BD_Employee)
                      ,_DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName FROM BD_Whs)
                      ,_DATA_Ppt1 AS (SELECT Ppt1ID AS _Ppt1ID, Value AS Ppt1Name FROM BD_Goods_Ppt1)
                      ,_DATA_Ppt2 AS (SELECT Ppt2ID AS _Ppt2ID, Value AS Ppt2Name FROM BD_Goods_Ppt2)
                      ,_DATA_Goods AS (SELECT GoodsID AS GoodsID,Spec,Model,GoodsAbbName,Brand FROM BD_Goods)'
                   
    --SET @DataSql += 'LEFT JOIN _DATA_Price ON Data.GoodsID = _DATA_Price.GoodsID1 AND _DATA_Price.UnitID1 = Data.UnitID
	SET @DataSql += 'LEFT JOIN _DATA_Price ON Data.GoodsID = _DATA_Price.GoodsID1 AND _DATA_Price.UnitID1 = 1
					 LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID
					 LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID 
					 LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID 
					 LEFT JOIN _DATA_Ppt1 ON Data.Ppt1ID = _DATA_Ppt1._Ppt1ID
					 LEFT JOIN _DATA_Ppt2 ON Data.Ppt2ID = _DATA_Ppt2._Ppt2ID
					 LEFT JOIN _DATA_Goods ON Data.GoodsID = _DATA_Goods.GoodsID'
					 
	IF @IsHistory=0
		SET @Sql = ';With PagingData AS ( ' + @HeadSql + 'FROM PD_SellOrdDetail detail INNER JOIN PD_SellOrdBill ord ON detail.BillNo = ord.BillNo ' + @Sql + @SqlParam + ')' + @BaseSql + 
			   ',DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
						  CROSS JOIN
						 (SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM PagingData ) B
						    WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				   SELECT * FROM DATA ' + @DataSql + ' ORDER BY ROWID'
	ELSE
		SET @Sql = ';With PagingData AS ( ' + @HeadSql 
					+ 'FROM PD_SellOrdDetail detail INNER JOIN PD_SellOrdBill ord ON detail.BillNo = ord.BillNo '
					+ @Sql 
					+ @SqlParam 
					+ 'UNION ALL '
					+ @HeadSql 
					+ 'FROM PD_SellOrdDetail_His detail INNER JOIN PD_SellOrdBill_His ord ON detail.BillNo = ord.BillNo '
					+ @Sql 
					+ @SqlParam +')' + @BaseSql + 
			   ',DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData ) A 
						  CROSS JOIN
						 (SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM PagingData ) B
						    WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				   SELECT * FROM DATA ' + @DataSql + ' ORDER BY ROWID'
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END 
	EXEC sp_executesql @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate DATETIME,@BillEndDate DATETIME,@BillCode VARCHAR(100)
	,@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsNo VARCHAR(50),
	@GoodsName VARCHAR(100), @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT,
	@Ppt1 VARCHAR(10),@Ppt2 VARCHAR(10),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@GiftStt INT
	,@StopTag INT,@OperatorID INT,@GoodsTypeID_mx INT, @GoodsID_mx INT, @BtypeTypeID_mx INT, @BTypeID_mx INT, @WhsTypeID_mx INT, @WhsID_mx INT, @AreaID_mx INT, @DeptID_mx INT, @ElyID_mx INT,@TVP_Com TVP_Type READONLY,@TVP_Depart TVP_Type READONLY',
	@PageNo,@PageSize,@BillStartDate,@BillEndDate,@BillCode,@BTypeID,@DeptID,@ElyID,@WhsID, @GoodsNo,@GoodsName,
	@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch,
	@Ppt1,@Ppt2,@Summary,@Description,@Remark,@GiftStt,@StopTag,@OperatorID,@GoodsTypeID_mx, @GoodsID_mx, @BtypeTypeID_mx, @BTypeID_mx, @WhsTypeID_mx, @WhsID_mx, @AreaID_mx, @DeptID_mx, @ElyID_mx, @TVP_Com,@TVP_Depart
							 	 
END
GO




/****** Object:  StoredProcedure [UP_PD_QuerySaleOrdermDetailList]    Script Date: 07/01/2014 15:11:36 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySaleOrdermDetailList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySaleOrdermDetailList]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleOrdermDetailList]    Script Date: 07/01/2014 15:11:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-01
	描述：销售订单管理(明细)
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleOrdermDetailList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillNo BIGINT=0,					--单据编号
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@StopTag INT=9,					--中止状态
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@Sqla NVARCHAR(MAX),@Sqlb NVARCHAR(MAX)
		,@Sqlc NVARCHAR(MAX),@Sqld NVARCHAR(MAX)
		,@HisStr VARCHAR(20)='_His',@KtypeLimit INT=0 
IF EXISTS (SELECT 1 FROM PD_SellOrdBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''

SET @Sql='
;WITH PagingData AS 
(
		SELECT DID,dtl.GoodsID,Ppt1ID,Ppt2ID,dtl.UnitID,dtl.ComQty[DHQty],dtl.Convfactor,Qty,TaxPrice[Price],TaxTotal[Total],dtl.ComTotal[DHTotal]
		,cast(dtl.Gift AS BIT) Gift
		,StopTag,CASE StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow]
		,dtl.Remark ,dtl.goodsno as BtypeGoodsNo
		FROM PD_SellOrdDetail'+@HisStr+' dtl '
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1 --部份权限
	SET @Sql += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=dtl.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @Sql +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=dtl.WhsID '
	END
END
*/
IF @GoodsID <> ''
	SET @Sql +='INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID ' 
IF @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
BEGIN
	SET @Sql += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
END
--IF @BarCode <> ''
--BEGIN 
--	SET @Sql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID  '
--END 
SET @Sql +='WHERE 1=1 '
IF @StopTag <> 9
	SET @Sql +='AND dtl.StopTag=@StopTag '
--商品型号	
IF @Model <> ''      
   BEGIN 
	   IF @ModelMatch = 0
		   SET @Sql += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @Sql += N' AND goods.Model = @Model ' 
   END  
--商品简名     
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @Sql += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @Sql += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
END     
--商品品牌  
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @Sql += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @Sql += N' AND goods.Brand = @Brand ' 
END  
--商品规格  
IF @Spec <> ''        
   BEGIN 
	   IF @SpecMatch = 0
		   SET @Sql += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @Sql += N' AND goods.Spec = @Spec '  
   END
--商品条码
IF @BarCode <> ''      
BEGIN 
	SET @Sql += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = dtl.GoodsID '
	IF @BarCodeMatch = 0
	   SET @Sql += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	ELSE IF @BarCodeMatch = 1
	   SET @Sql += N' AND pri.BarCode = @BarCode ' 
	SET @Sql += ' ) '
END 	
	
SET @Sql +='AND dtl.BillNo=@BillNo )'

/***********定义要关联的基础资料sql***********/
SET @Sqla=N'SELECT GoodsID[G1ID],GoodsNo,GoodsName,Spec,Model,GoodsAbbName,Brand FROM BD_Goods'
SET @Sqlb=N'SELECT Ppt1ID[P1ID],Value[Ppt1Name] FROM BD_Goods_Ppt1'
SET @Sqlc=N'SELECT Ppt2ID[P2ID],Value[Ppt2Name] FROM BD_Goods_Ppt2'
SET @Sqld=N'SELECT GoodsID[G2ID],UnitID[UID],Unit,BarCode FROM BD_Goods_Price'

DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillNo','BIGINT',@BillNo)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@GoodsID','VARCHAR(1000)',@GoodsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Model','VARCHAR(50)',@Model)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@ModelMatch','INT',@ModelMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@GoodsAbbName','VARCHAR(50)',@GoodsAbbName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@GoodsAbbNameMatch','INT',@GoodsAbbNameMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Brand','VARCHAR(50)',@Brand)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BrandMatch','INT',@BrandMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Spec','VARCHAR(50)',@Spec)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@SpecMatch','INT',@SpecMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BarCode','VARCHAR(100)',@BarCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BarCodeMatch','INT',@BarCodeMatch)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@StopTag','INT',@StopTag)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@OperatorID','INT',@OperatorID)

/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsID=_DATA_a.G1ID',@Sqla)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_b','Data.Ppt1ID=_DATA_b.P1ID',@Sqlb)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_c','Data.Ppt2ID=_DATA_c.P2ID',@Sqlc)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_d','Data.GoodsID=_DATA_d.G2ID AND _DATA_d.UID = Data.UnitID',@Sqld)

--print @Sql
IF @KtypeLimit = 0 EXEC SP_EXECUTESQL N' SELECT * FROM BD_Area WHERE 1 <> 1'
ELSE 
EXEC UP_OT_Paging @Sql,@TVP,@PageNo,@PageSize,'DID','','',1,0

GO






/****** Object:  StoredProcedure [UP_PD_QuerySaleOrdermList]    Script Date: 06/16/2014 16:14:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySaleOrdermList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySaleOrdermList]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleOrdermList]    Script Date: 06/16/2014 16:14:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-09-12
	描述：销售订单管理
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleOrdermList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@DlvStartDate VARCHAR(50)='',	--交货日期查询开始时间
	@DlvEndDate VARCHAR(50)='',		--交货日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@BTypeID VARCHAR(1000)='',		--往来单位
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@WhsID VARCHAR(1000)='',		--仓库
	@GoodsID VARCHAR(1000)='',		--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@Stt VARCHAR(50)='',			--订单状态
	@StopTag INT=9,					--中止状态
	@IsDraft INT=9,                 --生效状态  ------update sunzhiyuan
	@AuditStatus VARCHAR(100)='',   --审核状态  ------update sunzhiyuan
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@BtypeAddr VARCHAR(max)='',		--往来单位地址
	@BtypePhone VARCHAR(max)=''		--往来单位编号
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX),@SqlHead VARCHAR(500),@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)='',@StrStt VARCHAR(500),@InnerStt VARCHAR(100),@SqlSum VARCHAR(1000),@SqlSumParam VARCHAR(100)='',@SqlSumHead VARCHAR(100),@SqlSumOther VARCHAR(200),@SqlSumHead_His VARCHAR(100),@SqlSumOther_His VARCHAR(200),@BtypeLimit INT=0,@KtypeLimit INT=0 
IF @BTypeID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BTypeID '
IF @DeptID <> ''
	SET @SqlJoin +='
		INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @WhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = b.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
		INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SqlJoin += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=b.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=b.BTypeID '
	END
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=b.WhsID '
	END
END
*/
SET @SqlParam = 'WHERE 1=1 '
IF @BillCode <> ''
	SET @SqlParam +='AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @DlvStartDate <> ''
	SET @SqlParam +='AND b.DlvDate BETWEEN @DlvStartDate AND @DlvEndDate '
IF @Description <> ''
	SET @SqlParam +='AND b.[Description] Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='AND b.Summary Like ''%''+@Summary+''%'' '
IF @StopTag <> 9
BEGIN
	SET @SqlParam +='AND b.StopTag=@StopTag '
	SET @SqlSumParam ='WHERE p.StopTag=@StopTag '
END
-- 生效状态
IF @IsDraft <> 9
BEGIN
	SET @SqlParam +='AND b.IsDraft=@IsDraft '
	--SET @SqlSumParam ='WHERE p.IsDraft=@IsDraft '
END
-- 审核状态
IF @AuditStatus <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@AuditStatus, '','') _AuditStatus ON _AuditStatus.typeid = b.AuditStatus '
SET @SqlParam_His = @SqlParam
--IF @GoodsID <> ''
--BEGIN
--	SET @SqlParam_His += 'AND EXISTS (SELECT 1 FROM PD_SellOrdDetail_His dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--	SET @SqlParam += 'AND EXISTS (SELECT 1 FROM PD_SellOrdDetail dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--END

DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
--型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @ClauseParam += N' AND goods.Model = @Model ' 
END       
--简名
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @ClauseParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
END    
--品牌   
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
END    
--规格
IF @Spec <> ''        
BEGIN 
   IF @SpecMatch = 0
	   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @ClauseParam += N' AND goods.Spec = @Spec '  
END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
--条码
IF @BarCode <> ''      
BEGIN 
   IF @BarCodeMatch = 0
	   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID   '
END    


IF @GoodsID <> '' OR @ClauseParam <> ''
	BEGIN
		IF @GoodsID <> ''
			SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
		SET @SqlParam_His = @SqlParam + '
			AND EXISTS (SELECT 1 FROM PD_SellOrdDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
		SET @SqlParam += '
			AND EXISTS (SELECT 1 FROM PD_SellOrdDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
	END
ELSE
	SET @SqlParam_His = @SqlParam

SET @Sql = 'IF OBJECT_ID(''tempdb..#tempbo'',''U'') IS NOT NULL DROP TABLE #tempbo 
SET NOCOUNT ON; 
;WITH BillData AS( '
SET @SqlHead = '
		SELECT b.BillNo,BillDate,DlvDate,BillCode,StopTag,IsDraft,b.BTypeID,b.WhsID,ElyID,DeptID,BillQty,Total,[Description],Summary,AuditStatus '
SET @StrStt = '
			,CASE WHEN b.StopTag=1 THEN 2 
			WHEN NOT EXISTS(SELECT 1 FROM PD_SellOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty<BSQty) THEN 2 
			WHEN EXISTS(SELECT 1 FROM PD_SellOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty>0) THEN 1
			ELSE 0 END AS Stt '
SET @InnerStt = '
	INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = o.Stt '
SET @SqlSumHead = 'SELECT o.BillNo,SUM(p.ComQty/p.Convfactor)[DHQty],SUM(p.ComTotal)[DHTotal] '
SET @SqlSumOther = '
				FROM #tempbo o 
				INNER JOIN PD_SellOrdDetail p ON p.BillNo=o.BillNo '+@SqlSumParam+'GROUP BY o.BillNo '
SET @SqlSumHead_His = 'SELECT o.BillNo,SUM(p.ComQty/p.Convfactor)[DHQty],SUM(p.ComTotal)[DHTotal] '
SET @SqlSumOther_His = '
				FROM #tempbo o 
				INNER JOIN PD_SellOrdDetail_His p ON p.BillNo=o.BillNo '+@SqlSumParam+'GROUP BY o.BillNo '
	
IF @Stt <> '' AND @Stt <> '0,1,2'
BEGIN
	SET @Sql += '
	SELECT o.* FROM ( '
	IF @IsHistory = 0 
	BEGIN
		SET @Sql += @SqlHead + @StrStt + '
		FROM PD_SellOrdBill b ' + @SqlJoin + @SqlParam + ') AS o ' + @InnerStt + '
	) '
		SET @SqlSum = @SqlSumHead + @SqlSumOther
	END
	ELSE
	BEGIN
		SET @Sql += @SqlHead + @StrStt + '
		FROM PD_SellOrdBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + ',2[Stt] 
		FROM PD_SellOrdBill_His b ' + @SqlJoin + @SqlParam_His + '
	) AS o ' + @InnerStt + '
) '
		SET @SqlSum = @SqlSumHead + @SqlSumOther + '
				UNION ALL ' + @SqlSumHead_His + @SqlSumOther_His
	END
	SET @Sql += '
	SELECT * INTO #tempbo 
	FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillNo) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
	WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	SELECT o.*,s.DHQty,s.DHTotal,b.BtypeName,w.WhsName,e.ElyName,d.DeptName,CASE o.StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow]
	,CASE o.IsDraft WHEN 0 THEN ''已生效'' ELSE ''未生效'' END [IsDraftShow]
	,CASE o.AuditStatus WHEN 0 THEN ''无审核流程'' 
						WHEN 1 THEN ''未达审核条件'' 
						WHEN 2 THEN ''原始单据'' 
						WHEN 3 THEN ''审核中'' 
						WHEN 4 THEN ''审核通过''
						ELSE ''审核不通过'' END AS AuditStatusShow 
	FROM #tempbo o 
	INNER JOIN BD_Btype b ON b.BTypeID=o.BTypeID  AND B.Tel LIKE ''%' + @BtypePhone+'%'' AND B.Adress LIKE ''%' + @BtypeAddr+'%''
	INNER JOIN BD_Whs w ON w.WhsID=o.WhsID 
	INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
	INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
	INNER JOIN (' + @SqlSum + ') s ON s.BillNo = o.BillNo 
	DROP TABLE #tempbo '
END
ELSE
BEGIN
	IF @IsHistory = 0 
	BEGIN
		SET @Sql += @SqlHead + '
		FROM PD_SellOrdBill b ' + @SqlJoin + @SqlParam + '
	) '
		SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,2)[Stt] ' + @SqlSumOther
	END
	ELSE
	BEGIN
		SET @Sql += @SqlHead + '
		FROM PD_SellOrdBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + '
		FROM PD_SellOrdBill_His b ' + @SqlJoin + @SqlParam_His + '
	) '
		SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,2)[Stt] ' + @SqlSumOther + '
				UNION ALL 
				' + @SqlSumHead_His + ',dbo.UF_PD_GetBillStt(o.BillNo,2)[Stt] ' + @SqlSumOther_His
	END
	SET @Sql += '
	SELECT * INTO #tempbo 
	FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillNo) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
	WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	SELECT o.*,s.Stt,s.DHQty,s.DHTotal,b.BtypeName,w.WhsName,e.ElyName,d.DeptName
		,CASE o.StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow]
		,CASE o.IsDraft WHEN 0 THEN ''已生效'' ELSE ''未生效'' END [IsDraftShow]
		,CASE o.AuditStatus WHEN 0 THEN ''无审核流程'' 
						WHEN 1 THEN ''未达审核条件'' 
						WHEN 2 THEN ''原始单据'' 
						WHEN 3 THEN ''审核中'' 
						WHEN 4 THEN ''审核通过''
						ELSE ''审核不通过'' END AS AuditStatusShow 
	FROM #tempbo o 
	INNER JOIN BD_Btype b ON b.BTypeID=o.BTypeID  AND B.Tel LIKE ''%' + @BtypePhone+'%'' AND B.Adress LIKE ''%' + @BtypeAddr+'%''
	INNER JOIN BD_Whs w ON w.WhsID=o.WhsID 
	INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
	INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
	INNER JOIN (' + @SqlSum + ') s ON s.BillNo = o.BillNo 
	DROP TABLE #tempbo '
END
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--PRINT @Sql

EXEC SP_EXECUTESQL @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@DlvStartDate VARCHAR(50),@DlvEndDate VARCHAR(50),@BillCode VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@Stt VARCHAR(50),@StopTag INT=9,@IsDraft INT = 9,@AuditStatus VARCHAR(100),@OperatorID INT, @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',@PageNo,@PageSize,@BillStartDate,@BillEndDate,@DlvStartDate,@DlvEndDate,@BillCode,@BTypeID,@DeptID,@ElyID,@WhsID,@GoodsID,@Description,@Summary,@Stt,@StopTag,@IsDraft,@AuditStatus,@OperatorID, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch


END


GO








/****** Object:  StoredProcedure [UP_PD_QuerySaleSummaryList]    Script Date: 07/31/2014 10:38:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QuerySaleOrderSummary]') AND TYPE IN (N'P', N'PC'))
DROP PROCEDURE UP_PD_QuerySaleOrderSummary
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleSummaryList]    Script Date: 07/31/2014 10:38:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-30
	描述：销售订单汇总查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleOrderSummary]
(
     @PageNo INT = 0,						--页码
     @PageSize INT = 0,						--页大小
	 @BillDateType INT = 1,					--日期类型 1=录单日期,2=制单日期
	 @BillStartDate DATETIME,				--开始日期
	 @BillEndDate DATETIME,					--结束日期
	 @BTypeID VARCHAR(1000) = '',           --往来单位
	 @DeptID VARCHAR(1000) = '',            --部门
	 @ElyID VARCHAR(1000) = '',				--经手人
	 @WhsID VARCHAR(1000) = '',				--仓库
	 @GoodsNoMatch INT = 0,					--商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',				--商品编号
	 @GoodsNameMatch INT = 0,				--商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',			--商品名称
	 ---------------update sunzhiyuan 20150902--------------------
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	 ---------------update sunzhiyuan 20150902--------------------
	 @SummaryMatch INT = 0,					--摘要匹配方式
	 @Summary VARCHAR(256) = '',			--摘要
	 @DescriptionMatch INT = 0,				--说明匹配方式
	 @Description VARCHAR(100) = '',		--说明
	 @RemarkMatch INT = 0,					--明细备注匹配方式
	 @Remark VARCHAR(100) = '',				--明细备注
	 @GiftStt INT = 1,						--赠品状态 9=全部,1=是,0=否
	 @SumParam INT = 0,						--汇总条件
	 @SumLevel INT = 0,						--汇总等级
	 @OrderStr VARCHAR(50) = '',			--排序字符串
	 @IsHistory INT=0,						--是否包含历史数据
	 @OperatorID INT = 0					--操作员ID
) 
AS
SET NOCOUNT ON
BEGIN

	DECLARE @re INT 
	EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
	IF( @re=1 )RETURN @re;

	DECLARE @ComHeadSql NVARCHAR(2000), 
			@HeadSql NVARCHAR(2000)='', 
			@HeadSql_His NVARCHAR(2000)='', 
	        @Sql_Ct NVARCHAR(MAX), 
	        @Sql_His NVARCHAR(MAX), 
	        @Sql NVARCHAR(MAX) = '', 
	        @SqlGroup NVARCHAR(1000) = '',
	        @SqlGroup_His NVARCHAR(1000) = '',
		    @SqlParam NVARCHAR(1000) = '',
	        @DataSql NVARCHAR(2000) = '', 
	        @BaseSql NVARCHAR(2000) = '',
	        @BtypeLimit INT = 0, 
	        @KtypeLimit INT = 0
    DECLARE @TVP_Dept AS [TVP_Type]   
    
    SET @ComHeadSql = ';WITH PagingData AS (
					SELECT SUM(detail.BSQty) AS Qty,SUM(detail.TaxTotal) AS Total
					,SUM(detail.ComQty) AS ComQty,SUM(detail.ComTotal) AS ComTotal
                    ,SUM(CASE WHEN detail.StopTag = 1 AND detail.BSQty - detail.ComQty > 0 THEN detail.BSQty - detail.ComQty ELSE 0 END) AS StopQty
                    ,SUM(CASE WHEN detail.StopTag = 1 AND detail.TaxTotal - detail.ComTotal > 0 THEN detail.TaxTotal - detail.ComTotal ELSE 0 END) AS StopTotal '
                    
    SET @Sql_Ct = 'FROM PD_SellOrdBill ord 
                INNER JOIN PD_SellOrdDetail detail ON detail.BillNo = ord.BillNo '
    SET @Sql_His = 'FROM PD_SellOrdBill_His ord 
                INNER JOIN PD_SellOrdDetail_His detail ON detail.BillNo = ord.BillNo '
	/*权限使用公用方法*/
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
	IF @BtypeLimit = 1  --部份权限
		SET @Sql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=ord.BTypeID '
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF @KtypeLimit = 1  --部份权限
		SET @Sql += ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=ord.WhsID '
	/*权限使用非公用方法*/
	/*
	IF @OperatorID <> 1 
	BEGIN
		IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
		BEGIN
			SET @Sql +='
			INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=ord.BTypeID '
		END
		IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
		BEGIN
			SET @Sql +='
			INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=ord.WhsID '
		END
	END
	*/
	
    IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
	   SET @Sql += 'INNER JOIN BD_Goods goods ON goods.GoodsID = detail.GoodsID '
	
	-- 条码
	IF @BarCode <> ''
	BEGIN 
		SET @Sql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = detail.GoodsID AND pri.UnitID = 1 '
	END   
	   
    IF @BillDateType = 1
       SET @SqlParam = 'WHERE detail.BillDate BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
    ELSE
       SET @SqlParam = 'WHERE ord.CreateTime BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
       
    IF @BTypeID <> ''     --往来单位
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = ord.BTypeID '
	   
    IF @DeptID <> ''     --部门
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = ord.DeptID '
		INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
		SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
		INNER JOIN BD_Dept cd ON cd.[Path] LIKE d.[Path] + '%'
		WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	END
	   
    IF @ElyID <> ''     --经手人
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = ord.ElyID '
	   
    IF @WhsID <> ''     --仓库
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = ord.WhsID '
	     							
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += 'AND goods.GoodsNo LIKE ''%''+@GoodsNo+''%'' '
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += 'AND goods.GoodsNo=@GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	BEGIN 
	   IF @GoodsNameMatch = 0
		   SET @SqlParam += 'AND goods.GoodsName LIKE ''%''+@GoodsName+''%'' '
	   ELSE IF @GoodsNameMatch = 1
		   SET @SqlParam += 'AND goods.GoodsName=@GoodsName ' 
	END
    --商品型号
    IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @Sql += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @Sql += N' AND goods.Model = @Model ' 
	END       
	--商品简名
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @Sql += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @Sql += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @Sql += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @Sql += N' AND goods.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
	   IF @SpecMatch = 0
		   SET @Sql += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @Sql += N' AND goods.Spec = @Spec '  
	END
	--商品条码
	IF @BarCode <> ''      
	BEGIN 
	IF @BarCodeMatch = 0
	   SET @Sql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=detail.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @Sql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=detail.GoodsID)'
	END
	
	--IF @BarCode <> ''      
	--BEGIN 
	--   IF @BarCodeMatch = 0
	--	   SET @Sql += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	--   ELSE IF @BarCodeMatch = 1
	--	   SET @Sql += N' AND pri.BarCode = @BarCode ' 
	--END
       							
	IF @Summary <> ''   --摘要 
	   BEGIN 
		   IF @SummaryMatch = 0
			   SET @SqlParam += 'AND ord.Summary LIKE ''%''+@Summary+''%'' '
		   ELSE IF @SummaryMatch = 1
			   SET @SqlParam += 'AND ord.Summary=@Summary ' 
	   END
	   
	IF @Description <> ''  --说明
	   BEGIN 
		   IF @DescriptionMatch = 0
			   SET @SqlParam += 'AND ord.[Description] LIKE ''%''+@Description+''%'' '
		   ELSE IF @DescriptionMatch = 1
			   SET @SqlParam += 'AND ord.[Description]=@Description ' 
	   END
       							
	IF @Remark <> ''   --明细备注
	   BEGIN 
		   IF @RemarkMatch = 0 
			   SET @SqlParam += 'AND detail.Remark LIKE ''%''+@Remark+''%'' '
		   ELSE IF @RemarkMatch = 1
			   SET @SqlParam += 'AND detail.Remark=@Remark ' 
	   END
	   
    IF @GiftStt <> 9 --赠品 
       SET @SqlParam += 'AND detail.Gift = @GiftStt '
	   
	IF @SumParam = 1 --汇总层级：商品分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
	          SET @HeadSql += ',parGoodsType.BaseID AS GoodsTypeID '
	          SET @HeadSql_His += ',o.GoodsTypeID '
	          SET @Sql += '
				INNER JOIN BD_Goods _bg ON _bg.GoodsID = detail.GoodsID 
				INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @SumLevel) parGoodsType ON parGoodsType.ParID = _bg.GoodsTypeID '
			  SET @SqlGroup += ',parGoodsType.BaseID '
			  SET @SqlGroup_His += ',o.GoodsTypeID '
	        END
	     ELSE IF @SumLevel = 6  --商品
            BEGIN
			  SET @HeadSql += ', detail.GoodsID '
			  SET @HeadSql_His += ', o.GoodsID '
			  SET @SqlGroup += ', detail.GoodsID '
			  SET @SqlGroup_His += ', o.GoodsID '
	        END
	   END
	   
	IF @SumParam = 2 --汇总层级：往来单位分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
	          SET @HeadSql += ',parBtypeType.BaseID AS BtypeTypeID '
	          SET @HeadSql_His += ',o.BtypeTypeID '
	          SET @Sql += '
				INNER JOIN BD_Btype _bt ON _bt.BTypeID = ord.BTypeID 
				INNER JOIN dbo.UF_BD_BaseSummary(''BTYPE'', @SumLevel) parBtypeType ON parBtypeType.ParID = _bt.BtypeTypeID '
			  SET @SqlGroup += ',parBtypeType.BaseID '
			  SET @SqlGroup_His += ',o.BtypeTypeID '
	        END
	     ELSE IF @SumLevel = 6  --往来单位
            BEGIN
			  SET @HeadSql += ',ord.BTypeID '
			  SET @HeadSql_His += ',o.BTypeID '
			  SET @SqlGroup += ',ord.BTypeID '
			  SET @SqlGroup_His += ',o.BTypeID '
	        END
	   END
	   
	IF @SumParam = 3 --汇总层级：仓库分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
				SET @HeadSql += ',parWhsType.BaseID AS WhsTypeID '
				SET @HeadSql_His += ',o.WhsTypeID '
				SET @Sql += '
				INNER JOIN BD_Whs _bw ON _bw.WhsID = ord.WhsID 
				INNER JOIN dbo.UF_BD_BaseSummary(''KTYPE'', @SumLevel) parWhsType ON parWhsType.ParID = _bw.WhsTypeID '
				SET @SqlGroup += ',parWhsType.BaseID '
				SET @SqlGroup_His += ',o.WhsTypeID '
	        END
	     ELSE IF @SumLevel = 6  --仓库
            BEGIN
			  SET @HeadSql += ',ord.WhsID '
			  SET @HeadSql_His += ',o.WhsID '
			  SET @SqlGroup += ',ord.WhsID '
			  SET @SqlGroup_His += ',o.WhsID '
	        END
	   END
	   
	IF @SumParam = 4 --汇总层级：地区
	   BEGIN
	      IF @SumLevel<>5 
		     BEGIN
		        SET @HeadSql += ',parArea.BaseID AS AreaID '
		        SET @HeadSql_His += ',o.AreaID '
                SET @Sql += '
				INNER JOIN BD_Btype _bbt ON _bbt.BTypeID = ord.BTypeID 
				INNER JOIN dbo.UF_BD_BaseSummary(''AREA'', @SumLevel) parArea ON parArea.ParID = _bbt.AreaID '
		        SET @SqlGroup += ',parArea.BaseID '
		        SET @SqlGroup_His += ',o.AreaID '
		     END
		     ELSE
		     BEGIN
		        SET @HeadSql += ',bType.AreaID '
		        SET @HeadSql_His += ',o.AreaID '
                SET @Sql += 'INNER JOIN BD_BType bType ON bType.BTypeID=ord.BTypeID  '
		        SET @SqlGroup += ',bType.AreaID '
		        SET @SqlGroup_His += ',o.AreaID '
		     END
	   END
	   
	IF @SumParam = 5 --汇总层级：部门
	   BEGIN
	      IF @SumLevel<>5 
		     BEGIN
		        SET @HeadSql += ',parDept.BaseID AS DeptID '
		        SET @HeadSql_His += ',o.DeptID '
                SET @Sql += '
                INNER JOIN BD_Dept _bd ON _bd.DeptID = ord.DeptID 
				INNER JOIN dbo.UF_BD_BaseSummary(''DTYPE'', @SumLevel) parDept ON parDept.ParID = _bd.DeptID '
		        SET @SqlGroup += ',parDept.BaseID '
		        SET @SqlGroup_His += ',o.DeptID '
		     END
		     ELSE
		     BEGIN
		        SET @HeadSql += ',ord.DeptID '
		        SET @HeadSql_His += ',o.DeptID '
		        SET @SqlGroup += ',ord.DeptID '
		        SET @SqlGroup_His += ',o.DeptID '
		     END
	   END
	   
	IF @SumParam = 6 --汇总层级：职员
	   BEGIN
          SET @HeadSql += ',ord.ElyID '
          SET @HeadSql_His += ',o.ElyID '
		  SET @SqlGroup += ',ord.ElyID '
		  SET @SqlGroup_His += ',o.ElyID '
	   END
	
	IF @IsHistory=0
		SET @Sql = @ComHeadSql + @HeadSql + @Sql_Ct + @Sql + @SqlParam + ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1)  + ' )'
	ELSE
		SET @Sql = ';WITH PagingData AS (
					SELECT SUM(o.BSQty) AS Qty,SUM(o.TaxTotal) AS Total
					,SUM(o.ComQty) AS ComQty,SUM(o.ComTotal) AS ComTotal
                    ,SUM(CASE WHEN o.StopTag = 1 AND o.BSQty - o.ComQty > 0 THEN o.BSQty - o.ComQty ELSE 0 END) AS StopQty
                    ,SUM(CASE WHEN o.StopTag = 1 AND o.TaxTotal - o.ComTotal > 0 THEN o.TaxTotal - o.ComTotal ELSE 0 END) AS StopTotal ' + @HeadSql_His 
                    + 'FROM ( 
                    SELECT detail.BSQty,detail.TaxTotal,detail.ComQty,detail.ComTotal,detail.StopTag ' + @HeadSql + @Sql_Ct + @Sql + @SqlParam 
					+ 'UNION ALL '
					+ 'SELECT detail.BSQty,detail.TaxTotal,detail.ComQty,detail.ComTotal,detail.StopTag ' + @HeadSql + @Sql_His + @Sql + @SqlParam 
					+ ') o GROUP BY ' + SUBSTRING(@SqlGroup_His, 2, LEN(@SqlGroup_His) - 1)  + ' )'
    SET @Sql += ',MainData AS (SELECT PagingData.* ' 
    IF @SumParam = 1 AND @SumLevel <> 6
		SET @Sql += ',g.TypeCode AS GoodsTypeCode,g.TypeName AS GoodsTypeName FROM PagingData
		              INNER JOIN BD_Goods_Type g on g.GoodsTypeID = PagingData.GoodsTypeID ' 
	ELSE IF @SumParam = 1 AND @SumLevel = 6
		SET @Sql += ',goods.GoodsNo,goods.GoodsName,goods.Model,goods.GoodsAbbName,goods.Brand,goods.Spec,pri.BarCode FROM PagingData
		              INNER JOIN BD_Goods goods on goods.GoodsID = PagingData.GoodsID
		              INNER JOIN BD_Goods_Price pri ON pri.GoodsID = PagingData.GoodsID AND pri.UnitID = 1'
	ELSE IF @SumParam = 2 AND @SumLevel <> 6
		SET @Sql += ',b.TypeCode AS BtypeTypeCode,b.TypeName AS BtypeTypeName FROM PagingData
		              INNER JOIN BD_Btype_Type b on b.BtypeTypeID = PagingData.BtypeTypeID ' 
	ELSE IF @SumParam = 2 AND @SumLevel = 6
		SET @Sql += ',btype.BTypeCode,btype.BTypeName FROM PagingData
		              INNER JOIN BD_Btype btype on btype.BTypeID = PagingData.BTypeID ' 
	ELSE IF @SumParam = 3 AND @SumLevel <> 6
		SET @Sql += ',w.TypeCode AS WhsTypeCode,w.TypeName AS WhsTypeName FROM PagingData
		              INNER JOIN BD_Whs_Type w on w.WhsTypeID = PagingData.WhsTypeID ' 
	ELSE IF @SumParam = 3 AND @SumLevel = 6
		SET @Sql += ',whs.WhsNO,whs.WhsName FROM PagingData
		             INNER JOIN BD_Whs whs on whs.WhsID = PagingData.WhsID ' 
	ELSE IF @SumParam = 4
		SET @Sql += ',a.AreaNO,a.AreaName FROM PagingData 
		             INNER JOIN BD_Area a on a.AreaID = PagingData.AreaID ' 
	ELSE IF @SumParam = 5
		SET @Sql += ',d.DeptCode,d.DeptName FROM PagingData 
		             INNER JOIN BD_Dept d on d.DeptID = PagingData.DeptID ' 
	ELSE IF @SumParam = 6
		SET @Sql += ',e.ElyCode,e.ElyName FROM PagingData 
		             INNER JOIN BD_Employee e on e.ElyID = PagingData.ElyID ' 
    SET @Sql += ')'  
    
    SET @Sql='SET NOCOUNT ON;'
             + @Sql + 
			 ',DATA AS(SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM MainData) A 
						CROSS JOIN 
						(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM MainData) B 
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize) 
				SELECT * FROM DATA ORDER BY ROWID '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--PRINT @Sql
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillDateType INT, @BillStartDate DATETIME, 
							   @BillEndDate DATETIME, @BTypeID VARCHAR(1000), @DeptID VARCHAR(1000), 
							   @ElyID VARCHAR(1000), @WhsID VARCHAR(1000), @GoodsNo VARCHAR(50),
							   @GoodsName VARCHAR(100), @Summary VARCHAR(256), @Description VARCHAR(100), 
							   @Remark VARCHAR(100), @GiftStt INT, @SumLevel INT, @OperatorID INT, @TVP_Dept TVP_Type READONLY
							   , @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT', 
	                         @PageNo, @PageSize, @BillDateType, @BillStartDate, @BillEndDate, @BTypeID, @DeptID, @ElyID, 
	                         @WhsID, @GoodsNo, @GoodsName, @Summary, @Description, @Remark, @GiftStt, @SumLevel, @OperatorID, @TVP_Dept     
	                         , @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
END
GO




/****** Object:  StoredProcedure [UP_PD_QuerySaleSummaryList]    Script Date: 06/23/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySaleSummaryList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySaleSummaryList]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySaleSummaryList]    Script Date: 06/23/2014 15:42:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-09-14
	描述：销售汇总统计
	××××××××××××××××××
	修改：sunzhiyuan
	日期：2015-3-31
	修改描述：66行：取消归档数据判断
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySaleSummaryList]
(			   
	@pageNo INT=1,					--页码
	@pageSize INT=10,				--分页数
	@BillDateType INT=1,			--单据日期类型:1=录单日期,2=制单日期,3=过账日期  对应BillDate,CreateTime,PosTime
	@BillStartDate DATETIME,		--单据开始日期
	@BillEndDate DATETIME,			--单据结束日期
	@SaleBillOut INT=1,				--销售出库单勾选状态
	@SaleBillIn INT=1,				--销售退货单勾选状态
	@BTypeID VARCHAR(MAX) = '',	--往来单位
	@DeptID VARCHAR(MAX) = '',		--部门
	@ElyID VARCHAR(MAX) = '',		--经手人
	@CreatorID VARCHAR(MAX)='',    --制单人
	@WhsID VARCHAR(MAX) = '',		--仓库
	@GoodsID VARCHAR(1000) = '',	--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(20) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(50) = '',	--商品名称
	---------------update sunzhiyuan 20150906--------------------
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	---------------update sunzhiyuan 20150906--------------------
	@SummaryMatch INT=0,			--摘要配置模式:0=包含,1=等于
	@Summary VARCHAR(256) = '',		--摘要
	@DescriptionMatch INT=0,		--说明配置模式:0=包含,1=等于
	@Description VARCHAR(100) = '', --说明
	@RemarkMatch INT=0,				--明细备注配置模式:0=包含,1=等于
	@Remark VARCHAR(100) = '',		--明细备注
	@Goods INT=0,					--商品汇总项：商品
	@Ppt1 INT=0,					--商品汇总项：属性一
	@Ppt2 INT=0,					--商品汇总项：属性二
	@GoodsC1 INT=0,					--商品汇总项：自定义字段一
	@GoodsC2 INT=0,					--商品汇总项：自定义字段二
	@GoodsC3 INT=0,					--商品汇总项：自定义字段三
	@GoodsC4 INT=0,					--商品汇总项：自定义字段四
	@GoodsC5 INT=0,					--商品汇总项：自定义字段五
	@Btype INT=0,					--往来单位汇总：往来单位
	@BtypeC1 INT=0,					--往来单位汇总：自定义字段一
	@BtypeC2 INT=0,					--往来单位汇总：自定义字段二
	@BtypeC3 INT=0,					--往来单位汇总：自定义字段三
	@BtypeC4 INT=0,					--往来单位汇总：自定义字段四
	@BtypeC5 INT=0,					--往来单位汇总：自定义字段五
	@GiftState INT=9,				--赠品状态：9=全部,1=是,0=否
	@Privilege INT=0,				--包含优惠信息：0=不包含，1=包含
	@CollectType1 INT=0,			--汇总条件一:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer1 INT=0,					--汇总层级一:0:空 1-5:XX分类层级 6:XX
	@CollectType2 INT=0,			--汇总条件二:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer2 INT=0,					--汇总层级二:0:空 1-5:XX分类层级 6:XX
	@OrderType1 INT=0,				--排序条件一:1=商品分类编码,2=商品分类名称,3=商品编码,4=商品名称,5=往来单位分类编码,6=往来单位分类名称,7=往来单位编码,8=往来单位名称,9=仓库分类编码,10=仓库分类名称,11=仓库编码,12=仓库名称,13=地区编码,14=地区名称,15=部门编码,16=部门名称,17=职员编码,18=职员名称,19=数量,20=销售均价,21=销售金额,22=成本均价,23=成本金额,24=毛利,25=毛利率,26=赠品数量,27=属性一,28=属性二
	@OrderSeq1 INT=1,				--排序规则：1=升序，2=降序
	@OrderType2 INT=0,				--排序条件一:1=商品分类编码,2=商品分类名称,3=商品编码,4=商品名称,5=往来单位分类编码,6=往来单位分类名称,7=往来单位编码,8=往来单位名称,9=仓库分类编码,10=仓库分类名称,11=仓库编码,12=仓库名称,13=地区编码,14=地区名称,15=部门编码,16=部门名称,17=职员编码,18=职员名称,19=数量,20=销售均价,21=销售金额,22=成本均价,23=成本金额,24=毛利,25=毛利率,26=赠品数量,27=属性一,28=属性二
	@OrderSeq2 INT=1,				--排序规则：1=升序，2=降序
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)
AS
SET NOCOUNT ON
BEGIN
	-- 当日期类型为业务日期的场合，做归档日期的范围判断
	IF @BillDateType = 1
	BEGIN
		DECLARE @Re INT 
		EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
		IF( @Re=1 )RETURN @Re;
	END

DECLARE @Sql NVARCHAR(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlOrder VARCHAR(100)=''
	,@SumData NVARCHAR(MAX),@VbSumHead VARCHAR(MAx)='',@SumHead NVARCHAR(MAX),@SumHeadFH NVARCHAR(MAX),@SumJoin NVARCHAR(MAX)='',@SumParam NVARCHAR(MAX),@VbSumG VARCHAR(300)=''
	,@Sql_PPB NVARCHAR(MAX),@Sql_PPB_His NVARCHAR(MAX),@Sql_PRB NVARCHAR(MAX),@Sql_PRB_His NVARCHAR(MAX)
	,@BillData NVARCHAR(MAX),@VbBDHead VARCHAR(MAX)='',@BDHead VARCHAR(MAX),@VbSumBDHead VARCHAR(MAX)='',@VbBDJoin VARCHAR(MAX)='',@CFBDJoin NVARCHAR(MAX)='',@VbSumBDG VARCHAR(600)=''
	,@AVGPrice VARCHAR(200),@AVGCostPrice VARCHAR(200),@Profit VARCHAR(200),@ProfitRate VARCHAR(200)
	,@bg1 VARCHAR(500),@bt1 VARCHAR(500),@bw1 VARCHAR(500),@ba1 VARCHAR(500),@bd1 VARCHAR(500)
	,@bg2 VARCHAR(500),@bt2 VARCHAR(500),@bw2 VARCHAR(500),@ba2 VARCHAR(500),@bd2 VARCHAR(500)
	,@BtypeLimit INT=0,@KtypeLimit INT=0 ,@GoodsCSourceType1 int = 1,@GoodsCSourceType2 int = 1,@GoodsCSourceType3 int = 1,@GoodsCSourceType4 int = 1,@GoodsCSourceType5 int = 1
	,@BtypeCSourceType1 int = 1,@BtypeCSourceType2 int = 1,@BtypeCSourceType3 int = 1,@BtypeCSourceType4 int = 1,@BtypeCSourceType5 int = 1
	,@GoodsSource1 int = 1,@GoodsSource2 int = 1,@GoodsSource3 int = 1,@GoodsSource4 int = 1,@GoodsSource5 int = 1
	,@BTypeSource1 int = 1,@BtypeSource2 int = 1,@BtypeSource3 int = 1,@BtypeSource4 int = 1,@BtypeSource5 int = 1
--INNER JOIN BEGIN
Select @GoodsCSourceType1 = SourceType from BD_Goods_CustomItem where CustItemID = 1
Select @GoodsCSourceType2 = SourceType from BD_Goods_CustomItem where CustItemID = 2
Select @GoodsCSourceType3 = SourceType from BD_Goods_CustomItem where CustItemID = 3
Select @GoodsCSourceType4 = SourceType from BD_Goods_CustomItem where CustItemID = 4
Select @GoodsCSourceType5 = SourceType from BD_Goods_CustomItem where CustItemID = 5
Select @BtypeCSourceType1 = SourceType from BD_Btype_CustomItem where CustItemID = 1
Select @BtypeCSourceType2 = SourceType from BD_Btype_CustomItem where CustItemID = 2
Select @BtypeCSourceType3 = SourceType from BD_Btype_CustomItem where CustItemID = 3
Select @BtypeCSourceType4 = SourceType from BD_Btype_CustomItem where CustItemID = 4
Select @BtypeCSourceType5 = SourceType from BD_Btype_CustomItem where CustItemID = 5

IF @BTypeID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _BType ON _BType.typeid = p.BTypeID '
IF @DeptID <> ''
BEGIN
	SET @SumJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=p.DeptID '
END
IF @ElyID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = p.ElyID '
IF @CreatorID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@CreatorID, '','') _PEly ON _PEly.typeid = p.Creator '
IF @WhsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = p.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SumJoin += '
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=p.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SumJoin += '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=p.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SumJoin +='
	INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=p.BTypeID '
	END
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SumJoin +='
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=p.WhsID '
	END
END
*/
IF @GoodsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID '
IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
	SET @SumJoin +='
	INNER JOIN BD_Goods g ON g.GoodsID=dtl.GoodsID '
IF @BarCode <> ''
BEGIN 
	SET @SumJoin += ' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID and pri.UnitID = 1 '
END 
--INNER JOIN END

--条件BEGIN
IF @BillDateType=1
	SET @SqlDTStr='dtl.BillDate'
IF @BillDateType=2
	SET @SqlDTStr='p.CreateTime'	
IF @BillDateType=3
	SET @SqlDTStr='p.PosTime'	
SET @SumParam = '
	WHERE '+@SqlDTStr+' BETWEEN @BillStartDate AND @BillEndDate AND p.IsDraft=0 AND p.Red=0 '
IF @GiftState<>9 
	SET @SumParam += 'AND Gift=@GiftState '

IF @Summary <> ''
BEGIN
	IF @SummaryMatch=0 SET @SumParam += 'AND p.Summary LIKE ''%''+@Summary+''%'' '  
	IF @SummaryMatch=1 SET @SumParam += 'AND p.Summary=@Summary '  
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch=0 SET @SumParam += 'AND p.[Description] LIKE ''%''+@Description+''%'' '  
	IF @DescriptionMatch=1 SET @SumParam += 'AND p.[Description]=@Description '  
END
IF @Remark <> ''
BEGIN
	IF @RemarkMatch=0 SET @SumParam += 'AND dtl.Remark LIKE ''%''+@Remark+''%'' '   
	IF @RemarkMatch=1 SET @SumParam += 'AND dtl.Remark=@Remark '  
END
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0 SET @SumParam += 'AND g.GoodsNo LIKE ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch=1 SET @SumParam += 'AND g.GoodsNo=@GoodsNo '  
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0 SET @SumParam += 'AND g.GoodsName LIKE ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch=1 SET @SumParam += 'AND g.GoodsName=@GoodsName '  
END
--商品型号	
IF @Model <> ''      
   BEGIN 
	   IF @ModelMatch = 0
		   SET @SumParam += N' AND g.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @SumParam += N' AND g.Model = @Model ' 
   END  
--商品简名     
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @SumParam += N' AND g.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @SumParam += N' AND g.GoodsAbbName = @GoodsAbbName ' 
END     
--商品品牌  
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @SumParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @SumParam += N' AND g.Brand = @Brand ' 
END  
--商品规格  
IF @Spec <> ''        
   BEGIN 
	   IF @SpecMatch = 0
		   SET @SumParam += N' AND g.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @SumParam += N' AND g.Spec = @Spec '  
   END
--商品条码
IF @BarCode <> ''      
BEGIN 
	IF @BarCodeMatch = 0
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=dtl.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=dtl.GoodsID)'
END
--条件END

--
--商品分类
SET @bg1 = '
			SELECT pbs.BaseID,[_bg].GoodsID 
			FROM (
				SELECT GT.GoodsTypeID AS BaseID,T.GoodsTypeID FROM BD_Goods_Type GT 
				INNER JOIN BD_Goods_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) pbs
			INNER JOIN BD_Goods _bg ON [_bg].GoodsTypeID = pbs.GoodsTypeID '

--往来单位分类
SET @bt1 = '
			SELECT bbs.BaseID,[_bt].BTypeID 
			FROM (
				SELECT GT.BtypeTypeID AS BaseID,T.BtypeTypeID FROM BD_Btype_Type GT 
				INNER JOIN BD_Btype_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) bbs
			INNER JOIN BD_Btype _bt ON [_bt].BtypeTypeID = bbs.BtypeTypeID '

--仓库分类
SET @bw1 = '
			SELECT wbs.BaseID,[_bw].WhsID 
			FROM (
				SELECT GT.WhsTypeID AS BaseID,T.WhsTypeID FROM BD_Whs_Type GT 
				INNER JOIN BD_Whs_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) wbs
			INNER JOIN BD_Whs _bw ON [_bw].WhsTypeID = wbs.WhsTypeID '

--地区分类
SET @ba1 = '
			SELECT dbs.BaseID,_ba.AreaID 
			FROM (
				SELECT GT.AreaID AS BaseID,T.AreaID 
				FROM BD_Area GT 
				INNER JOIN BD_Area T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Area _ba ON [_ba].AreaID = dbs.AreaID '

--部门分类
SET @bd1 = '
			SELECT dbs.BaseID,_bd.DeptID 
			FROM (
				SELECT GT.DeptID AS BaseID,T.DeptID 
				FROM BD_Dept GT 
				INNER JOIN BD_Dept T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Dept _bd ON [_bd].DeptID = dbs.DeptID '
--

-----汇总层级一-----begin
IF @CollectType1 <> 0
BEGIN
	IF @CollectType1 = 1
	BEGIN
		IF @Layer1 <> 6 --汇总层级:商品分类1-5
		BEGIN
			SET @VbSumHead += ',dtl.GoodsID '
			SET @VbSumG += 'dtl.GoodsID '
			SET @VbBDHead += ',gt.TypeCode[Code1],gt.TypeName[Name1] '
			SET @VbSumBDHead += ',pbs.BaseID[ID1] '
			SET @VbSumBDG += 'pbs.BaseID '
			SET @VbBDJoin += '
		INNER JOIN BD_Goods_Type gt ON gt.GoodsTypeID=o.ID1'
			SET @CFBDJoin += '
		INNER JOIN ('+@bg1+'
		) pbs ON pbs.GoodsID = sd.GoodsID '
		END
		ELSE
		BEGIN
			IF @Ppt1=0 AND @Ppt2=0 And @GoodsC1 = 0 And @GoodsC2 = 0 And @GoodsC3 = 0 And @GoodsC4 = 0 And @GoodsC5 = 0
			BEGIN
				SET @VbSumHead += ',dtl.GoodsID '
				SET @VbSumG += 'dtl.GoodsID '
				SET @VbBDHead += ',g.GoodsNo[Code1],g.GoodsName[Name1],g.Model[Model1],g.GoodsAbbName[GoodsAbbName1],g.Brand[Brand1],g.Spec[Spec1],pri.BarCode[BarCode1] '
				SET @VbSumBDHead += ',sd.GoodsID[ID1] '
				SET @VbSumBDG += ' sd.GoodsID '
				SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID1 
	INNER JOIN BD_Goods_Price pri ON o.ID1 = pri.GoodsID AND pri.UnitID = 1 '
			END
			ELSE
			BEGIN
				IF @Goods<>0 
				BEGIN
					SET @VbSumHead += ',dtl.GoodsID '
					SET @VbSumG += 'dtl.GoodsID '
					SET @VbBDHead += ',g.GoodsNo[Code1],g.GoodsName[Name1],g.Model[Model1],g.GoodsAbbName[GoodsAbbName1],g.Brand[Brand1],g.Spec[Spec1],pri.BarCode[BarCode1] '
					SET @VbSumBDHead += ',sd.GoodsID[ID1] '
					SET @VbSumBDG += 'sd.GoodsID '
					SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID1 
	INNER JOIN BD_Goods_Price pri ON o.ID1 = pri.GoodsID AND pri.UnitID = 1'
				END
				IF @Ppt1<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt1ID '
					SET @VbBDHead += ',p1.Value[Ppt1Name1] '
					SET @VbSumBDHead += ',sd.Ppt1ID '
					IF @Goods<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt1ID ' 
						SET @VbSumBDG += ',sd.Ppt1ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += 'dtl.Ppt1ID '
						SET @VbSumBDG += 'sd.Ppt1ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt1 p1 ON p1.Ppt1ID=o.Ppt1ID '
				END
				IF @Ppt2<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt2ID '
					SET @VbBDHead += ',p2.Value[Ppt2Name1] '
					SET @VbSumBDHead += ',sd.Ppt2ID '
					IF @Goods<>0 OR @Ppt1<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt2ID '
						SET @VbSumBDG += ',sd.Ppt2ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += 'dtl.Ppt2ID '
						SET @VbSumBDG += 'sd.Ppt2ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt2 p2 ON p2.Ppt2ID=o.Ppt2ID '
				END
			END
			
			--自定义字段分类
			IF @Goods = 0
			BEGIN
				IF(@GoodsC1 <> 0)
				BEGIN
				   Set @VbSumHead += ' ,BGC.CustVal1 '
				   SET @VbSumBDG += ',sd.CustVal1 '				       
				   Set @VbSumBDHead += ',sd.CustVal1 '
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal1 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal1 '
				    
				   Set @VbBDHead += ',o.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=o.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=o.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=o.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=o.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=o.CustVal1 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType1 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=o.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal2'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal2 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal2 '
				   Set @VbSumBDHead += ',sd.CustVal2 '
				   SET @VbSumBDG += ',sd.CustVal2 '	
				   Set @VbBDHead += ',o.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=o.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=o.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=o.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=o.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=o.CustVal2 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType2 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=o.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal3'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal3 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal3 '
				   Set @VbSumBDHead += ',sd.CustVal3 '
				   SET @VbSumBDG += ',sd.CustVal3 '				       
				   Set @VbBDHead += ',o.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=o.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=o.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=o.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=o.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=o.CustVal3 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType3 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=o.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal4'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal4 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal4 '
				   Set @VbSumBDHead += ',sd.CustVal4 '
				   SET @VbSumBDG += ',sd.CustVal4 '				       
				   Set @VbBDHead += ',o.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=o.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=o.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=o.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=o.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=o.CustVal4 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType4 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=o.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal5'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal5 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal5 '
				   Set @VbSumBDHead += ',sd.CustVal5 '
				   SET @VbSumBDG += ',sd.CustVal5 '				       
				   Set @VbBDHead += ',o.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=o.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=o.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=o.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=o.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=o.CustVal5 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType5 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=o.CustVal5 '
				   END
				END
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @SumJoin += ' Inner Join BD_Goods_CustomVal BGC ON dtl.GoodsID = BGC.BaseID '
			END
			ELSE
			BEGIN
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @VbBDJoin += ' Inner Join BD_Goods_CustomVal BGC ON o.ID1 = BGC.BaseID '
				IF(@GoodsC1 <> 0)
				BEGIN			
				   Set @VbBDHead += ',BGC.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=BGC.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=BGC.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=BGC.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=BGC.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=BGC.CustVal1 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=BGC.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=BGC.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=BGC.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=BGC.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=BGC.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=BGC.CustVal2 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=BGC.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=BGC.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=BGC.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=BGC.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=BGC.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=BGC.CustVal3 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=BGC.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=BGC.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=BGC.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=BGC.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=BGC.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=BGC.CustVal4 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=BGC.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=BGC.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=BGC.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=BGC.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=BGC.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=BGC.CustVal5 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=BGC.CustVal5 '
				   END
				END				
			END
		END
	END
	IF @CollectType1 = 2
	BEGIN
		SET @VbSumHead += ',p.BTypeID '
		SET @VbSumG += 'p.BTypeID '
		IF @Layer1 <> 6 --汇总层级:往来单位分类1-5
		BEGIN
			SET @VbBDHead += ',bt.TypeCode[Code1],bt.TypeName[Name1] '
			SET @VbSumBDHead += ',bbs.BaseID[ID1] '
			SET @VbSumBDG += 'bbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_BType_Type bt ON bt.BTypeTypeID=o.ID1 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bt1+'
		) bbs ON bbs.BTypeID = sd.BTypeID '
		END
		ELSE
		BEGIN	
		IF @BtypeC1=0 AND @BtypeC2=0 And @BtypeC3 = 0 And @BtypeC4 = 0 And @BtypeC5 = 0 
			BEGIN				
				SET @VbBDHead += ',b.BTypeCode[Code1],b.BTypeName[Name1] '
				SET @VbSumBDHead += ',sd.BTypeID[ID1] '
				SET @VbSumBDG += 'sd.BTypeID '
				SET @VbBDJoin += '
			INNER JOIN BD_BType b ON b.BTypeID=o.ID1 '
			END
			ELSE
			BEGIN	
				IF(@Btype <> 0)	
				Begin
					SET @VbBDHead += ',b.BTypeCode[Code1],b.BTypeName[Name1] '
					SET @VbSumBDHead += ',sd.BTypeID[ID1] '
					SET @VbSumBDG += 'sd.BTypeID '
					SET @VbBDJoin += '
			INNER JOIN BD_BType b ON b.BTypeID=o.ID1 '
				End
		
		--自定义字段分类
				IF @Btype = 0
				BEGIN
					IF(@BtypeC1 <> 0)
					BEGIN
					   Set @VbSumHead += ' ,BBC.CustVal1 [BCustVal1] '
					   IF(@VbSumBDG = '')
						   SET @VbSumBDG += ' sd.BCustVal1 '
					   Else
						   SET @VbSumBDG += ',sd.BCustVal1 '
					   Set @VbSumBDHead += ',sd.BCustVal1 '
					   IF(@VbSumG = '')
						   Set @VbSumG+= ' BBC.CustVal1 '
					   else
						   Set @VbSumG+= ' ,BBC.CustVal1 '					    
					   Set @VbBDHead += ',o.BCustVal1 [BtypeDataFile1] '
					   IF(@BtypeCSourceType1 = 1)
					   BEGIN
						   Set @VbBDHead += ',o.BCustVal1 [BtypeCName1] '
					   END	   
					   ELSE IF(@BtypeCSourceType1 = 2)
					   BEGIN
						   select @BtypeSource1 = Source from BD_Btype_CustomItem where CustItemID = 1
						   IF(@BtypeSource1 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg1.GoodsName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg1 ON Bg1.GoodsID=o.BCustVal1 '	
						   END	 
						   Else IF(@BtypeSource1 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB1.BTypeName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB1 ON BB1.BTypeID=o.BCustVal1 '	
						   END	
						   Else IF(@BtypeSource1 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW1.WhsName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW1 ON BW1.WhsID=o.BCustVal1 '	
						   END
						   Else IF(@BtypeSource1 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD1.DeptName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD1 ON BD1.DeptID=o.BCustVal1 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE1.ElyName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE1 ON BE1.ElyID=o.BCustVal1 '	
						   END		        
					   END
					   ELSE IF( @BtypeCSourceType1 = 3)
					   BEGIN
						   Set @VbBDHead += ',BBC1.CustName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC1 ON BBC1.CustID=o.BCustVal1 '
					   END
					END
					IF(@BtypeC2 <> 0)
					BEGIN
					   Set @VbSumHead += ',BBC.CustVal2 [BCustVal2]'
					   IF(@VbSumG = '')
						   Set @VbSumG+= ' BBC.CustVal2 '
					   else
						   Set @VbSumG+= ' ,BBC.CustVal2 '
					   Set @VbSumBDHead += ',sd.BCustVal2 '
					   IF(@VbSumBDG = '')
						   SET @VbSumBDG += ' sd.BCustVal2 '
					   Else
						   SET @VbSumBDG += ',sd.BCustVal2 '	
					   Set @VbBDHead += ',o.BCustVal2 [BtypeDataFile2] '
					   IF(@BtypeCSourceType2 = 1)
					   BEGIN
						   Set @VbBDHead += ',o.BCustVal2 [BtypeCName2] '
					   END	   
					   ELSE IF(@BtypeCSourceType2 = 2)
					   BEGIN
						   select @BtypeSource2 = Source from BD_Btype_CustomItem where CustItemID = 2
						   IF(@BtypeSource2 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg2.GoodsName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg2 ON Bg2.GoodsID=o.BCustVal2 '	
						   END	 
						   Else IF(@BtypeSource2 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB2.BTypeName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB2 ON BB2.BTypeID=o.BCustVal2 '	
						   END	
						   Else IF(@BtypeSource2 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW2.WhsName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW2 ON BW2.WhsID=o.BCustVal2 '	
						   END
						   Else IF(@BtypeSource2 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD2.DeptName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD2 ON BD2.DeptID=o.BCustVal2 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE2.ElyName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE2 ON BE2.ElyID=o.BCustVal2 '	
						   END		        
					   END
					   ELSE IF( @BtypeCSourceType2 = 3)
					   BEGIN
						   Set @VbBDHead += ',BBC2.CustName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC2 ON BBC2.CustID=o.BCustVal2 '
					   END
					END
					IF(@BtypeC3 <> 0)
					BEGIN
					   Set @VbSumHead += ',BBC.CustVal3 [BCustVal3]'
					   IF(@VbSumG = '')
						   Set @VbSumG+= ' BBC.CustVal3 '
					   else
						   Set @VbSumG+= ' ,BBC.CustVal3 '
					   Set @VbSumBDHead += ',sd.BCustVal3 '
					   IF(@VbSumBDG = '')
						   SET @VbSumBDG += ' sd.BCustVal3 '
					   Else
						   SET @VbSumBDG += ',sd.BCustVal3 '				       
					   Set @VbBDHead += ',o.BCustVal3 [BtypeDataFile3] '
					   IF(@BtypeCSourceType3 = 1)
					   BEGIN
						   Set @VbBDHead += ',o.BCustVal3 [BtypeCName3] '
					   END	   
					   ELSE IF(@BtypeCSourceType3 = 2)
					   BEGIN
						   select @BtypeSource3 = Source from BD_Btype_CustomItem where CustItemID = 3
						   IF(@BtypeSource3 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg3.GoodsName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg3 ON Bg3.GoodsID=o.BCustVal3 '	
						   END	 
						   Else IF(@BtypeSource3 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB3.BTypeName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB3 ON BB3.BTypeID=o.BCustVal3 '	
						   END	
						   Else IF(@BtypeSource3 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW3.WhsName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW3 ON BW3.WhsID=o.BCustVal3 '	
						   END
						   Else IF(@BtypeSource3 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD3.DeptName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD3 ON BD3.DeptID=o.BCustVal3 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE3.ElyName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE3 ON BE3.ElyID=o.BCustVal3 '	
						   END		        
					   END
					   ELSE IF( @BtypeCSourceType3 = 3)
					   BEGIN
						   Set @VbBDHead += ',BBC3.CustName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC3 ON BBC3.CustID=o.BCustVal3 '
					   END
					END
					IF(@BtypeC4 <> 0)
					BEGIN
					   Set @VbSumHead += ',BBC.CustVal4 [BCustVal4]'
					   IF(@VbSumG = '')
						   Set @VbSumG+= ' BBC.CustVal4 '
					   else
						   Set @VbSumG+= ' ,BBC.CustVal4 '
					   Set @VbSumBDHead += ',sd.BCustVal4 '
					   IF(@VbSumBDG = '')
						   SET @VbSumBDG += ' sd.BCustVal4 '
					   Else
						   SET @VbSumBDG += ',sd.BCustVal4 '			       
					   Set @VbBDHead += ',o.BCustVal4 [BtypeDataFile4] '
					   IF(@BtypeCSourceType4 = 1)
					   BEGIN
						   Set @VbBDHead += ',o.BCustVal4 [BtypeCName4] '
					   END	   
					   ELSE IF(@BtypeCSourceType4 = 2)
					   BEGIN
						   select @BtypeSource4 = Source from BD_Btype_CustomItem where CustItemID = 4
						   IF(@BtypeSource4 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg4.GoodsName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg4 ON Bg4.GoodsID=o.BCustVal4 '	
						   END	 
						   Else IF(@BtypeSource4 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB4.BTypeName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB4 ON BB4.BTypeID=o.BCustVal4 '	
						   END	
						   Else IF(@BtypeSource4 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW4.WhsName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW4 ON BW4.WhsID=o.BCustVal4 '	
						   END
						   Else IF(@BtypeSource4 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD4.DeptName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD4 ON BD4.DeptID=o.BCustVal4 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE4.ElyName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE4 ON BE4.ElyID=o.BCustVal4 '	
						   END		        
					   END
					   ELSE IF( @BtypeCSourceType4 = 3)
					   BEGIN
						   Set @VbBDHead += ',BBC4.CustName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC4 ON BBC4.CustID=o.BCustVal4 '
					   END
					END
					IF(@BtypeC5 <> 0)
					BEGIN
					   Set @VbSumHead += ',BBC.CustVal5 [BCustVal5]'
					   IF(@VbSumG = '')
						   Set @VbSumG+= ' BBC.CustVal5 '
					   else
						   Set @VbSumG+= ' ,BBC.CustVal5 '
					   Set @VbSumBDHead += ',sd.BCustVal5 '
					   IF(@VbSumBDG = '')
						   SET @VbSumBDG += ' sd.BCustVal5 '
					   Else
						   SET @VbSumBDG += ',sd.BCustVal5 '				       
					   Set @VbBDHead += ',o.BCustVal5 [BtypeDataFile5] '
					   IF(@BtypeCSourceType5 = 1)
					   BEGIN
						   Set @VbBDHead += ',o.BCustVal5 [BtypeCName5] '
					   END	   
					   ELSE IF(@BtypeCSourceType5 = 2)
					   BEGIN
						   select @BtypeSource5 = Source from BD_Btype_CustomItem where CustItemID = 5
						   IF(@BtypeSource5 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg5.GoodsName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg5 ON Bg5.GoodsID=o.BCustVal5 '	
						   END	 
						   Else IF(@BtypeSource5 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB5.BTypeName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB5 ON BB5.BTypeID=o.BCustVal5 '	
						   END	
						   Else IF(@BtypeSource5 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW5.WhsName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW5 ON BW5.WhsID=o.BCustVal5 '	
						   END
						   Else IF(@BtypeSource5 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD5.DeptName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD5 ON BD5.DeptID=o.BCustVal5 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE5.ElyName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE5 ON BE5.ElyID=o.BCustVal5 '	
						   END		        
					   END
					   ELSE IF( @BtypeCSourceType5 = 3)
					   BEGIN
						   Set @VbBDHead += ',BBC5.CustName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC5 ON BBC5.CustID=o.BCustVal5 '
					   END
					END
					IF(@BtypeC1 <> 0 OR @BtypeC2 <> 0 OR @BtypeC3 <> 0 OR @BtypeC4 <> 0 OR @BtypeC5 <> 0)
						Set @SumJoin += ' left Join BD_Btype_CustomVal BBC ON p.BtypeID = BBC.BaseID '
				END
				ELSE
				BEGIN
					IF(@BtypeC1 <> 0 OR @BtypeC2 <> 0 OR @BtypeC3 <> 0 OR @BtypeC4 <> 0 OR @BtypeC5 <> 0)
						Set @VbBDJoin += ' Inner Join BD_Btype_CustomVal BBC ON o.ID1 = BBC.BaseID '
					IF(@BtypeC1 <> 0)
					BEGIN			
					   Set @VbBDHead += ',BBC.CustVal1 [BtypeDataFile1] '
					   IF(@BtypeCSourceType1 = 1)
					   BEGIN
						   Set @VbBDHead += ',BBC.CustVal1 [BtypeCName1] '
					   END	   
					   ELSE IF(@BtypeCSourceType1 = 2)
					   BEGIN
						   select @BtypeSource1 = Source from BD_Btype_CustomItem where CustItemID = 1
						   IF(@BtypeSource1 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg1.GoodsName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg1 ON Bg1.GoodsID=BBC.CustVal1 '	
						   END	 
						   Else IF(@BtypeSource1 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB1.BTypeName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB1 ON BB1.BTypeID=BBC.CustVal1 '	
						   END	
						   Else IF(@BtypeSource1 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW1.WhsName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW1 ON BW1.WhsID=BBC.CustVal1 '	
						   END
						   Else IF(@BtypeSource1 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD1.DeptName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD1 ON BD1.DeptID=BBC.CustVal1 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE1.ElyName [BtypeCName1] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE1 ON BE1.ElyID=BBC.CustVal1 '	
						   END		        
					   END
					   ELSE
					   BEGIN
						   Set @VbBDHead += ',BBC1.CustName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC1 ON BBC1.CustID=BBC.CustVal1 '
					   END
					END
					IF(@BtypeC2 <> 0)
					BEGIN
					   Set @VbBDHead += ',BBC.CustVal2 [BtypeDataFile2] '
					   IF(@BtypeCSourceType2 = 1)
					   BEGIN
						   Set @VbBDHead += ',BBC.CustVal2 [BtypeCName2] '
					   END	   
					   ELSE IF(@BtypeCSourceType2 = 2)
					   BEGIN
						   select @BtypeSource2 = Source from BD_Btype_CustomItem where CustItemID = 2
						   IF(@BtypeSource2 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg2.GoodsName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg2 ON Bg2.GoodsID=BBC.CustVal2 '	
						   END	 
						   Else IF(@BtypeSource2 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB2.BTypeName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB2 ON BB2.BTypeID=BBC.CustVal2 '	
						   END	
						   Else IF(@BtypeSource2 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW2.WhsName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW2 ON BW2.WhsID=BBC.CustVal2 '	
						   END
						   Else IF(@BtypeSource2 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD2.DeptName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD2 ON BD2.DeptID=BBC.CustVal2 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE2.ElyName [BtypeCName2] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE2 ON BE2.ElyID=BBC.CustVal2 '	
						   END		        
					   END
					   ELSE
					   BEGIN
						   Set @VbBDHead += ',BBC2.CustName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC2 ON BBC2.CustID=BBC.CustVal2 '
					   END
					END
					IF(@BtypeC3 <> 0)
					BEGIN
					   Set @VbBDHead += ',BBC.CustVal3 [BtypeDataFile3] '
					   IF(@BtypeCSourceType3 = 1)
					   BEGIN
						   Set @VbBDHead += ',BBC.CustVal3 [BtypeCName3] '
					   END	   
					   ELSE IF(@BtypeCSourceType3 = 2)
					   BEGIN
						   select @BtypeSource3 = Source from BD_Btype_CustomItem where CustItemID = 3
						   IF(@BtypeSource3 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg3.GoodsName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg3 ON Bg3.GoodsID=BBC.CustVal3 '	
						   END	 
						   Else IF(@BtypeSource3 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB3.BTypeName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB3 ON BB3.BTypeID=BBC.CustVal3 '	
						   END	
						   Else IF(@BtypeSource3 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW3.WhsName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW3 ON BW3.WhsID=BBC.CustVal3 '	
						   END
						   Else IF(@BtypeSource3 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD3.DeptName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD3 ON BD3.DeptID=BBC.CustVal3 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE3.ElyName [BtypeCName3] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE3 ON BE3.ElyID=BBC.CustVal3 '	
						   END		        
					   END
					   ELSE
					   BEGIN
						   Set @VbBDHead += ',BBC3.CustName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC3 ON BBC3.CustID=BBC.CustVal3 '
					   END
					END
					IF(@BtypeC4 <> 0)
					BEGIN
					   Set @VbBDHead += ',BBC.CustVal4 [BtypeDataFile4] '
					   IF(@BtypeCSourceType4 = 1)
					   BEGIN
						   Set @VbBDHead += ',BBC.CustVal4 [BtypeCName4] '
					   END	   
					   ELSE IF(@BtypeCSourceType4 = 2)
					   BEGIN
						   select @BtypeSource4 = Source from BD_Btype_CustomItem where CustItemID = 4
						   IF(@BtypeSource4 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg4.GoodsName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg4 ON Bg4.GoodsID=BBC.CustVal4 '	
						   END	 
						   Else IF(@BtypeSource4 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB4.BTypeName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB4 ON BB4.BTypeID=BBC.CustVal4 '	
						   END	
						   Else IF(@BtypeSource4 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW4.WhsName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW4 ON BW4.WhsID=BBC.CustVal4 '	
						   END
						   Else IF(@BtypeSource4 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD4.DeptName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD4 ON BD4.DeptID=BBC.CustVal4 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE4.ElyName [BtypeCName4] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE4 ON BE4.ElyID=BBC.CustVal4 '	
						   END		        
					   END
					   ELSE
					   BEGIN
						   Set @VbBDHead += ',BBC4.CustName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC4 ON BBC4.CustID=BBC.CustVal4 '
					   END
					END
					IF(@BtypeC5 <> 0)
					BEGIN
					   Set @VbBDHead += ',BBC.CustVal5 [BtypeDataFile5] '
					   IF(@BtypeCSourceType5 = 1)
					   BEGIN
						   Set @VbBDHead += ',BBC.CustVal5 [BtypeCName5] '
					   END	   
					   ELSE IF(@BtypeCSourceType5 = 2)
					   BEGIN
						   select @BtypeSource5 = Source from BD_Btype_CustomItem where CustItemID = 5
						   IF(@BtypeSource5 = 1)
						   BEGIN
							   Set @VbBDHead += ',Bg5.GoodsName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Goods Bg5 ON Bg5.GoodsID=BBC.CustVal5 '	
						   END	 
						   Else IF(@BtypeSource5 = 2)
						   BEGIN
							   Set @VbBDHead += ',BB5.BTypeName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Btype BB5 ON BB5.BTypeID=BBC.CustVal5 '	
						   END	
						   Else IF(@BtypeSource5 = 3)
						   BEGIN
							   Set @VbBDHead += ',BW5.WhsName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Whs BW5 ON BW5.WhsID=BBC.CustVal5 '	
						   END
						   Else IF(@BtypeSource5 = 4)
						   BEGIN
							   Set @VbBDHead += ',BD5.DeptName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Dept BD5 ON BD5.DeptID=BBC.CustVal5 '	
						   END	
						   Else 
						   BEGIN
							   Set @VbBDHead += ',BE5.ElyName [BtypeCName5] '
							   SET @VbBDJoin += ' left JOIN BD_Employee BE5 ON BE5.ElyID=BBC.CustVal5 '	
						   END		        
					   END
					   ELSE
					   BEGIN
						   Set @VbBDHead += ',BBC5.CustName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Custom BBC5 ON BBC5.CustID=BBC.CustVal5 '
					   END
					END				
				END
			END
		END
	END
	IF @CollectType1 = 3
	BEGIN
		SET @VbSumHead += ',dtl.WhsID '
		SET @VbSumG += 'dtl.WhsID '
		IF @Layer1 <> 6 --汇总层级:仓库分类1-5
		BEGIN
			SET @VbBDHead += ',wt.TypeCode[Code1],wt.TypeName[Name1] '
			SET @VbSumBDHead += ',kbs.BaseID[ID1] '
			SET @VbSumBDG += 'kbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs_Type wt ON wt.WhsTypeID=o.ID1 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bw1+'
		) kbs ON kbs.WhsID = sd.WhsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',w.WhsNO[Code1],w.WhsName[Name1] '
			SET @VbSumBDHead += ',sd.WhsID[ID1] '
			SET @VbSumBDG += 'sd.WhsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs w ON w.WhsID=o.ID1 '
		END
	END
	IF @CollectType1 = 4
	BEGIN
		SET @VbSumHead += ',bt.AreaID '
		SET @SumJoin += '
	INNER JOIN BD_Btype bt ON bt.BTypeID = p.BTypeID '
		SET @VbSumG += 'bt.AreaID '
		SET @VbBDHead += ',a.AreaNO[Code1],a.AreaName[Name1] '
		SET @VbBDJoin += '
	INNER JOIN BD_Area a ON a.AreaID=o.ID1 '
		IF @Layer1<>5 
		BEGIN
			SET @VbSumBDHead += ',abs.BaseID[ID1] '
			SET @VbSumBDG += 'abs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@ba1+'
		) abs ON abs.AreaID = sd.AreaID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.AreaID[ID1] '
			SET @VbSumBDG += 'sd.AreaID '
		END
	END
	IF @CollectType1 = 5
	BEGIN
		SET @VbSumHead += ',p.DeptID '
		SET @VbSumG += 'p.DeptID '
		SET @VbBDHead += ',d.DeptCode[Code1],d.DeptName[Name1] '
		SET @VbBDJoin += '
	INNER JOIN BD_Dept d ON d.DeptID=o.ID1 '
		IF @Layer1<>5 
		BEGIN
			SET @VbSumBDHead += ',dbs.BaseID[ID1] '
			SET @VbSumBDG += 'dbs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@bd1+'
		) dbs ON dbs.DeptID = sd.DeptID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.DeptID[ID1] '
			SET @VbSumBDG += 'sd.DeptID '
		END
	END
	IF @CollectType1 = 6
	BEGIN
		SET @VbSumHead += ',p.ElyID '
		SET @VbSumG += 'p.ElyID '
		SET @VbBDHead += ',e.ElyCode[Code1],e.ElyName[Name1] '
		SET @VbSumBDHead += ',sd.ElyID[ID1] '
		SET @VbSumBDG += 'sd.ElyID '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee e ON e.ElyID=o.ID1 '
	END
	IF @CollectType1 = 7
	BEGIN
		SET @VbSumHead += ',p.Creator '
		SET @VbSumG += 'p.Creator '
		SET @VbBDHead += ',pe.ElyCode[Code1],pe.ElyName[Name1] '
		SET @VbSumBDHead += ',sd.Creator[ID1] '
		SET @VbSumBDG += 'sd.Creator '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee pe ON pe.ElyID=o.ID1 '
	END
END
-----汇总层级一-----END
--
--商品分类
SET @bg2 = '
			SELECT pbs.BaseID,[_bg].GoodsID 
			FROM (
				SELECT GT.GoodsTypeID AS BaseID,T.GoodsTypeID FROM BD_Goods_Type GT 
				INNER JOIN BD_Goods_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) pbs
			INNER JOIN BD_Goods _bg ON [_bg].GoodsTypeID = pbs.GoodsTypeID '

--往来单位分类
SET @bt2 = '
			SELECT bbs.BaseID,[_bt].BTypeID 
			FROM (
				SELECT GT.BtypeTypeID AS BaseID,T.BtypeTypeID FROM BD_Btype_Type GT 
				INNER JOIN BD_Btype_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) bbs
			INNER JOIN BD_Btype _bt ON [_bt].BtypeTypeID = bbs.BtypeTypeID '

--仓库分类
SET @bw2 = '
			SELECT wbs.BaseID,[_bw].WhsID 
			FROM (
				SELECT GT.WhsTypeID AS BaseID,T.WhsTypeID FROM BD_Whs_Type GT 
				INNER JOIN BD_Whs_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) wbs
			INNER JOIN BD_Whs _bw ON [_bw].WhsTypeID = wbs.WhsTypeID '

--地区分类
SET @ba2 = '
			SELECT dbs.BaseID,_ba.AreaID 
			FROM (
				SELECT GT.AreaID AS BaseID,T.AreaID 
				FROM BD_Area GT 
				INNER JOIN BD_Area T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Area _ba ON [_ba].AreaID = dbs.AreaID '

--部门分类
SET @bd2 = '
			SELECT dbs.BaseID,_bd.DeptID 
			FROM (
				SELECT GT.DeptID AS BaseID,T.DeptID 
				FROM BD_Dept GT 
				INNER JOIN BD_Dept T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Dept _bd ON [_bd].DeptID = dbs.DeptID '
--
-----汇总层级二-----BEGIN
IF @CollectType2 <> 0
BEGIN
	IF @CollectType2 = 1
	BEGIN
		IF @Layer2 <> 6 --汇总层级:商品分类1-5
		BEGIN
			SET @VbSumHead += ',dtl.GoodsID '
			SET @VbSumG += ',dtl.GoodsID '
			SET @VbBDHead += ',gt.TypeCode[Code2],gt.TypeName[Name2] '
			SET @VbSumBDHead += ',pbs.BaseID[ID2] '
			SET @VbSumBDG += ',pbs.BaseID '
			SET @VbBDJoin += '
		INNER JOIN BD_Goods_Type gt ON gt.GoodsTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bg2+'
		) pbs ON pbs.GoodsID = sd.GoodsID '
		END
		ELSE
		BEGIN
			IF @Ppt1=0 AND @Ppt2=0 And @GoodsC1 = 0 And @GoodsC2 = 0 And @GoodsC3 = 0 And @GoodsC4 = 0 And @GoodsC5 = 0			
			BEGIN
				SET @VbSumHead += ',dtl.GoodsID '
				SET @VbSumG += ',dtl.GoodsID '
				SET @VbBDHead += ',g.GoodsNo[Code2],g.GoodsName[Name2],g.Model[Model2],g.GoodsAbbName[GoodsAbbName2],g.Brand[Brand2],g.Spec[Spec2],pri.BarCode[BarCode2] '
				SET @VbSumBDHead += ',sd.GoodsID[ID2] '
				SET @VbSumBDG += ',sd.GoodsID '
				SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID2 
	INNER JOIN BD_Goods_Price pri ON o.ID2 = pri.GoodsID AND pri.UnitID = 1 '
			END
			ELSE
			BEGIN
				IF @Goods<>0 
				BEGIN
					SET @VbSumHead += ',dtl.GoodsID '
					SET @VbSumG += ',dtl.GoodsID '
					SET @VbBDHead += ',g.GoodsNo[Code2],g.GoodsName[Name2],g.Model[Model2],g.GoodsAbbName[GoodsAbbName2],g.Brand[Brand2],g.Spec[Spec2],pri.BarCode[BarCode2] '
					SET @VbSumBDHead += ',sd.GoodsID[ID2] '
					SET @VbSumBDG += ',sd.GoodsID '
					SET @VbBDJoin += '
						INNER JOIN BD_Goods g ON g.GoodsID=o.ID2 
						INNER JOIN BD_Goods_Price pri ON o.ID2 = pri.GoodsID AND pri.UnitID = 1 '
				END
				IF @Ppt1<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt1ID '
					SET @VbBDHead += ',p1.Value[Ppt1Name2] '
					SET @VbSumBDHead += ',sd.Ppt1ID '
					IF @Goods<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt1ID ' 
						SET @VbSumBDG += ',sd.Ppt1ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += ',dtl.Ppt1ID '
						SET @VbSumBDG += ',sd.Ppt1ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt1 p1 ON p1.Ppt1ID=o.Ppt1ID '
				END
				IF @Ppt2<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt2ID '
					SET @VbBDHead += ',p2.Value[Ppt2Name2] '
					SET @VbSumBDHead += ',sd.Ppt2ID '
					IF @Goods<>0 OR @Ppt1<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt2ID '
						SET @VbSumBDG += ',sd.Ppt2ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += ',dtl.Ppt2ID '
						SET @VbSumBDG += ',sd.Ppt2ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt2 p2 ON p2.Ppt2ID=o.Ppt2ID '
				END
			END
			--自定义字段分类
			IF @Goods = 0
			BEGIN
				IF(@GoodsC1 <> 0)
				BEGIN
				   Set @VbSumHead += ' ,BGC.CustVal1 '
				   SET @VbSumBDG += ',sd.CustVal1 '				       
				   Set @VbSumBDHead += ',sd.CustVal1 '
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal1 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal1 '
				   Set @VbBDHead += ',o.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=o.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=o.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=o.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=o.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=o.CustVal1 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType1 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=o.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal2'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal2 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal2 '
				   Set @VbSumBDHead += ',sd.CustVal2 '
				   SET @VbSumBDG += ',sd.CustVal2 '				       
				   Set @VbBDHead += ',o.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal2 '		
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=o.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=o.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=o.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=o.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=o.CustVal2 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType2 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=o.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal3'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal3 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal3 '
				   Set @VbSumBDHead += ',sd.CustVal3 '
				   SET @VbSumBDG += ',sd.CustVal3 '				       
				   Set @VbBDHead += ',o.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal3 '		
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=o.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=o.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=o.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=o.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=o.CustVal3 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType3 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=o.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal4'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal4 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal4 '
				   Set @VbSumBDHead += ',sd.CustVal4 '
				   SET @VbSumBDG += ',sd.CustVal4 '				       
				   Set @VbBDHead += ',o.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal4 '		
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=o.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=o.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=o.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=o.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=o.CustVal4 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType4 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=o.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal5'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal5 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal5 '
				   Set @VbSumBDHead += ',sd.CustVal5 '
				   SET @VbSumBDG += ',sd.CustVal5 '				       
				   Set @VbBDHead += ',o.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal5 '		
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=o.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=o.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=o.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=o.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=o.CustVal5 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType5 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=o.CustVal5 '
				   END
				END
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @SumJoin += ' Inner Join BD_Goods_CustomVal BGC ON dtl.GoodsID = BGC.BaseID '
			END
			ELSE
			BEGIN
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @VbBDJoin += ' Inner Join BD_Goods_CustomVal BGC ON o.ID2 = BGC.BaseID '
				IF(@GoodsC1 <> 0)
				BEGIN			
				   Set @VbBDHead += ',BGC.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=BGC.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=BGC.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=BGC.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=BGC.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=BGC.CustVal1 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=BGC.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=BGC.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=BGC.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=BGC.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=BGC.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=BGC.CustVal2 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=BGC.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=BGC.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=BGC.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=BGC.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=BGC.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=BGC.CustVal3 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=BGC.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=BGC.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=BGC.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=BGC.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=BGC.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=BGC.CustVal4 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=BGC.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=BGC.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=BGC.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=BGC.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=BGC.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=BGC.CustVal5 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=BGC.CustVal5 '
				   END
				END				
			END
		END
	END
	IF @CollectType2 = 2
	BEGIN
		SET @VbSumHead += ',p.BTypeID '
		SET @VbSumG += ',p.BTypeID '
		IF @Layer2 <> 6 --汇总层级:往来单位分类1-5
		BEGIN
			SET @VbBDHead += ',bt.TypeCode[Code2],bt.TypeName[Name2] '
			SET @VbSumBDHead += ',bbs.BaseID[ID2] '
			SET @VbSumBDG += ',bbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_BType_Type bt ON bt.BTypeTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bt2+'
		) bbs ON bbs.BTypeID = sd.BTypeID '
		END
		ELSE
		BEGIN	
			IF @BtypeC1=0 AND @BtypeC2=0 And @BtypeC3 = 0 And @BtypeC4 = 0 And @BtypeC5 = 0 
			BEGIN				
				SET @VbBDHead += ',b.BTypeCode[Code2],b.BTypeName[Name2] '
				SET @VbSumBDHead += ',sd.BTypeID[ID2] '
				IF(@VbSumBDG = '')
					SET @VbSumBDG += 'sd.BTypeID '
				else
				   SET @VbSumBDG += ',sd.BTypeID '
				SET @VbBDJoin += '
				INNER JOIN BD_BType b ON b.BTypeID=o.ID2 '
			END
			ELSE
			BEGIN		
		    IF(@Btype <> 0)	
		    Begin
				SET @VbBDHead += ',b.BTypeCode[Code2],b.BTypeName[Name2] '
				SET @VbSumBDHead += ',sd.BTypeID[ID2] '
				IF(@VbSumBDG = '')
					SET @VbSumBDG += 'sd.BTypeID '
				else
				   SET @VbSumBDG += ',sd.BTypeID '
				SET @VbBDJoin += '
		INNER JOIN BD_BType b ON b.BTypeID=o.ID2 '
			End
	
	--自定义字段分类
			IF @Btype = 0
			BEGIN
				IF(@BtypeC1 <> 0)
				BEGIN
				   Set @VbSumHead += ' ,BBC.CustVal1 [BCustVal1] '
				   IF(@VbSumBDG = '')
					   SET @VbSumBDG += ' sd.BCustVal1 '
				   Else
					   SET @VbSumBDG += ',sd.BCustVal1 '
				   Set @VbSumBDHead += ',sd.BCustVal1 '
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BBC.CustVal1 '
				   else
				       Set @VbSumG+= ' ,BBC.CustVal1 '
				    
				   Set @VbBDHead += ',o.BCustVal1 [BtypeDataFile1] '
				   IF(@BtypeCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.BCustVal1 [BtypeCName1] '
				   END	   
				   ELSE IF(@BtypeCSourceType1 = 2)
				   BEGIN
				       select @BtypeSource1 = Source from BD_Btype_CustomItem where CustItemID = 1
					   IF(@BtypeSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg1.GoodsName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg1 ON Bg1.GoodsID=o.BCustVal1 '	
					   END	 
					   Else IF(@BtypeSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB1.BTypeName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB1 ON BB1.BTypeID=o.BCustVal1 '	
					   END	
					   Else IF(@BtypeSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW1.WhsName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW1 ON BW1.WhsID=o.BCustVal1 '	
					   END
					   Else IF(@BtypeSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD1.DeptName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD1 ON BD1.DeptID=o.BCustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE1.ElyName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE1 ON BE1.ElyID=o.BCustVal1 '	
					   END		        
				   END
				   ELSE IF( @BtypeCSourceType1 = 3)
				   BEGIN
				       Set @VbBDHead += ',BBC1.CustName [BtypeCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC1 ON BBC1.CustID=o.BCustVal1 '
				   END
				END
				IF(@BtypeC2 <> 0)
				BEGIN
				   Set @VbSumHead += ',BBC.CustVal2 [BCustVal2]'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BBC.CustVal2 '
				   else
				       Set @VbSumG+= ' ,BBC.CustVal2 '
				   Set @VbSumBDHead += ',sd.BCustVal2 '
				   IF(@VbSumBDG = '')
					   SET @VbSumBDG += ' sd.BCustVal2 '
				   Else
					   SET @VbSumBDG += ',sd.BCustVal2 '	
				   Set @VbBDHead += ',o.BCustVal2 [BtypeDataFile2] '
				   IF(@BtypeCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.BCustVal2 [BtypeCName2] '
				   END	   
				   ELSE IF(@BtypeCSourceType2 = 2)
				   BEGIN
				       select @BtypeSource2 = Source from BD_Btype_CustomItem where CustItemID = 2
					   IF(@BtypeSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg2.GoodsName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg2 ON Bg2.GoodsID=o.BCustVal2 '	
					   END	 
					   Else IF(@BtypeSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB2.BTypeName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB2 ON BB2.BTypeID=o.BCustVal2 '	
					   END	
					   Else IF(@BtypeSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW2.WhsName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW2 ON BW2.WhsID=o.BCustVal2 '	
					   END
					   Else IF(@BtypeSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD2.DeptName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD2 ON BD2.DeptID=o.BCustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE2.ElyName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE2 ON BE2.ElyID=o.BCustVal2 '	
					   END		        
				   END
				   ELSE IF( @BtypeCSourceType2 = 3)
				   BEGIN
				       Set @VbBDHead += ',BBC2.CustName [BtypeCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC2 ON BBC2.CustID=o.BCustVal2 '
				   END
				END
				IF(@BtypeC3 <> 0)
				BEGIN
				   Set @VbSumHead += ',BBC.CustVal3 [BCustVal3]'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BBC.CustVal3 '
				   else
				       Set @VbSumG+= ' ,BBC.CustVal3 '
				   Set @VbSumBDHead += ',sd.BCustVal3 '
				   IF(@VbSumBDG = '')
					   SET @VbSumBDG += ' sd.BCustVal3 '
				   Else
					   SET @VbSumBDG += ',sd.BCustVal3 '	
				   Set @VbBDHead += ',o.BCustVal3 [BtypeDataFile3] '
				   IF(@BtypeCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.BCustVal3 [BtypeCName3] '
				   END	   
				   ELSE IF(@BtypeCSourceType3 = 2)
				   BEGIN
				       select @BtypeSource3 = Source from BD_Btype_CustomItem where CustItemID = 3
					   IF(@BtypeSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg3.GoodsName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg3 ON Bg3.GoodsID=o.BCustVal3 '	
					   END	 
					   Else IF(@BtypeSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB3.BTypeName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB3 ON BB3.BTypeID=o.BCustVal3 '	
					   END	
					   Else IF(@BtypeSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW3.WhsName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW3 ON BW3.WhsID=o.BCustVal3 '	
					   END
					   Else IF(@BtypeSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD3.DeptName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD3 ON BD3.DeptID=o.BCustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE3.ElyName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE3 ON BE3.ElyID=o.BCustVal3 '	
					   END		        
				   END
				   ELSE IF( @BtypeCSourceType3 = 3)
				   BEGIN
				       Set @VbBDHead += ',BBC3.CustName [BtypeCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC3 ON BBC3.CustID=o.BCustVal3 '
				   END
				END
				IF(@BtypeC4 <> 0)
				BEGIN
				   Set @VbSumHead += ',BBC.CustVal4 [BCustVal4]'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BBC.CustVal4 '
				   else
				       Set @VbSumG+= ' ,BBC.CustVal4 '
				   Set @VbSumBDHead += ',sd.BCustVal4 '
				   IF(@VbSumBDG = '')
					   SET @VbSumBDG += ' sd.BCustVal4 '
				   Else
					   SET @VbSumBDG += ',sd.BCustVal4 '			       
				   Set @VbBDHead += ',o.BCustVal4 [BtypeDataFile4] '
				   IF(@BtypeCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.BCustVal4 [BtypeCName4] '
				   END	   
				   ELSE IF(@BtypeCSourceType4 = 2)
				   BEGIN
				       select @BtypeSource4 = Source from BD_Btype_CustomItem where CustItemID = 4
					   IF(@BtypeSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg4.GoodsName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg4 ON Bg4.GoodsID=o.BCustVal4 '	
					   END	 
					   Else IF(@BtypeSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB4.BTypeName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB4 ON BB4.BTypeID=o.BCustVal4 '	
					   END	
					   Else IF(@BtypeSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW4.WhsName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW4 ON BW4.WhsID=o.BCustVal4 '	
					   END
					   Else IF(@BtypeSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD4.DeptName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD4 ON BD4.DeptID=o.BCustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE4.ElyName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE4 ON BE4.ElyID=o.BCustVal4 '	
					   END		        
				   END
				   ELSE IF( @BtypeCSourceType4 = 3)
				   BEGIN
				       Set @VbBDHead += ',BBC4.CustName [BtypeCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC4 ON BBC4.CustID=o.BCustVal4 '
				   END
				END
				IF(@BtypeC5 <> 0)
				BEGIN
				   Set @VbSumHead += ',BBC.CustVal5 [BCustVal5]'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BBC.CustVal5 '
				   else
				       Set @VbSumG+= ' ,BBC.CustVal5 '
				   Set @VbSumBDHead += ',sd.BCustVal5 '
				   IF(@VbSumBDG = '')
					   SET @VbSumBDG += ' sd.BCustVal5 '
				   Else
					   SET @VbSumBDG += ',sd.BCustVal5 '				       
				   Set @VbBDHead += ',o.BCustVal5 [BtypeDataFile5] '
				   IF(@BtypeCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.BCustVal5 [BtypeCName5] '
				   END	   
				   ELSE IF(@BtypeCSourceType5 = 2)
				   BEGIN
				       select @BtypeSource5 = Source from BD_Btype_CustomItem where CustItemID = 5
					   IF(@BtypeSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg5.GoodsName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg5 ON Bg5.GoodsID=o.BCustVal5 '	
					   END	 
					   Else IF(@BtypeSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB5.BTypeName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB5 ON BB5.BTypeID=o.BCustVal5 '	
					   END	
					   Else IF(@BtypeSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW5.WhsName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW5 ON BW5.WhsID=o.BCustVal5 '	
					   END
					   Else IF(@BtypeSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD5.DeptName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD5 ON BD5.DeptID=o.BCustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE5.ElyName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE5 ON BE5.ElyID=o.BCustVal5 '	
					   END		        
				   END
				   ELSE IF( @BtypeCSourceType5 = 3)
				   BEGIN
				       Set @VbBDHead += ',BBC5.CustName [BtypeCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC5 ON BBC5.CustID=o.BCustVal5 '
				   END
				END
				IF(@BtypeC1 <> 0 OR @BtypeC2 <> 0 OR @BtypeC3 <> 0 OR @BtypeC4 <> 0 OR @BtypeC5 <> 0)
					Set @SumJoin += ' left Join BD_Btype_CustomVal BBC ON p.BtypeID = BBC.BaseID '
			END
			ELSE
			BEGIN
				IF(@BtypeC1 <> 0 OR @BtypeC2 <> 0 OR @BtypeC3 <> 0 OR @BtypeC4 <> 0 OR @BtypeC5 <> 0)
					Set @VbBDJoin += ' Inner Join BD_Btype_CustomVal BBC ON o.ID2 = BBC.BaseID '
				IF(@BtypeC1 <> 0)
				BEGIN			
				   Set @VbBDHead += ',BBC.CustVal1 [BtypeDataFile1] '
				   IF(@BtypeCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',BBC.CustVal1 [BtypeCName1] '
				   END	   
				   ELSE IF(@BtypeCSourceType1 = 2)
				   BEGIN
				       select @BtypeSource1 = Source from BD_Btype_CustomItem where CustItemID = 1
					   IF(@BtypeSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg1.GoodsName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg1 ON Bg1.GoodsID=BBC.CustVal1 '	
					   END	 
					   Else IF(@BtypeSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB1.BTypeName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB1 ON BB1.BTypeID=BBC.CustVal1 '	
					   END	
					   Else IF(@BtypeSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW1.WhsName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW1 ON BW1.WhsID=BBC.CustVal1 '	
					   END
					   Else IF(@BtypeSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD1.DeptName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD1 ON BD1.DeptID=BBC.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE1.ElyName [BtypeCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE1 ON BE1.ElyID=BBC.CustVal1 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BBC1.CustName [BtypeCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC1 ON BBC1.CustID=BBC.CustVal1 '
				   END
				END
				IF(@BtypeC2 <> 0)
				BEGIN
				   Set @VbBDHead += ',BBC.CustVal2 [BtypeDataFile2] '
				   IF(@BtypeCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',BBC.CustVal2 [BtypeCName2] '
				   END	   
				   ELSE IF(@BtypeCSourceType2 = 2)
				   BEGIN
				       select @BtypeSource2 = Source from BD_Btype_CustomItem where CustItemID = 2
					   IF(@BtypeSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg2.GoodsName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg2 ON Bg2.GoodsID=BBC.CustVal2 '	
					   END	 
					   Else IF(@BtypeSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB2.BTypeName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB2 ON BB2.BTypeID=BBC.CustVal2 '	
					   END	
					   Else IF(@BtypeSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW2.WhsName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW2 ON BW2.WhsID=BBC.CustVal2 '	
					   END
					   Else IF(@BtypeSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD2.DeptName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD2 ON BD2.DeptID=BBC.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE2.ElyName [BtypeCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE2 ON BE2.ElyID=BBC.CustVal2 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BBC2.CustName [BtypeCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC2 ON BBC2.CustID=BBC.CustVal2 '
				   END
				END
				IF(@BtypeC3 <> 0)
				BEGIN
				   Set @VbBDHead += ',BBC.CustVal3 [BtypeDataFile3] '
				   IF(@BtypeCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',BBC.CustVal3 [BtypeCName3] '
				   END	   
				   ELSE IF(@BtypeCSourceType3 = 2)
				   BEGIN
				       select @BtypeSource3 = Source from BD_Btype_CustomItem where CustItemID = 3
					   IF(@BtypeSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg3.GoodsName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg3 ON Bg3.GoodsID=BBC.CustVal3 '	
					   END	 
					   Else IF(@BtypeSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB3.BTypeName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB3 ON BB3.BTypeID=BBC.CustVal3 '	
					   END	
					   Else IF(@BtypeSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW3.WhsName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW3 ON BW3.WhsID=BBC.CustVal3 '	
					   END
					   Else IF(@BtypeSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD3.DeptName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD3 ON BD3.DeptID=BBC.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE3.ElyName [BtypeCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE3 ON BE3.ElyID=BBC.CustVal3 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BBC3.CustName [BtypeCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC3 ON BBC3.CustID=BBC.CustVal3 '
				   END
				END
				IF(@BtypeC4 <> 0)
				BEGIN
				   Set @VbBDHead += ',BBC.CustVal4 [BtypeDataFile4] '
				   IF(@BtypeCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',BBC.CustVal4 [BtypeCName4] '
				   END	   
				   ELSE IF(@BtypeCSourceType4 = 2)
				   BEGIN
				       select @BtypeSource4 = Source from BD_Btype_CustomItem where CustItemID = 4
					   IF(@BtypeSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg4.GoodsName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg4 ON Bg4.GoodsID=BBC.CustVal4 '	
					   END	 
					   Else IF(@BtypeSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB4.BTypeName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB4 ON BB4.BTypeID=BBC.CustVal4 '	
					   END	
					   Else IF(@BtypeSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW4.WhsName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW4 ON BW4.WhsID=BBC.CustVal4 '	
					   END
					   Else IF(@BtypeSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD4.DeptName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD4 ON BD4.DeptID=BBC.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE4.ElyName [BtypeCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE4 ON BE4.ElyID=BBC.CustVal4 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BBC4.CustName [BtypeCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC4 ON BBC4.CustID=BBC.CustVal4 '
				   END
				END
				IF(@BtypeC5 <> 0)
				BEGIN
				   Set @VbBDHead += ',BBC.CustVal5 [BtypeDataFile5] '
				   IF(@BtypeCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',BBC.CustVal5 [BtypeCName5] '
				   END	   
				   ELSE IF(@BtypeCSourceType5 = 2)
				   BEGIN
				       select @BtypeSource5 = Source from BD_Btype_CustomItem where CustItemID = 5
					   IF(@BtypeSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',Bg5.GoodsName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods Bg5 ON Bg5.GoodsID=BBC.CustVal5 '	
					   END	 
					   Else IF(@BtypeSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',BB5.BTypeName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype BB5 ON BB5.BTypeID=BBC.CustVal5 '	
					   END	
					   Else IF(@BtypeSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',BW5.WhsName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs BW5 ON BW5.WhsID=BBC.CustVal5 '	
					   END
					   Else IF(@BtypeSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',BD5.DeptName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept BD5 ON BD5.DeptID=BBC.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',BE5.ElyName [BtypeCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee BE5 ON BE5.ElyID=BBC.CustVal5 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BBC5.CustName [BtypeCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BBC5 ON BBC5.CustID=BBC.CustVal5 '
				   END
				END				
			END
		END
		END
	END
	IF @CollectType2 = 3
	BEGIN
		SET @VbSumHead += ',dtl.WhsID '
		SET @VbSumG += ',dtl.WhsID '
		IF @Layer2 <> 6 --汇总层级:仓库分类1-5
		BEGIN
			SET @VbBDHead += ',wt.TypeCode[Code2],wt.TypeName[Name2] '
			SET @VbSumBDHead += ',kbs.BaseID[ID2] '
			SET @VbSumBDG += ',kbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs_Type wt ON wt.WhsTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bw2+'
		) kbs ON kbs.WhsID = sd.WhsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',w.WhsNO[Code2],w.WhsName[Name2] '
			SET @VbSumBDHead += ',sd.WhsID[ID2] '
			SET @VbSumBDG += ',sd.WhsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs w ON w.WhsID=o.ID2 '
		END
	END
	IF @CollectType2 = 4
	BEGIN
		SET @VbSumHead += ',bt.AreaID '
		SET @SumJoin += '
	INNER JOIN BD_Btype bt ON bt.BTypeID = p.BTypeID '
		SET @VbSumG += ',bt.AreaID '
		SET @VbBDHead += ',a.AreaNO[Code2],a.AreaName[Name2] '
		SET @VbBDJoin += '
	INNER JOIN BD_Area a ON a.AreaID=o.ID2 '
		IF @Layer2<>5 
		BEGIN
			SET @VbSumBDHead += ',abs.BaseID[ID2] '
			SET @VbSumBDG += ',abs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@ba2+'
		) abs ON abs.AreaID = sd.AreaID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.AreaID[ID2] '
			SET @VbSumBDG += ',sd.AreaID '
		END
	END
	IF @CollectType2 = 5
	BEGIN
		SET @VbSumHead += ',p.DeptID '
		SET @VbSumG += ',p.DeptID '
		SET @VbBDHead += ',d.DeptCode[Code2],d.DeptName[Name2] '
		SET @VbBDJoin += '
	INNER JOIN BD_Dept d ON d.DeptID=o.ID2 '
		IF @Layer2<>5 
		BEGIN
			SET @VbSumBDHead += ',dbs.BaseID[ID2] '
			SET @VbSumBDG += ',dbs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@bd2+'
		) dbs ON dbs.DeptID = sd.DeptID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.DeptID[ID2] '
			SET @VbSumBDG += ',sd.DeptID '
		END
	END
	IF @CollectType2 = 6
	BEGIN
		SET @VbSumHead += ',p.ElyID '
		SET @VbSumG += ',p.ElyID '
		SET @VbBDHead += ',e.ElyCode[Code2],e.ElyName[Name2] '
		SET @VbSumBDHead += ',sd.ElyID[ID2] '
		SET @VbSumBDG += ',sd.ElyID '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee e ON e.ElyID=o.ID2 '
	END
	IF @CollectType2 = 7
	BEGIN
		SET @VbSumHead += ',p.Creator '
		SET @VbSumG += ',p.Creator '
		SET @VbBDHead += ',pe.ElyCode[Code2],pe.ElyName[Name2] '
		SET @VbSumBDHead += ',sd.Creator[ID2] '
		SET @VbSumBDG += ',sd.Creator '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee pe ON pe.ElyID=o.ID2 '
	END
END
-----汇总层级二-----END
declare @str varchar(10)
select @str = SUBSTRING(@VbSumG,1,1)
if(@str = ',')
	Select @VbSumG = SUBSTRING(@VbSumG,2,len(@VbSumG))
IF @VbSumG <> ''
	SET @VbSumG = '
	GROUP BY ' + @VbSumG
select @str = SUBSTRING(@VbSumBDG,1,1)
if(@str = ',')
	Select @VbSumBDG = SUBSTRING(@VbSumBDG,2,len(@VbSumBDG))
IF @VbSumBDG <> ''
	SET @VbSumBDG = '
		GROUP BY ' + @VbSumBDG
if(@Privilege = 1 and @VbSumG <> '')
	SET @VbSumG += ',p.BillNo '

--排序BEGIN
SET @SqlOrder=''
--select @CollectType1,@OrderType1,@CollectType2,@OrderType2
IF @OrderType1<>0
BEGIN
	IF (@CollectType1 = 1 AND @OrderType1 IN (1,3)) OR (@CollectType1 = 2 AND @OrderType1 IN (5,7)) OR (@CollectType1 = 3 AND @OrderType1 IN (9,11)) OR (@CollectType1 = 4 AND @OrderType1 = 13) OR (@CollectType1 = 5 AND @OrderType1 = 15) OR (@CollectType1 = 6 AND @OrderType1 = 17) OR (@CollectType1 = 7 AND @OrderType1 = 29)
		SET @SqlOrder += 'Code1'
	IF (@CollectType1 = 1 AND @OrderType1 IN (2,4)) OR (@CollectType1 = 2 AND @OrderType1 IN (6,8)) OR (@CollectType1 = 3 AND @OrderType1 IN (10,12)) OR (@CollectType1 = 4 AND @OrderType1 = 14) OR (@CollectType1 = 5 AND @OrderType1 = 16) OR (@CollectType1 = 6 AND @OrderType1 = 18) OR (@CollectType1 = 7 AND @OrderType1 = 30)
		SET @SqlOrder += 'Name1'
	IF (@CollectType2 = 1 AND @OrderType1 IN (1,3)) OR (@CollectType2 = 2 AND @OrderType1 IN (5,7)) OR (@CollectType2 = 3 AND @OrderType1 IN (9,11)) OR (@CollectType2 = 4 AND @OrderType1 = 13) OR (@CollectType2 = 5 AND @OrderType1 = 15) OR (@CollectType2 = 6 AND @OrderType1 = 17) OR (@CollectType2 = 7 AND @OrderType1 = 29)
		SET @SqlOrder += 'Code2'
	IF (@CollectType2 = 1 AND @OrderType1 IN (2,4)) OR (@CollectType2 = 2 AND @OrderType1 IN (6,8)) OR (@CollectType2 = 3 AND @OrderType1 IN (10,12)) OR (@CollectType2 = 4 AND @OrderType1 = 14) OR (@CollectType2 = 5 AND @OrderType1 = 16) OR (@CollectType2 = 6 AND @OrderType1 = 18) OR (@CollectType2 = 7 AND @OrderType1 = 30)
		SET @SqlOrder += 'Name2'
	IF @OrderType1=19 SET @SqlOrder+='BSQty' IF @OrderType1=20 SET @SqlOrder+='AVGPrice' IF @OrderType1=21 SET @SqlOrder+='SaleTotal' IF @OrderType1=22 SET @SqlOrder+='AVGCostPrice'
	IF @OrderType1=23 SET @SqlOrder+='CostTotal' IF @OrderType1=24 SET @SqlOrder+='Profit' IF @OrderType1=25 SET @SqlOrder+='ProfitRate' IF @OrderType1=26 SET @SqlOrder+='GiftQty'
	IF @CollectType1=1 AND @OrderType1=27 SET @SqlOrder+='Ppt1Name1' IF @CollectType1=1 AND @OrderType1=28 SET @SqlOrder+='Ppt2Name1'
	IF @CollectType2=1 AND @OrderType1=27 SET @SqlOrder+='Ppt1Name2' IF @CollectType2=1 AND @OrderType1=28 SET @SqlOrder+='Ppt2Name2'
	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=31 SET @SqlOrder+='GoodsCName1'	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=32 SET @SqlOrder+='GoodsCName2'
	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=33 SET @SqlOrder+='GoodsCName3'  IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=34 SET @SqlOrder+='GoodsCName4'
	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=35 SET @SqlOrder+='GoodsCName5'
	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType1=36 SET @SqlOrder+='BtypeCName1'	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType1=37 SET @SqlOrder+='BtypeCName2'
	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType1=38 SET @SqlOrder+='BtypeCName3'  IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType1=39 SET @SqlOrder+='BtypeCName4'
	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType1=40 SET @SqlOrder+='BtypeCName5'
	IF @OrderSeq1=2 SET @SqlOrder+= ' DESC'
END
IF @OrderType2<>0
BEGIN
	IF (@CollectType1 = 1 AND @OrderType2 IN (1,3)) OR (@CollectType1 = 2 AND @OrderType2 IN (5,7)) OR (@CollectType1 = 3 AND @OrderType2 IN (9,11)) OR (@CollectType1 = 4 AND @OrderType2 = 13) OR (@CollectType1 = 5 AND @OrderType2 = 15) OR (@CollectType1 = 6 AND @OrderType2 = 17) OR (@CollectType1 = 7 AND @OrderType2 = 29)
		SET @SqlOrder += ',Code1'
	IF (@CollectType1 = 1 AND @OrderType2 IN (2,4)) OR (@CollectType1 = 2 AND @OrderType2 IN (6,8)) OR (@CollectType1 = 3 AND @OrderType2 IN (10,12)) OR (@CollectType1 = 4 AND @OrderType2 = 14) OR (@CollectType1 = 5 AND @OrderType2 = 16) OR (@CollectType1 = 6 AND @OrderType2 = 18) OR (@CollectType1 = 7 AND @OrderType2 = 30)
		SET @SqlOrder += ',Name1'
	IF (@CollectType2 = 1 AND @OrderType2 IN (1,3)) OR (@CollectType2 = 2 AND @OrderType2 IN (5,7)) OR (@CollectType2 = 3 AND @OrderType2 IN (9,11)) OR (@CollectType2 = 4 AND @OrderType2 = 13) OR (@CollectType2 = 5 AND @OrderType2 = 15) OR (@CollectType2 = 6 AND @OrderType2 = 17) OR (@CollectType2 = 7 AND @OrderType2 = 29)
		SET @SqlOrder += ',Code2'
	IF (@CollectType2 = 1 AND @OrderType2 IN (2,4)) OR (@CollectType2 = 2 AND @OrderType2 IN (6,8)) OR (@CollectType2 = 3 AND @OrderType2 IN (10,12)) OR (@CollectType2 = 4 AND @OrderType2 = 14) OR (@CollectType2 = 5 AND @OrderType2 = 16) OR (@CollectType2 = 6 AND @OrderType2 = 18) OR (@CollectType2 = 7 AND @OrderType2 = 30)
		SET @SqlOrder += ',Name2'
	IF @OrderType2=19 SET @SqlOrder+=',BSQty' IF @OrderType2=20 SET @SqlOrder+=',AVGPrice' IF @OrderType2=21 SET @SqlOrder+=',SaleTotal' IF @OrderType2=22 SET @SqlOrder+=',AVGCostPrice'
	IF @OrderType2=23 SET @SqlOrder+=',CostTotal' IF @OrderType2=24 SET @SqlOrder+=',Profit' IF @OrderType2=25 SET @SqlOrder+=',ProfitRate' IF @OrderType2=26 SET @SqlOrder+=',GiftQty'
	IF @CollectType1=1 AND @OrderType2=27 SET @SqlOrder+=',Ppt1Name1' IF @CollectType1=1 AND @OrderType2=28 SET @SqlOrder+=',Ppt2Name1'
	IF @CollectType2=1 AND @OrderType2=27 SET @SqlOrder+=',Ppt1Name2' IF @CollectType2=1 AND @OrderType2=28 SET @SqlOrder+=',Ppt2Name2'
	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=31 SET @SqlOrder+=',GoodsCName1'	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=32 SET @SqlOrder+=',GoodsCName2'
	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=33 SET @SqlOrder+=',GoodsCName3'  IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=34 SET @SqlOrder+=',GoodsCName4'
	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=35 SET @SqlOrder+=',GoodsCName5'
	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType2=36 SET @SqlOrder+=',BtypeCName1'	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType2=37 SET @SqlOrder+=',BtypeCName2'
	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType2=38 SET @SqlOrder+=',BtypeCName3'  IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType2=39 SET @SqlOrder+=',BtypeCName4'
	IF (@CollectType1=2 or @CollectType2 = 2) AND @OrderType2=40 SET @SqlOrder+=',BtypeCName5'
	IF @OrderSeq2=2 SET @SqlOrder+= ' DESC'
END
IF @SqlOrder='' SET @SqlOrder='BSQty'
--排序END

SET @SumData=';WITH SumData AS('

SET @SumHead='SUM(dtl.BSQty)[BSQtyST]
	,SUM(dtl.TaxTotal)[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)[GiftQtyST] '
SET @SumHeadFH='SUM(dtl.BSQty)*-1[BSQtyST]
	,SUM(dtl.TaxTotal)*-1[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)*-1[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)*-1[GiftQtyST] '
IF(@Privilege = 1)
BEGIN
	Set @SumHead += ' ,Sum(distinct p.Privilege) as [Privilege] '
	Set @SumHeadFH += ' ,Sum(distinct p.Privilege)*-1 as [Privilege] ' 
END
IF NOT (@SaleBillOut<>0 AND @SaleBillIn<>0)
	SET @SumHeadFH = @SumHead
SET @Sql_PPB='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill p 
	INNER JOIN PD_SellDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PPB_His='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill_His p 
	INNER JOIN PD_SellDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PRB='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill p 
	INNER JOIN PD_SellRetDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PRB_His='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill_His p 
	INNER JOIN PD_SellRetDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG

IF @IsHistory = 0
BEGIN
	IF @SaleBillOut<>0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL '+@Sql_PRB+')'
	END
	IF @SaleBillOut<>0 AND @SaleBillIn=0
	BEGIN
		SET @SumData+=@Sql_PPB+')'
	END
	IF @SaleBillOut=0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PRB+')'
	END
END
ELSE
BEGIN
	IF @SaleBillOut<>0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL '+@Sql_PRB+'
	UNION ALL'+@Sql_PPB_His+'
	UNION ALL '+@Sql_PRB_His+')'
	END
	IF @SaleBillOut<>0 AND @SaleBillIn=0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL'+@Sql_PPB_His+')'
	END
	IF @SaleBillOut=0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PRB+'
	UNION ALL'+@Sql_PRB_His+')'
	END
END

SET @BillData = '
,BillData AS( 
	SELECT o.*'
	
SET @BDHead='SUM(sd.BSQtyST)[BSQty]
		,SUM(sd.SaleTotalST)[SaleTotal]
		,SUM(sd.CostTotalST)[CostTotal]
		,SUM(sd.GiftQtyST)[GiftQty] '
IF(@Privilege = 1)
BEGIN
	Set @BDHead += ',SUM(sd.Privilege)[Privilege] '
END
SET @AVGPrice = '
	,CASE WHEN o.BSQty=0 THEN NULL ELSE ABS(CAST( CAST(o.SaleTotal AS FLOAT)/o.BSQty AS DECIMAL(20,8) )) END [AVGPrice] '
IF(@Privilege = 1)
BEGIN
	Set @AVGPrice += ',o.SaleTotal-o.Privilege [SalePrivilege] '
END
SET @AVGCostPrice = '
	,CASE WHEN o.BSQty=0  THEN NULL ELSE  ABS(CAST( CAST(o.CostTotal AS FLOAT)/o.BSQty AS DECIMAL(20,8) )) END[AVGCostPrice] '
IF(@Privilege = 0)
BEGIN
	SET	@Profit ='
		,o.SaleTotal-o.CostTotal [Profit] '
	SET @ProfitRate = '
		,CASE WHEN o.SaleTotal=0 THEN NULL ELSE CAST( ((o.SaleTotal-o.CostTotal)/o.SaleTotal)*100 AS DECIMAL(20,2) ) END[ProfitRate] '
END
ELSE
BEGIN
	SET	@Profit ='
		,o.SaleTotal-o.Privilege-o.CostTotal [Profit] '
	SET @ProfitRate = '
		,CASE WHEN (o.SaleTotal-o.Privilege)=0 THEN NULL ELSE CAST( ((o.SaleTotal-o.Privilege-o.CostTotal)/(o.SaleTotal-o.Privilege))*100 AS DECIMAL(20,2) ) END[ProfitRate] '
END
IF @OrderType1 = 20 OR @OrderType2 = 20 SET @VbBDHead += @AVGPrice
IF @OrderType1 = 22 OR @OrderType2 = 22 SET @VbBDHead += @AVGCostPrice
IF @OrderType1 = 24 OR @OrderType2 = 24 SET @VbBDHead += @Profit
IF @OrderType1 = 25 OR @OrderType2 = 25 SET @VbBDHead += @ProfitRate
SET @BillData += @VbBDHead + '
	FROM ( 
		SELECT ' + @BDHead + @VbSumBDHead + '
		FROM SumData sd ' + @CFBDJoin + @VbSumBDG + '
	) o ' + @VbBDJoin + '
)'

SET @Sql += 'SET NOCOUNT ON;
' + @SumData + @BillData + '
,PageData as(
	SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ' + @SqlOrder + ') AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData) AS B
	WHERE ROWID>(@pageNo-1)*@pageSize 
	AND ROWID<=@pageNo*@pageSize 
)

SELECT o.* '
IF @OrderType1 <> 20 AND @OrderType2 <> 20 SET @Sql += @AVGPrice
IF @OrderType1 <> 22 AND @OrderType2 <> 22 SET @Sql += @AVGCostPrice
IF @OrderType1 <> 24 AND @OrderType2 <> 24 SET @Sql += @Profit
IF @OrderType1 <> 25 AND @OrderType2 <> 25 SET @Sql += @ProfitRate
IF (@CollectType1=1 AND @Layer1=6) OR (@CollectType2=1 AND @Layer2=6)
	IF @Goods<>0 OR (@Ppt1=0 AND @Ppt2=0 And @GoodsC1=0 And @GoodsC2=0 And @GoodsC3=0 And @GoodsC4=0 And @GoodsC5=0 )
		SET @Sql += '
	,gp1.Unit[Unit]
	,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3]
	,gp1.Convfactor[Convfactor1],ISNULL(gp2.Convfactor,1)[Convfactor2],ISNULL(gp3.Convfactor,1)[Convfactor3] '
SET @Sql += '
	FROM PageData o '
IF @CollectType1=1 AND @Layer1=6
	IF @Goods<>0 OR (@Ppt1=0 AND @Ppt2=0 And @GoodsC1=0 And @GoodsC2=0 And @GoodsC3=0 And @GoodsC4=0 And @GoodsC5=0 )
		SET @Sql += '
	LEFT JOIN BD_Goods_Price gp1 ON gp1.GoodsID=o.ID1 AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON gp2.GoodsID=o.ID1 AND gp2.UnitID=2 
	LEFT JOIN BD_Goods_Price gp3 ON gp3.GoodsID=o.ID1 AND gp3.UnitID=3 '
IF @CollectType2=1 AND @Layer2=6
	IF @Goods<>0 OR (@Ppt1=0 AND @Ppt2=0 And @GoodsC1=0 And @GoodsC2=0 And @GoodsC3=0 And @GoodsC4=0 And @GoodsC5=0 )
		SET @Sql += '
	LEFT JOIN BD_Goods_Price gp1 ON gp1.GoodsID=o.ID2 AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON gp2.GoodsID=o.ID2 AND gp2.UnitID=2 
	LEFT JOIN BD_Goods_Price gp3 ON gp3.GoodsID=o.ID2 AND gp3.UnitID=3 '
SET @Sql += '
	ORDER BY ROWID '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--print @Sql
DECLARE @curPos INT = 1 , @count INT = 1
WHILE (@curPos < len(@Sql))
BEGIN
	PRINT substring(@Sql, @curPos, @curPos + 3999)
	SET @curPos += 3999 + 1
	SET @count += 1
END 

EXEC SP_EXECUTESQL @Sql,N'@pageNo INT,@pageSize INT,@BillDateType INT,@BillStartDate DATETIME,@BillEndDate DATETIME
,@BTypeID VARCHAR(max),@DeptID VARCHAR(max),@ElyID VARCHAR(max),@CreatorID VARCHAR(max),@WhsID VARCHAR(max),@GoodsID VARCHAR(1000)
,@GoodsNo VARCHAR(20),@GoodsName VARCHAR(50),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@GiftState INT
,@CollectType1 INT,@Layer1 INT,@CollectType2 INT,@Layer2 INT,@OperatorID INT
,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT'
,@pageNo,@pageSize,@BillDateType,@BillStartDate,@BillEndDate
,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@GoodsID,@GoodsNo,@GoodsName,@Summary,@Description,@Remark,@GiftState
,@CollectType1,@Layer1,@CollectType2,@Layer2,@OperatorID
, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
END


GO






/****** Object:  StoredProcedure [UP_PD_QuerySAMDTLSum]    Script Date: 12/08/2014 16:44:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySAMDTLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySAMDTLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySAMDTLSum]    Script Date: 12/08/2014 16:44:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-08
	描述：调拨申请管理(明细)Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySAMDTLSum]
(
	@BillNo BIGINT=0,
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@StopTag INT=9,					--中止状态
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@SqlHead VARCHAR(500),@SqlJoin NVARCHAR(MAX)='',@SqlJoin2 NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@HisStr VARCHAR(20)='_His'
IF EXISTS (SELECT 1 FROM PD_AllotReqBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''
IF @GoodsID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID ' 
/*权限使用公用方法*/
IF( dbo.UF_BD_IsAllKtypeLimit(@OperatorID)=0 )
BEGIN
	SET @SqlJoin2 = @SqlJoin + '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs2 ON rWhs2.WhsID=dtl.OutWhsID '
	SET @SqlJoin +='
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs1 ON rWhs1.WhsID=dtl.InWhsID '
END
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin2 = @SqlJoin + '
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs2 ON rWhs2.WhsID=dtl.OutWhsID '
		SET @SqlJoin += '
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs1 ON rWhs1.WhsID=dtl.InWhsID '
	END
END
*/

SET @SqlParam +='
	WHERE dtl.BillNo=@BillNo '
IF @StopTag <> 9
	SET @SqlParam +='AND dtl.StopTag=@StopTag '
	
/*新增商品查询条件 start 150901*/
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @SqlParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @SqlParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @SqlParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @SqlParam += N' AND goods.Spec = @Spec '  
   END
IF @Model <> '' OR @AbbName <> '' OR @Brand <> '' OR @Spec <> ''
   BEGIN
	   SET @SqlJoin += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
	   IF @SqlJoin2 <> ''
		   SET @SqlJoin2 += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
   END
IF @BarCode <> ''      --商品条码
   BEGIN  
	   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = dtl.GoodsID '
	   IF @BarCodeMatch = 0
		   SET @SqlParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlParam += N' AND pri.BarCode = @BarCode '
	   SET @SqlParam += ' ) '
   END    
/*end*/	
SET @Sql='SET NOCOUNT ON; '
IF(@SqlJoin2 <> '')
BEGIN
	SET @Sql += '
SELECT ISNULL(SUM(a.ComTotal),0)[FHTotal] FROM (
	SELECT DISTINCT o.* FROM ( '
	SET @Sql += '
		SELECT InWhsID,OutWhsID,dtl.ComTotal FROM PD_AllotReqDetail'+@HisStr+' dtl ' + @SqlJoin + @SqlParam + '
		UNION ALL 
		SELECT InWhsID,OutWhsID,dtl.ComTotal FROM PD_AllotReqDetail'+@HisStr+' dtl ' +  @SqlJoin2 + @SqlParam
	SET @Sql += '
	) AS o 
) AS a '
END
ELSE
BEGIN
	SET @SqlHead='
	SELECT ISNULL(SUM(dtl.ComTotal),0)[FHTotal] 
	FROM PD_AllotReqDetail'+@HisStr+' dtl '
	SET @Sql += @SqlHead + @SqlJoin + @SqlParam
END
--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillNo BIGINT,@GoodsID VARCHAR(1000),@StopTag INT,@OperatorID INT, @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)',@BillNo,@GoodsID,@StopTag,@OperatorID, @Model, @AbbName, @Brand, @Spec, @BarCode

GO






/****** Object:  StoredProcedure [UP_PD_QuerySAMLSum]    Script Date: 12/08/2014 10:25:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySAMLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySAMLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySAMLSum]    Script Date: 12/08/2014 10:25:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-08
	描述：调拨申请管理Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySAMLSum]
(
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@DlvStartDate VARCHAR(50)='',	--交货日期查询开始时间
	@DlvEndDate VARCHAR(50)='',		--交货日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@InWhsID VARCHAR(1000)='',		--要货仓库
	@OutWhsID VARCHAR(1000)='',		--发货仓库
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@StopTag INT=9,					--中止状态
	@Stt VARCHAR(50)='',			--订单状态
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql1 NVARCHAR(MAX)='',@Sql2 NVARCHAR(MAX)='',@SqlJoin NVARCHAR(MAX)='',@SqlJoin2 NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)=''
		,@Sql1_His NVARCHAR(MAX)='',@Sql2_His NVARCHAR(MAX)='',@KtypeLimit INT=0 

SET @Sql1='
	SELECT b.BillNo
	,CASE WHEN b.StopTag=1 THEN 2 
		WHEN NOT EXISTS(SELECT 1 FROM PD_AllotReqDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty<BSQty) THEN 2 
		WHEN EXISTS(SELECT 1 FROM PD_AllotReqDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty>0) THEN 1 
		ELSE 0 END AS Stt 
	FROM PD_AllotReqBill b '
SET @Sql1_His='
	UNION ALL 
	SELECT b.BillNo,2[Stt] 
	FROM PD_AllotReqBill_His b '
SET @Sql2='
	SELECT b.BillNo,p.ComTotal[FHTotal] 
	FROM PD_AllotReqBill b 
	INNER JOIN PD_AllotReqDetail p ON p.BillNo=b.BillNo '
SET @Sql2_His='
	UNION ALL 
	SELECT b.BillNo,p.ComTotal[FHTotal] 
	FROM PD_AllotReqBill_His b 
	INNER JOIN PD_AllotReqDetail_His p ON p.BillNo=b.BillNo '

IF @DeptID <> ''
	SET @SqlJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @InWhsID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@InWhsID, '','') _Whs0 ON _Whs0.typeid = b.InWhsID '
IF @OutWhsID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@OutWhsID, '','') _Whs1 ON _Whs1.typeid = b.OutWhsID '
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
BEGIN
	SET @SqlJoin2 = @SqlJoin + '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs2 ON rWhs2.WhsID=b.OutWhsID '
	SET @SqlJoin +='
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs1 ON rWhs1.WhsID=b.InWhsID '
END
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin2 = @SqlJoin + '
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs2 ON rWhs2.WhsID=b.OutWhsID '
		SET @SqlJoin += '
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs1 ON rWhs1.WhsID=b.InWhsID '
	END
END
*/
   
SET @SqlParam = '
	WHERE 1=1 '
IF @BillCode <> ''
	SET @SqlParam +='
	AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
	AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @DlvStartDate <> ''
	SET @SqlParam +='
	AND b.DlvDate BETWEEN @DlvStartDate AND @DlvEndDate '
IF @Description <> ''
	SET @SqlParam +='
	AND b.Description Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='
	AND b.Summary Like ''%''+@Summary+''%'' '
IF @StopTag <> 9
	SET @SqlParam +='
	AND b.StopTag=@StopTag '

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
IF @BarCode <> ''      --商品条码
   BEGIN 
	   IF @BarCodeMatch = 0
		   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
	   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID '
   END    
/*end*/

IF @GoodsID <> '' OR @ClauseParam <> ''
	BEGIN
		IF @GoodsID <> ''
			SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
		SET @SqlParam_His = @SqlParam + '
			AND EXISTS (SELECT 1 FROM PD_AllotReqDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
		SET @SqlParam += '
			AND EXISTS (SELECT 1 FROM PD_AllotReqDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
	END
ELSE
	SET @SqlParam_His = @SqlParam

IF @IsHistory = 0 
BEGIN
	IF @Stt <> '' AND @Stt <> '0,1,2'
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += ';WITH SttData AS ( 
	SELECT DISTINCT o.* FROM ('+@Sql1 + @SqlJoin + @SqlParam + '
	UNION ALL ' +@Sql1 + @SqlJoin2 + @SqlParam + '
	) AS o 
) '
		END
		ELSE
		BEGIN
			SET @Sql += ';WITH SttData AS ( '+@Sql1 + @SqlJoin + @SqlParam + '
) '
		END
		SET @Sql += '
,dData AS ('+ @Sql2 + '
	INNER JOIN SttData sd ON sd.BillNo=b.BillNo 
	INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt 
) '
	END
	ELSE
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += ';WITH dData AS ( 
	SELECT DISTINCT o.* FROM ('+@Sql2 + @SqlJoin + @SqlParam + '
	UNION ALL ' +@Sql2 + @SqlJoin2 + @SqlParam + '
	) AS o 
) '
		END
		ELSE
		BEGIN
			SET @Sql += ';WITH dData AS ( '+@Sql2 + @SqlJoin + @SqlParam + '
) '
		END
	END
END
ELSE
BEGIN
	IF @Stt <> '' AND @Stt <> '0,1,2'
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += ';WITH SttData AS ( 
	SELECT DISTINCT o.* FROM (' + @Sql1 + @SqlJoin + @SqlParam + @Sql1_His + @SqlJoin + @SqlParam_His + '
	UNION ALL ' + @Sql1 + @SqlJoin2 + @SqlParam + @Sql1_His + @SqlJoin2 + @SqlParam_His + '
	) AS o 
) '
		END
		ELSE
		BEGIN
			SET @Sql += ';WITH SttData AS ( ' + @Sql1 + @SqlJoin + @SqlParam + @Sql1_His + @SqlJoin + @SqlParam_His + '
) '
		END
		SET @Sql += '
,dData AS ('+ @Sql2 + '
	INNER JOIN SttData sd ON sd.BillNo=b.BillNo 
	INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt '+ @Sql2_His + '
	INNER JOIN SttData sd ON sd.BillNo=b.BillNo INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt 
) '
	END
	ELSE
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += ';WITH dData AS ( 
	SELECT DISTINCT o.* FROM (' + @Sql2 + @SqlJoin + @SqlParam + @Sql2_His + @SqlJoin + @SqlParam_His + '
	UNION ALL ' + @Sql2 + @SqlJoin2 + @SqlParam + @Sql2_His + @SqlJoin2 + @SqlParam_His + '
	) AS o 
) '
		END
		ELSE
		BEGIN
			SET @Sql += ';WITH dData AS ( ' + @Sql2 + @SqlJoin + @SqlParam + @Sql2_His + @SqlJoin + @SqlParam_His + '
) '
		END
	END
END
	
SET @Sql += '
,Data AS (
	SELECT BillNo,SUM(FHTotal)[FHTotal] FROM dData 
	GROUP BY BillNo 
) '

SET @Sql += '
SELECT ISNULL(SUM(FHTotal),0)[FHTotal] FROM Data '
IF @KtypeLimit = 0 SET @Sql = N' SELECT 0[Total],0[DHTotal] '
--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@DlvStartDate VARCHAR(50),@DlvEndDate VARCHAR(50),@BillCode VARCHAR(50),@InWhsID VARCHAR(1000),@OutWhsID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@Stt VARCHAR(50),@StopTag INT,@OperatorID INT, @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)',@BillStartDate,@BillEndDate,@DlvStartDate,@DlvEndDate,@BillCode,@InWhsID,@OutWhsID,@DeptID,@ElyID,@GoodsID,@Description,@Summary,@Stt,@StopTag,@OperatorID, @Model, @AbbName, @Brand, @Spec, @BarCode

END

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QuerySellOrdBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QuerySellOrdBill]
GO
/****** Object:  StoredProcedure [UP_PD_QuerySellOrdBill]    Script Date: 06/16/2014 11:33:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/6/16
-- Description:	 查询销售订单
-- Update:增加IsDraft字段检索（确认生效状态）
-- Update:增加AuditStatus字段检索（审核状态）
-- =============================================
CREATE PROCEDURE [UP_PD_QuerySellOrdBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SqlMain NVARCHAR(4000), @SqlDetail NVARCHAR(4000), @ExtCol NVARCHAR(40) = ', AuditStatus',
	        @MainTable NVARCHAR(40) = 'PD_SellOrdBill', @DetailTable NVARCHAR(40) = 'PD_SellOrdDetail'
	IF NOT EXISTS (SELECT 1 FROM PD_SellOrdBill WHERE BillNo = @BillNo)
		BEGIN
			SET @MainTable += '_His'
			SET @DetailTable += '_His'
			SET @ExtCol = ''
		END
	SET @SqlMain = 'SELECT ord.BillNo, ord.BillCode, ord.BillDate, ord.DlvDate, ord.BTypeID, ord.DeptID, ord.ElyID, ord.WhsID, ord.BillQty, 
						   ord.BTDTotal, ord.Total, creator.ElyName AS CreatorName, ord.CreateTime, ord.Summary, ord.Description, ord.Stt,ord.IsDraft,
						   ord.StopTag, ord.Creator AS CreatorID, whs.WhsName, dept.DeptName, ely.ElyName, btype.BTypeName,ord.AuditStatus ' + @ExtCol +
						 ' FROM ' + @MainTable + ' ord
						   LEFT JOIN BD_Whs whs ON ord.WhsID = whs.WhsID
						   LEFT JOIN BD_Dept dept ON ord.DeptID = dept.DeptID
						   LEFT JOIN BD_Employee ely ON ord.ElyID = ely.ElyID
						   LEFT JOIN BD_Employee creator ON ord.Creator = creator.ElyID
						   LEFT JOIN BD_Btype btype ON ord.BTypeID = btype.BTypeID
					 WHERE ord.BillNo = @BillNo'  --查询主表
						
	EXEC sp_executesql @SqlMain, N'@BillNo INT', @BillNo
     
     SET @SqlDetail = 'SELECT detail.DID, detail.BillNo, detail.BarCode, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.PriceID,
							detail.WhsID, detail.WhsPtID, detail.UnitID, detail.Convfactor, detail.Price, detail.DiscPrice, 
							detail.TaxPrice, detail.Qty, detail.BSQty, detail.Total, detail.DiscTotal, detail.TaxTotal,
							detail.Discount, detail.TaxRate, detail.Tax, detail.ComQty, detail.Stt, CAST(detail.Gift AS BIT) AS Gift,
							detail.StopTag, detail.Remark, goods.GoodsNo, goods.GoodsName, goods.Spec, goods.Model, price.Unit, 
							ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name, 
							(SELECT COUNT(1) FROM PD_SellDetail d 
											   INNER JOIN PD_SellBill b ON d.BillNo = b.BillNo
											   WHERE d.OrdDID = detail.DID AND b.Red = 0) AS SelectQty,
							(SELECT COUNT(1) FROM PD_SellDetail_His d 
											   INNER JOIN PD_SellBill_His b ON d.BillNo = b.BillNo
											   WHERE d.OrdDID = detail.DID AND b.Red = 0) AS HisSelectQty,
							price1.UnitID AS UnitID1, price1.Unit AS Unit1, price1.BarCode AS BarCode1,
							case when price1.Convfactor IS null then 1 else price1.Convfactor end  AS Convfactor1,
							price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2, 
							case when price2.Convfactor IS null then 1 else price2.Convfactor end  AS Convfactor2,
							price3.UnitID AS UnitID3, price3.Unit AS Unit3, price3.BarCode AS BarCode3, 
							case when price3.Convfactor IS null then 1 else price3.Convfactor end  AS Convfactor3  ,
							detail.goodsno AS BtypeGoodsNo,goods.Brand,goods.KG		    
							FROM ' + @DetailTable + ' detail
							LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
							LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID
							LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
							LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
							LEFT JOIN BD_Goods_Price price1 ON price1.GoodsID = detail.GoodsID
							LEFT JOIN BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID And price2.UnitID = 2
							LEFT JOIN BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID And price3.UnitID = 3
					  WHERE detail.BillNo = @BillNo AND price.UnitID = detail.UnitID
							AND price1.UnitID = 1
					   ORDER BY detail.DID'  --查询明细
						
	EXEC sp_executesql @SqlDetail, N'@BillNo INT', @BillNo
END
GO




/****** Object:  StoredProcedure [UP_PD_QuerySIDSum]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySIDSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySIDSum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySIDSum]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：销售单据开票情况查询(明细)Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySIDSum]
(
	@BillNo BIGINT=0,				--单据编号
	@BillTypeID INT=101				--单据类型
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@Sql0 NVARCHAR(MAX)='',@Sql1 NVARCHAR(MAX)='',@Sql2 NVARCHAR(MAX)='',@TableName VARCHAR(20)='',@HisStr VARCHAR(20)='_His'
IF EXISTS (SELECT 1 FROM MF_SellInvoiceDetail dtl WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql1='
		SELECT dtl.SellBillNo,dtl.SellDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_SellInvoiceDetail dtl
		WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY SellBillNo,SellDID,BillType '
IF EXISTS (SELECT 1 FROM MF_SellInvoiceDetail_His dtl WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0))
SET @Sql2='
		SELECT dtl.SellBillNo,dtl.SellDID,dtl.BillType,SUM(dtl.InvoiceQty)[InvoiceQty],SUM(dtl.InvoiceTotal)[InvoiceTotal] 
		FROM MF_SellInvoiceDetail_His dtl
		WHERE dtl.SellBillNo=@BillNo AND EXISTS(SELECT 1 FROM MF_SellInvoiceBill_His b WHERE b.BillNo=dtl.BillNo AND b.IsDraft=0)
		GROUP BY SellBillNo,SellDID,BillType '
IF @Sql1<>'' AND @Sql2<>''
	SET @Sql0 = @Sql1 +'
		UNION ALL ' + @Sql2
ELSE IF @Sql1<>'' AND @Sql2='' SET @Sql0 = @Sql1
ELSE IF @Sql1='' AND @Sql2<>'' SET @Sql0 = @Sql2
IF @BillTypeID = 201
BEGIN
	SET @TableName = 'PD_SellDetail'
	IF EXISTS (SELECT 1 FROM PD_SellDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='SET NOCOUNT ON; 
SELECT SUM(ISNULL(pidtl.InvoiceTotal,0))[InvoiceTotal],SUM(ISNULL(dtl.TaxTotal,0))-SUM(ISNULL(pidtl.InvoiceTotal,0))[NoInvoiceTotal] 
FROM '+@TableName+@HisStr+' dtl 
LEFT JOIN ( '+@Sql0+'
) AS pidtl ON SellBillNo = dtl.BillNo AND pidtl.SellDID = dtl.DID AND BillType=@BillTypeID 
WHERE dtl.BillNo=@BillNo '
END
ELSE
BEGIN
	SET @TableName = 'PD_SellRetDetail'
	IF EXISTS (SELECT 1 FROM PD_SellRetDetail b WHERE b.BillNo=@BillNo) SET @HisStr=''
	SET @Sql='SET NOCOUNT ON; 
SELECT SUM(ISNULL(pidtl.InvoiceTotal,0))[InvoiceTotal],SUM(ISNULL(dtl.TaxTotal,0))*-1-SUM(ISNULL(pidtl.InvoiceTotal,0))[NoInvoiceTotal] 
FROM '+@TableName+@HisStr+' dtl 
LEFT JOIN ( '+@Sql0+'
) AS pidtl ON SellBillNo = dtl.BillNo AND pidtl.SellDID = dtl.DID AND BillType=@BillTypeID 
WHERE dtl.BillNo=@BillNo '
END

--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillNo BIGINT,@BillTypeID INT',@BillNo,@BillTypeID

GO






/****** Object:  StoredProcedure [UP_PD_QuerySISum]    Script Date: 10/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySISum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySISum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySISum]    Script Date: 10/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-10
	描述：销售单据开票情况查询Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySISum]
(
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@BTypeID VARCHAR(1000)='',		--往来单位
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@BillCode VARCHAR(50)='',		--单据编号
	@BillType INT=9,				--单据类型
	@InvoiceState INT=9,			--开票状态 9=全部,2=已开票,0=未开票,1=部分开票
	@GoodsNoMatch INT = 0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',		--商品编号
	@GoodsNameMatch INT = 0,		--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',	--商品名称
	@SummaryMatch INT = 0,			--摘要配置模式:0=包含,1=等于
	@Summary VARCHAR(100) = '',		--摘要
	@DescriptionMatch INT = 0,		--说明配置模式:0=包含,1=等于
	@Description VARCHAR(100) = '',	--说明
	@PriceStart decimal(20,8),      --单价范围开始
	@PriceEnd  decimal(20,8),       --单价范围结束
	@TotalStart decimal(20,8),      --金额范围开始
	@TotalEnd  decimal(20,8),       --金额范围结束
	@IsShowRed INT=0,				--是否包含红冲数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql_SB VARCHAR(460)='',@Sql_SB_His VARCHAR(460)='',@Sql_SRB VARCHAR(460)='',@Sql_SRB_His VARCHAR(460)=''
		,@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@BtypeLimit INT=0 ,@SqlDetailParam NVARCHAR(MAX)='',@SqlDetailJoin NVARCHAR(MAX)=''
		,@SqlDetailSB NVARCHAR(MAX)='',@SqlDetailSRB NVARCHAR(MAX)='',@SqlDetailSB_His NVARCHAR(MAX)='',@SqlDetailSRB_His NVARCHAR(MAX)=''

IF @BTypeID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BTypeID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
		INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
IF @DeptID <> ''
	SET @SqlJoin +='
		INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '

SET @SqlParam = '
		WHERE b.IsDraft=0 '
IF @IsShowRed = 0
	SET @SqlParam += '
		AND b.Red=0 '
IF @BillCode <> ''
	SET @SqlParam +='
		AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
		AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
-- 摘要
IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 0
		SET @SqlParam += 'AND b.Summary Like ''%''+@Summary+''%'' '  
	IF @SummaryMatch = 1
		SET @SqlParam += 'AND b.Summary = @Summary '  
END
-- 说明
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 0
		SET @SqlParam += 'AND b.Description Like ''%''+@Description+''%'' '  
	IF @DescriptionMatch = 1
		SET @SqlParam += 'AND b.Description = @Description '  
END
IF @GoodsName <> '' OR @GoodsNo <> ''
BEGIN
	SET @SqlDetailJoin += ' INNER JOIN BD_Goods _goods ON _goods.GoodsID = dtl.GoodsID '
END
-- 商品名称
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsNo Like ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsNo = @GoodsNo '  
END
-- 商品名称
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 0
		SET @SqlDetailParam += ' AND _goods.GoodsName Like ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch = 1
		SET @SqlDetailParam += ' AND _goods.GoodsName = @GoodsName '  
END
-- 商品单价从--到
IF @PriceEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Price BETWEEN @PriceStart AND @PriceEnd '
END
-- 商品金额从--到
IF @TotalEnd <> 0
BEGIN
	SET @SqlDetailParam += ' AND dtl.Total BETWEEN @TotalStart AND @TotalEnd '
END
IF @GoodsName <> '' OR @GoodsNo <> '' OR @PriceEnd <> 0 OR @TotalEnd <> 0
BEGIN
	SET @SqlDetailSB += '  AND EXISTS (SELECT 1 FROM PD_SellDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailSRB += '  AND EXISTS (SELECT 1 FROM PD_SellRetDetail dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailSB_His += '  AND EXISTS (SELECT 1 FROM PD_SellDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
	SET @SqlDetailSRB_His += '  AND EXISTS (SELECT 1 FROM PD_SellRetDetail_His dtl '+ @SqlDetailJoin +' WHERE dtl.BillNo=b.BillNo '+ @SqlDetailParam +' )'
END
IF @InvoiceState <> 9
BEGIN
	IF @InvoiceState = 2
		SET @SqlParam +='
	AND ABS(b.InvoiceTotal)>=b.Total '
	IF @InvoiceState = 0
		SET @SqlParam +='
	AND b.InvoiceTotal=0 '
	IF @InvoiceState = 1
		SET @SqlParam +='
	AND b.InvoiceTotal<>0 AND ABS(b.InvoiceTotal)<b.Total '
END
SET @SqlParam += ' AND b.IsInvoice = 1 ' --只查询是否开票为是的单据
SET @Sql_SB += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_SellBill b '
SET @Sql_SRB += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_SellRetBill b '
SET @Sql_SB_His += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total*-1 ELSE b.Total END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total-b.InvoiceTotal)*-1 ELSE b.Total-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_SellBill_His b '
SET @Sql_SRB_His += '
	SELECT b.BillNo,CASE WHEN b.Red=2 THEN b.Total ELSE b.Total*-1 END[Total]
		,CASE WHEN b.Red=2 THEN b.InvoiceTotal*-1 ELSE b.InvoiceTotal END[InvoiceTotal]
		,CASE WHEN b.Red=2 THEN (b.Total*-1-b.InvoiceTotal)*-1 ELSE b.Total*-1-b.InvoiceTotal END[NoInvoiceTotal] 
	FROM PD_SellRetBill_His b '
IF @IsHistory = 1
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_SB + @SqlJoin + @SqlParam + @SqlDetailSB + '
	UNION ALL ' + @Sql_SB_His + @SqlJoin + @SqlParam +  @SqlDetailSB_His 
	ELSE IF @BillType = 2
		SET @Sql = @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB + '
	UNION ALL ' + @Sql_SRB_His + @SqlJoin + @SqlParam + @SqlDetailSRB_His
	ELSE
		SET @Sql = @Sql_SB + @SqlJoin + @SqlParam + @SqlDetailSB + '
	UNION ALL ' + @Sql_SB_His + @SqlJoin + @SqlParam + @SqlDetailSB_His + '
	UNION ALL ' + @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB + '
	UNION ALL ' + @Sql_SRB_His + @SqlJoin + @SqlParam + @SqlDetailSRB_His
END
ELSE
BEGIN
	IF @BillType = 1
		SET @Sql = @Sql_SB + @SqlJoin + @SqlParam + @SqlDetailSB
	ELSE IF @BillType = 2
		SET @Sql = @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB
	ELSE
		SET @Sql = @Sql_SB  + @SqlJoin + @SqlParam + @SqlDetailSB + '
	UNION ALL ' + @Sql_SRB + @SqlJoin + @SqlParam + @SqlDetailSRB
END

SET @Sql = 'SET NOCOUNT ON; 
;WITH BillData AS( ' + @Sql + '
)'
SET @Sql += 'SELECT ISNULL(SUM(Total),0)[Total],ISNULL(SUM(InvoiceTotal),0)[InvoiceTotal],ISNULL(SUM(NoInvoiceTotal),0)[NoInvoiceTotal] FROM BillData '

IF @BtypeLimit = 0 
	SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
	
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END

EXEC SP_EXECUTESQL @Sql,N'@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@BillCode VARCHAR(50),@BillType INT=9,@OperatorID INT,
						  @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),@SummaryMatch INT, @Summary VARCHAR(100), @DescriptionMatch INT, @Description VARCHAR(100),
						  @PriceStart DECIMAL(20,8),@PriceEnd DECIMAL(20,8), @TotalStart DECIMAL(20,8), @TotalEnd DECIMAL(20,8)',
						  @BillStartDate,@BillEndDate,@BTypeID,@DeptID,@ElyID,@BillCode,@BillType,@OperatorID,
						  @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName, @SummaryMatch, @Summary, @DescriptionMatch, @Description,
						  @PriceStart, @PriceEnd, @TotalStart, @TotalEnd

END

GO






/****** Object:  StoredProcedure [UP_PD_QuerySODTLSum]    Script Date: 07/03/2014 16:44:41 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySODTLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySODTLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySODTLSum]    Script Date: 07/03/2014 16:44:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-03
	描述：销售订单管理(明细)Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySODTLSum]
(
	@BillNo BIGINT=0,
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@StopTag INT=9,					--中止状态
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@SqlParam NVARCHAR(MAX)
		,@HisStr VARCHAR(20)='_His',@KtypeLimit INT=0 
IF EXISTS (SELECT 1 FROM PD_SellOrdBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''
SET @Sql='SELECT ISNULL(SUM(dtl.TaxTotal),0)[Total],ISNULL(SUM(dtl.ComTotal),0)[DHTotal] 
	FROM PD_SellOrdDetail'+@HisStr+' dtl '
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @Sql += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=dtl.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @Sql +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=dtl.WhsID '
	END
END
*/
IF @GoodsID <> ''
	SET @Sql +='INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID ' 
	
IF @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
BEGIN
	SET @Sql += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
END	

--IF @BarCode <> ''
--BEGIN 
--	SET @Sql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID  '
--END

SET @Sql +='WHERE dtl.BillNo=@BillNo '
IF @StopTag <> 9
	SET @Sql +='AND dtl.StopTag=@StopTag '
--商品型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @Sql += N' AND goods.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @Sql += N' AND goods.Model = @Model ' 
END   
--商品简名    
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @Sql += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @Sql += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
END       
--商品品牌
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @Sql += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @Sql += N' AND goods.Brand = @Brand ' 
END
--商品规格    
IF @Spec <> ''        
BEGIN 
   IF @SpecMatch = 0
	   SET @Sql += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @Sql += N' AND goods.Spec = @Spec '  
END
--商品条码
IF @BarCode <> ''      
BEGIN 
   SET @Sql += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = dtl.GoodsID '
   IF @BarCodeMatch = 0
	   SET @Sql += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @Sql += N' AND pri.BarCode = @BarCode ' 
   SET @Sql += ' ) '
END 	
	
IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillNo BIGINT,@GoodsID VARCHAR(1000),@StopTag INT,@OperatorID INT, @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(50), @BarCodeMatch INT',@BillNo,@GoodsID,@StopTag,@OperatorID, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch

GO






/****** Object:  StoredProcedure [UP_PD_QuerySOLSum]    Script Date: 07/03/2014 10:25:15 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QuerySOLSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QuerySOLSum]
GO

/****** Object:  StoredProcedure [UP_PD_QuerySOLSum]    Script Date: 07/03/2014 10:25:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-03
	描述：销售订单管理Sum
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QuerySOLSum]
(
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@DlvStartDate VARCHAR(50)='',	--交货日期查询开始时间
	@DlvEndDate VARCHAR(50)='',		--交货日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@BTypeID VARCHAR(1000) = '',	--往来单位
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@WhsID VARCHAR(1000) = '',		--仓库
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@Stt VARCHAR(50)='',			--订单状态
	@IsDraft INT=9,                 --生效状态
	@StopTag INT=9,					--中止状态
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@BtypeAddr VARCHAR(max)='',		--往来单位地址
	@BtypePhone VARCHAR(max)=''		--往来单位编号
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql1 NVARCHAR(MAX)='',@Sql2 NVARCHAR(MAX)='',@SqlJoin NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)=''
		,@Sql1_His NVARCHAR(MAX)='',@Sql2_His NVARCHAR(MAX)='',@BtypeLimit INT=0,@KtypeLimit INT=0 

SET @Sql1='SELECT b.BillNo,CASE WHEN b.StopTag=1 THEN 2 
			WHEN NOT EXISTS(SELECT 1 FROM PD_SellOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty<BSQty) THEN 2 
			WHEN EXISTS(SELECT 1 FROM PD_SellOrdDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty>0) THEN 1
			ELSE 0 END AS Stt 
			FROM PD_SellOrdBill b '
			
IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql1 = @Sql1 + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '
	
SET @Sql1_His='UNION ALL 
			SELECT b.BillNo,2[Stt] 
			FROM PD_SellOrdBill_His b '

IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql1_His = @Sql1_His + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '			
			
SET @Sql2='SELECT b.BillNo,b.Total,p.ComTotal[DHTotal] 
			FROM PD_SellOrdBill b 
			INNER JOIN PD_SellOrdDetail p ON p.BillNo=b.BillNo '
			
IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql2 = @Sql2 + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '			

SET @Sql2_His='UNION ALL 
			SELECT b.BillNo,b.Total,p.ComTotal[DHTotal] 
			FROM PD_SellOrdBill_His b 
			INNER JOIN PD_SellOrdDetail_His p ON p.BillNo=b.BillNo '
IF @BtypePhone<>'' OR @BtypeAddr <> ''
	SET @Sql2_His = @Sql2_His + ' INNER JOIN BD_Btype bd ON bd.BTypeID=B.BTypeID  AND Bd.Tel LIKE ''%' + @BtypePhone+'%'' AND Bd.Adress LIKE ''%' + @BtypeAddr+'%'' '			

IF @BTypeID <> ''
   SET @SqlJoin +='INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = b.BtypeID '
IF @DeptID <> ''
   SET @SqlJoin +='INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
   SET @SqlJoin +='INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @WhsID <> ''
   SET @SqlJoin +='INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = b.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SqlJoin += '
		INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=b.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SqlJoin += '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=b.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=b.BTypeID '
	END
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin +='
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=b.WhsID '
	END
END
*/
SET @SqlParam = 'WHERE 1=1 '
IF @BillCode <> ''
	SET @SqlParam +='AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @DlvStartDate <> ''
	SET @SqlParam +='AND b.DlvDate BETWEEN @DlvStartDate AND @DlvEndDate '
IF @Description <> ''
	SET @SqlParam +='AND b.Description Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='AND b.Summary Like ''%''+@Summary+''%'' '
-- 生效状态
IF @IsDraft <> 9
BEGIN
	SET @SqlParam +='AND b.IsDraft=@IsDraft '
	--SET @SqlSumParam ='WHERE p.IsDraft=@IsDraft '
END		
IF @StopTag <> 9
	SET @SqlParam +='AND b.StopTag=@StopTag '
--IF @GoodsID <> ''
--BEGIN
--	SET @SqlParam_His = @SqlParam + 'AND EXISTS (SELECT 1 FROM PD_SellOrdDetail_His dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--	SET @SqlParam +='AND EXISTS (SELECT 1 FROM PD_SellOrdDetail dtl INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID WHERE dtl.BillNo=b.BillNo) '
--END

DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
--商品型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @ClauseParam += N' AND goods.Model = @Model ' 
END     
--商品简名  
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @ClauseParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
   END    
--商品品牌   
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
END    
IF @Spec <> ''       --商品规格 
BEGIN 
   IF @SpecMatch = 0
	   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @ClauseParam += N' AND goods.Spec = @Spec '  
END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
IF @BarCode <> ''      --商品条码
BEGIN 
   IF @BarCodeMatch = 0
	   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID    '
END    

IF @GoodsID <> '' OR @ClauseParam <> ''
BEGIN
	IF @GoodsID <> ''
		SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
	SET @SqlParam_His = @SqlParam + '
		AND EXISTS (SELECT 1 FROM PD_AllotReqDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
	SET @SqlParam += '
		AND EXISTS (SELECT 1 FROM PD_AllotReqDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
END
ELSE
	SET @SqlParam_His = @SqlParam

IF @IsHistory = 0 
	IF @Stt <> '' AND @Stt <> '0,1,2'
		SET @Sql += ';WITH SttData AS ( '+@Sql1 + @SqlJoin + @SqlParam + ') ,dData AS ('+ @Sql2 + 'INNER JOIN SttData sd ON sd.BillNo=b.BillNo INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt ) '
	ELSE
		SET @Sql += ';WITH dData AS ( '+@Sql2 + @SqlJoin + @SqlParam + ') '
ELSE
	IF @Stt <> '' AND @Stt <> '0,1,2'
		SET @Sql += ';WITH SttData AS ( '+@Sql1 + @SqlJoin + @SqlParam + @Sql1_His + @SqlJoin + @SqlParam_His 
					+ ') ,dData AS ('+ @Sql2 + 'INNER JOIN SttData sd ON sd.BillNo=b.BillNo INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt '
									+ @Sql2_His + 'INNER JOIN SttData sd ON sd.BillNo=b.BillNo INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = sd.Stt ) '
	ELSE
		SET @Sql += ';WITH dData AS ( '+@Sql2 + @SqlJoin + @SqlParam + @Sql2_His + @SqlJoin + @SqlParam_His + ') '
		
SET @Sql += ',Data AS (
	SELECT BillNo,SUM(Total)/COUNT(BillNo)[Total],SUM(DHTotal)[DHTotal] FROM dData 
	GROUP BY BillNo ) '

SET @Sql += 'SELECT ISNULL(SUM(Total),0)[Total],ISNULL(SUM(DHTotal),0)[DHTotal] FROM Data '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT 0[Total],0[DHTotal] '
--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@DlvStartDate VARCHAR(50),@DlvEndDate VARCHAR(50),@BillCode VARCHAR(50),@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@Stt VARCHAR(50),@IsDraft INT,@StopTag INT,@OperatorID INT, @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',@BillStartDate,@BillEndDate,@DlvStartDate,@DlvEndDate,@BillCode,@BTypeID,@DeptID,@ElyID,@WhsID,@GoodsID,@Description,@Summary,@Stt,@IsDraft,@StopTag,@OperatorID, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch

END

GO






/****** Object:  StoredProcedure [UP_PD_QueryStockAllotCheckDetailList]    Script Date: 05/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryStockAllotCheckDetailList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryStockAllotCheckDetailList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryStockAllotCheckDetailList]    Script Date: 05/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-06
	描述：调拨验收(明细)
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryStockAllotCheckDetailList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillNo BIGINT=0				--单据编号
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@HisStr VARCHAR(20)='_His'
		,@Sqla NVARCHAR(MAX),@Sqlb NVARCHAR(MAX),@Sqlc NVARCHAR(MAX),@Sqld NVARCHAR(MAX),@Sqle NVARCHAR(MAX)
IF EXISTS (SELECT 1 FROM PD_AllotBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''
SET @Sql='
;WITH PagingData AS 
( 
	SELECT dtl.DID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,dtl.UnitID,dtl.AllotPrice[Price],dtl.Qty[FHQty],CASE WHEN b.InspectTag=1 THEN dtl.Qty ELSE 0 END[InspectQty],dtl.AllotTotal[FHTotal],dtl.Remark 
	FROM PD_AllotDetail'+@HisStr+' dtl 
	INNER JOIN PD_AllotBill'+@HisStr+' b ON b.BillNo = dtl.BillNo 
	WHERE dtl.BillNo=@BillNo 
) '

/***********定义要关联的基础资料sql***********/
SET @Sqla=N'SELECT GoodsID[G1ID],GoodsNo,GoodsName,Spec,Model,GoodsAbbName,Brand FROM BD_Goods'
SET @Sqlb=N'SELECT Ppt1ID[P1ID],Value[Ppt1Name] FROM BD_Goods_Ppt1'
SET @Sqlc=N'SELECT Ppt2ID[P2ID],Value[Ppt2Name] FROM BD_Goods_Ppt2'
SET @Sqld=N'SELECT GoodsID[G2ID],UnitID[UID],Unit,BarCode FROM BD_Goods_Price'

DECLARE @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillNo','BIGINT',@BillNo)

/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsID=_DATA_a.G1ID',@Sqla)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_b','Data.Ppt1ID=_DATA_b.P1ID',@Sqlb)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_c','Data.Ppt2ID=_DATA_c.P2ID',@Sqlc)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_d','Data.GoodsID=_DATA_d.G2ID AND Data.UnitID=_DATA_d.UID',@Sqld)

EXEC UP_OT_Paging @Sql,@TVP,@PageNo,@PageSize,'DID','','',1,0

GO





/****** Object:  StoredProcedure [UP_PD_QueryStockAllotCheckList]    Script Date: 05/02/2015 18:20:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryStockAllotCheckList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryStockAllotCheckList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryStockAllotCheckList]    Script Date: 05/02/2015 18:20:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-05
	描述：调拨验收
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryStockAllotCheckList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@InWhsID VARCHAR(1000)='',		--要货仓库
	@OutWhsID VARCHAR(1000)='',		--发货仓库
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@GoodsID VARCHAR(1000)='',		--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@InspectTag INT=9,				--验收状态
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@Sql_One NVARCHAR(MAX)='',@Sql_Two NVARCHAR(MAX)='',@Sql_BN VARCHAR(200)='',@Sql_BN_His VARCHAR(200)=''
		,@SqlJoin NVARCHAR(MAX)='',@SqlJoin_BN VARCHAR(200)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)=''
		,@SqlJoin_KT_In VARCHAR(100)='',@SqlJoin_KT_Out VARCHAR(100)='',@KtypeLimit INT=2 
IF @DeptID <> ''
	SET @SqlJoin +='
		INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @InWhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@InWhsID, '','') _Whs0 ON _Whs0.typeid = b.InWhsID '
IF @OutWhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@OutWhsID, '','') _Whs1 ON _Whs1.typeid = b.OutWhsID '
IF @InWhsID = '' AND @OutWhsID = ''
BEGIN
	/*权限使用公用方法*/
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF( @KtypeLimit = 1 ) --部份权限
	BEGIN
		SET @SqlJoin_KT_Out = '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs2 ON rWhs2.WhsID=b.OutWhsID '
		SET @SqlJoin_KT_In = '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs1 ON rWhs1.WhsID=b.InWhsID '
	END
END

SET @SqlParam = '
		WHERE b.IsDraft=0 AND b.Red=0 '
IF @BillCode <> ''
	SET @SqlParam +='
		AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
		AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @Description <> ''
	SET @SqlParam +='
		AND b.[Description] Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='
		AND b.Summary Like ''%''+@Summary+''%'' '
SET @SqlParam_His = @SqlParam
IF @InspectTag <> 9
	SET @SqlParam +='
		AND b.InspectTag=@InspectTag '

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
IF @BarCode <> ''      --商品条码
   BEGIN 
	   IF @BarCodeMatch = 0
		   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
	   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID '
   END    
/*end*/

IF @GoodsID <> '' OR @ClauseParam <> ''
	BEGIN
		IF @GoodsID <> ''
			SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
		SET @SqlParam_His += '
			AND EXISTS (SELECT 1 FROM PD_AllotDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
		SET @SqlParam += '
			AND EXISTS (SELECT 1 FROM PD_AllotDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' )'
	END

SET @Sql_BN += '
		SELECT b.BillNo 
		FROM PD_AllotBill b '
SET @Sql_BN_His += '
		SELECT b.BillNo 
		FROM PD_AllotBill_His b '
SET @Sql_One = '
	SELECT 1[a] '
IF @InWhsID = '' AND @OutWhsID = ''
BEGIN
	IF @KtypeLimit = 1	--部份权限
	BEGIN
		SET @SqlJoin_BN = '
		INNER JOIN BillNoList bn ON bn.BillNo = b.BillNo '
		IF @IsHistory = 1 AND @InspectTag <> 0
		BEGIN
			SET @Sql_One = '
	SELECT DISTINCT o.* FROM ( ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_In + @SqlParam + '
		UNION ALL ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_Out + @SqlParam + '
		UNION ALL ' + @Sql_BN_His + @SqlJoin + @SqlJoin_KT_In + @SqlParam_His + '
		UNION ALL ' + @Sql_BN_His + @SqlJoin + @SqlJoin_KT_Out + @SqlParam_His + '
	) AS o'
		END
		ELSE
		BEGIN
			SET @Sql_One = '
	SELECT DISTINCT o.* FROM ( ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_In + @SqlParam + '
		UNION ALL ' + @Sql_BN + @SqlJoin + @SqlJoin_KT_Out + @SqlParam + '
	) AS o'
		END
	END
END
IF LEN(@SqlJoin_BN) > 0 
BEGIN
	SET @SqlJoin = ''
	SET @SqlParam = ''
	SET @SqlParam_His = ''
END 
SET @Sql_Two = '
		SELECT b.BillTypeID,b.BillNo,b.BillDate,b.BillCode,b.InWhsID,b.OutWhsID,b.ElyID,b.DeptID,b.BillQty[FHQty],b.InspectTag,b.Summary,b.[Description] 
		FROM PD_AllotBill b ' + @SqlJoin_BN + @SqlJoin + @SqlParam
IF @IsHistory = 1 AND @InspectTag <> 0 --AND LEN(@SqlJoin_BN) > 0
BEGIN
	SET @Sql_Two += '
		UNION ALL
		SELECT b.BillTypeID,b.BillNo,b.BillDate,b.BillCode,b.InWhsID,b.OutWhsID,b.ElyID,b.DeptID,b.BillQty[FHQty],b.InspectTag,b.Summary,b.[Description] 
		FROM PD_AllotBill_His b ' + @SqlJoin_BN + @SqlJoin + @SqlParam_His
END

SET @Sql = 'IF OBJECT_ID(''tempdb..#tempbo'',''U'') IS NOT NULL DROP TABLE #tempbo 
SET NOCOUNT ON; 
;WITH BillNoList AS( ' + @Sql_One + '
)
,BillData AS( ' + @Sql_Two + '
)'
SET @Sql += '
SELECT * INTO #tempbo 
FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillNo) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
WHERE B.ROWID>(@PageNo-1)*@PageSize AND B.ROWID<=@PageNo*@PageSize 
SELECT o.*,w1.WhsName[InWhsName],w2.WhsName[OutWhsName],e.ElyName,d.DeptName
	,CASE WHEN o.InspectTag=1 THEN o.FHQty ELSE 0 END[InspectQty]
	,CASE o.InspectTag WHEN 1 THEN ''已验收'' ELSE ''未验收'' END [InspectTagShow] 
FROM #tempbo o 
INNER JOIN BD_Whs w1 ON w1.WhsID=o.InWhsID 
INNER JOIN BD_Whs w2 ON w2.WhsID=o.OutWhsID 
INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
DROP TABLE #tempbo '

IF @KtypeLimit = 0 
	SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

EXEC SP_EXECUTESQL @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@BillCode VARCHAR(50),@InWhsID VARCHAR(1000),@OutWhsID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@InspectTag INT=9,@OperatorID INT, @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)',@PageNo,@PageSize,@BillStartDate,@BillEndDate,@BillCode,@InWhsID,@OutWhsID,@DeptID,@ElyID,@GoodsID,@Description,@Summary,@InspectTag,@OperatorID, @Model, @AbbName, @Brand, @Spec, @BarCode

END

GO








/****** Object:  StoredProcedure [UP_PD_QueryStockAllotMDetailList]    Script Date: 12/08/2014 15:11:36 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryStockAllotMDetailList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryStockAllotMDetailList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryStockAllotMDetailList]    Script Date: 12/08/2014 15:11:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-08
	描述：调拨申请管理(明细)
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryStockAllotMDetailList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillNo BIGINT=0,				--单据编号
	@GoodsID VARCHAR(1000) = '',	--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@StopTag INT=9,					--中止状态
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON

DECLARE @Sql NVARCHAR(MAX),@SqlHead VARCHAR(500),@SqlJoin NVARCHAR(MAX)='',@SqlJoin2 NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)=''
		,@Sqla NVARCHAR(MAX),@Sqlb NVARCHAR(MAX),@Sqlc NVARCHAR(MAX),@Sqld NVARCHAR(MAX),@Sqle NVARCHAR(MAX),@HisStr VARCHAR(20)='_His',@KtypeLimit INT=0 
IF EXISTS (SELECT 1 FROM PD_AllotReqBill b WHERE b.BillNo=@BillNo)
	SET @HisStr=''
SET @SqlHead='
	SELECT dtl.DID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,dtl.UnitID,dtl.Convfactor,dtl.BSQty,dtl.Qty,dtl.ComQty[FHQty],dtl.InspectQty/dtl.Convfactor[InspectQty],dtl.ComTotal[FHTotal]
	,dtl.StopTag,CASE dtl.StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow]
	,dtl.Remark 
	FROM PD_AllotReqDetail'+@HisStr+' dtl '
IF @GoodsID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID ' 
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1 --部份权限
BEGIN
	SET @SqlJoin2 = @SqlJoin + '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs2 ON rWhs2.WhsID=dtl.OutWhsID '
	SET @SqlJoin +='
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs1 ON rWhs1.WhsID=dtl.InWhsID '
END
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin2 = @SqlJoin + '
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs2 ON rWhs2.WhsID=dtl.OutWhsID '
		SET @SqlJoin += '
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs1 ON rWhs1.WhsID=dtl.InWhsID '
	END
END
*/
SET @SqlParam +='
	WHERE dtl.BillNo=@BillNo '
IF @StopTag <> 9
	SET @SqlParam +='AND dtl.StopTag=@StopTag '
	
/*新增商品查询条件 start 150901*/
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @SqlParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @SqlParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @SqlParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @SqlParam += N' AND goods.Spec = @Spec '  
   END
IF @Model <> '' OR @AbbName <> '' OR @Brand <> '' OR @Spec <> ''
   BEGIN
	   SET @SqlJoin += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
	   IF @SqlJoin2 <> ''
		   SET @SqlJoin2 += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
	   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = dtl.GoodsID '
	   IF @BarCodeMatch = 0
		   SET @SqlParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlParam += N' AND pri.BarCode = @BarCode ' 
	   SET @SqlParam += ' ) '
   END    
/*end*/	
	
SET @Sql='
;WITH PagingData AS 
( '
IF(@SqlJoin2 <> '')
BEGIN
	SET @Sql += '
	SELECT DISTINCT o.* FROM ( '
	SET @Sql += @SqlHead + @SqlJoin + @SqlParam + '
	UNION ALL ' + @SqlHead + @SqlJoin2 + @SqlParam
	SET @Sql += '
	) AS o '
END
ELSE
BEGIN
	SET @Sql += @SqlHead + @SqlJoin + @SqlParam
END
SET @Sql +='
) '

/***********定义要关联的基础资料sql***********/
SET @Sqla=N'SELECT GoodsID[G1ID],GoodsNo,GoodsName,Spec,Model,GoodsAbbName,Brand FROM BD_Goods'
SET @Sqlb=N'SELECT Ppt1ID[P1ID],Value[Ppt1Name] FROM BD_Goods_Ppt1'
SET @Sqlc=N'SELECT Ppt2ID[P2ID],Value[Ppt2Name] FROM BD_Goods_Ppt2'
SET @Sqld=N'SELECT GoodsID[G2ID],UnitID[UID],Unit,BarCode FROM BD_Goods_Price'

DECLARE @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BillNo','BIGINT',@BillNo)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@GoodsID','VARCHAR(1000)',@GoodsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@StopTag','INT',@StopTag)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@OperatorID','INT',@OperatorID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Model','VARCHAR(50)',@Model)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@AbbName','VARCHAR(50)',@AbbName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Brand','VARCHAR(50)',@Brand)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@Spec','VARCHAR(50)',@Spec)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@BarCode','VARCHAR(100)',@BarCode)

/***********将基础资料sql插入表值参数（注：[ParaName]前缀固定为_DATA_，[DataType]关联左表别名固定为Data）***********/
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_a','Data.GoodsID=_DATA_a.G1ID',@Sqla)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_b','Data.Ppt1ID=_DATA_b.P1ID',@Sqlb)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_c','Data.Ppt2ID=_DATA_c.P2ID',@Sqlc)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('_DATA_d','Data.GoodsID=_DATA_d.G2ID AND Data.UnitID=_DATA_d.UID',@Sqld)

IF @KtypeLimit = 0 EXEC SP_EXECUTESQL N' SELECT * FROM BD_Area WHERE 1 <> 1'
ELSE 
EXEC UP_OT_Paging @Sql,@TVP,@PageNo,@PageSize,'DID','','',1,0

GO





/****** Object:  StoredProcedure [UP_PD_QueryStockAllotMList]    Script Date: 12/08/2014 16:14:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryStockAllotMList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryStockAllotMList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryStockAllotMList]    Script Date: 12/08/2014 16:14:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2015-02-05
	描述：调拨申请管理
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryStockAllotMList]
(
	@PageNo INT=1,
	@PageSize INT=10,
	@BillStartDate VARCHAR(50)='',	--录单日期查询开始时间
	@BillEndDate VARCHAR(50)='',	--录单日期查询结束时间
	@DlvStartDate VARCHAR(50)='',	--交货日期查询开始时间
	@DlvEndDate VARCHAR(50)='',		--交货日期查询结束时间
	@BillCode VARCHAR(50)='',		--单据编号
	@InWhsID VARCHAR(1000)='',		--要货仓库
	@OutWhsID VARCHAR(1000)='',		--发货仓库
	@DeptID VARCHAR(1000)='',		--部门
	@ElyID VARCHAR(1000)='',		--经手人
	@GoodsID VARCHAR(1000)='',		--商品
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Description VARCHAR(50)='',	--说明
	@Summary VARCHAR(50)='',		--摘要
	@StopTag INT=9,					--中止状态
	@IsDraft INT=9,                 --生效状态  ------update sunzhiyuan
	@Stt VARCHAR(50)='',			--订单状态
	@IsHistory INT=0,				--是否包含历史数据
	@AuditStatus VARCHAR(100)='',   --审核状态
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX),@SqlHead VARCHAR(500),@SqlJoin NVARCHAR(MAX)='',@SqlJoin2 NVARCHAR(MAX)='',@SqlParam NVARCHAR(MAX)='',@SqlParam_His NVARCHAR(MAX)='',@StrStt VARCHAR(500),@InnerStt VARCHAR(100),@SqlSum VARCHAR(1000),@SqlSumParam VARCHAR(100)='',@SqlSumHead VARCHAR(120),@SqlSumOther VARCHAR(200),@SqlSumHead_His VARCHAR(120),@SqlSumOther_His VARCHAR(200),@KtypeLimit INT=0 
IF @DeptID <> ''
	SET @SqlJoin +='
		INNER JOIN (SELECT d2.DeptID[typeid] FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=b.DeptID '
IF @ElyID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = b.ElyID '
IF @InWhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@InWhsID, '','') _Whs0 ON _Whs0.typeid = b.InWhsID '
IF @OutWhsID <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@OutWhsID, '','') _Whs1 ON _Whs1.typeid = b.OutWhsID '
IF @AuditStatus <> ''
	SET @SqlJoin +='
		INNER JOIN dbo.UF_OT_Split_Int(@AuditStatus, '','') _AuditStatus ON _AuditStatus.typeid = b.AuditStatus '
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
BEGIN
	SET @SqlJoin2 = @SqlJoin + '
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs2 ON rWhs2.WhsID=b.OutWhsID '
	SET @SqlJoin +='
		INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs1 ON rWhs1.WhsID=b.InWhsID '
END
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SqlJoin2 = @SqlJoin + '
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs2 ON rWhs2.WhsID=b.OutWhsID '
		SET @SqlJoin += '
		INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs1 ON rWhs1.WhsID=b.InWhsID '
	END
END
*/
SET @SqlParam = '
		WHERE 1=1 '
IF @BillCode <> ''
	SET @SqlParam +='
		AND b.BillCode Like ''%''+@BillCode+''%'' '
IF @BillStartDate <> ''
	SET @SqlParam +='
		AND b.BillDate BETWEEN @BillStartDate AND @BillEndDate '
IF @DlvStartDate <> ''
	SET @SqlParam +='
		AND b.DlvDate BETWEEN @DlvStartDate AND @DlvEndDate '
IF @Description <> ''
	SET @SqlParam +='
		AND b.[Description] Like ''%''+@Description+''%'' '
IF @Summary <> ''
	SET @SqlParam +='
		AND b.Summary Like ''%''+@Summary+''%'' '
IF @StopTag <> 9
BEGIN
	SET @SqlParam +='
		AND b.StopTag=@StopTag '
	SET @SqlSumParam ='WHERE p.StopTag=@StopTag '
END
-- 生效状态
IF @IsDraft <> 9
BEGIN
	SET @SqlParam +='AND b.IsDraft=@IsDraft '
	--SET @SqlSumParam ='WHERE p.IsDraft=@IsDraft '
END

/*新增商品查询条件 start 150901*/
DECLARE @ClauseParam NVARCHAR(4000)='',@ClauseTable NVARCHAR(4000)=''
IF @Model <> ''      --商品型号
   BEGIN 
	   IF @ModelMatch = 0
		   SET @ClauseParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @ClauseParam += N' AND goods.Model = @Model ' 
   END       
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @ClauseParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @ClauseParam += N' AND goods.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @ClauseParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @ClauseParam += N' AND goods.Brand = @Brand ' 
   END    
IF @Spec <> ''       --商品规格 
   BEGIN 
	   IF @SpecMatch = 0
		   SET @ClauseParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @ClauseParam += N' AND goods.Spec = @Spec '  
   END
IF @ClauseParam <> ''
   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods goods ON goods.GoodsID = dtl.GoodsID '
IF @BarCode <> ''      --商品条码
   BEGIN 
	   IF @BarCodeMatch = 0
		   SET @ClauseParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @ClauseParam += N' AND pri.BarCode = @BarCode ' 
	   SET @ClauseTable += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID '
   END    
/*end*/

IF @GoodsID <> '' OR @ClauseParam <> ''
	BEGIN
		IF @GoodsID <> ''
			SET @ClauseTable += ' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID  '
		SET @SqlParam_His = @SqlParam + '
			AND EXISTS (SELECT 1 FROM PD_AllotReqDetail_His dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
		SET @SqlParam += '
			AND EXISTS (SELECT 1 FROM PD_AllotReqDetail dtl ' + @ClauseTable + ' WHERE dtl.BillNo=b.BillNo ' + @ClauseParam + ' ) '
	END
ELSE
	SET @SqlParam_His = @SqlParam
	
SET @Sql = 'IF OBJECT_ID(''tempdb..#tempbo'',''U'') IS NOT NULL DROP TABLE #tempbo 
SET NOCOUNT ON; 
;WITH BillData AS( '
SET @SqlHead = '
		SELECT b.BillNo,b.BillCode,b.BillDate,b.InWhsID,b.ElyID,b.DeptID,b.DlvDate,b.OutWhsID,b.Summary,b.[Description],b.BillQty,b.Creator,b.CreateTime,b.StopTag,b.IsDraft, b.AuditStatus '
SET @StrStt = '
					,CASE WHEN b.StopTag=1 THEN 2 
						WHEN NOT EXISTS(SELECT 1 FROM PD_AllotReqDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty<BSQty) THEN 2 
						WHEN EXISTS(SELECT 1 FROM PD_AllotReqDetail WHERE StopTag=0 AND BillNo=b.billno AND ComQty>0) THEN 1
						ELSE 0 END AS Stt '
SET @InnerStt = '
	INNER JOIN dbo.UF_OT_Split_Int(@Stt, '','') _Stt ON _Stt.typeid = o.Stt '
SET @SqlSumHead = 'SELECT o.BillNo,SUM(p.InspectQty/p.Convfactor)[InspectQty],SUM(p.ComQty/p.Convfactor)[FHQty],SUM(p.ComTotal)[FHTotal] '
SET @SqlSumOther = '
				FROM #tempbo o 
				INNER JOIN PD_AllotReqDetail p ON p.BillNo=o.BillNo '+@SqlSumParam+'GROUP BY o.BillNo '
SET @SqlSumHead_His = 'SELECT o.BillNo,SUM(p.InspectQty/p.Convfactor)[InspectQty],SUM(p.ComQty/p.Convfactor)[FHQty],SUM(p.ComTotal)[FHTotal] '
SET @SqlSumOther_His = '
				FROM #tempbo o 
				INNER JOIN PD_AllotReqDetail_His p ON p.BillNo=o.BillNo '+@SqlSumParam+'GROUP BY o.BillNo '
	
IF @Stt <> '' AND @Stt <> '0,1,2'
BEGIN
	IF @IsHistory = 0 
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += '
	SELECT DISTINCT o.* FROM ( '
			SET @Sql += @SqlHead + @StrStt + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + @StrStt + '
		FROM PD_AllotReqBill b ' + @SqlJoin2 + @SqlParam + '
	) AS o ' + @InnerStt + '
) '
			SET @SqlSum = @SqlSumHead + @SqlSumOther
		END
		ELSE
		BEGIN
			SET @Sql += '
	SELECT o.* FROM ( '
			SET @Sql += @SqlHead + @StrStt + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
	) AS o ' + @InnerStt + '
) '
			SET @SqlSum = @SqlSumHead + @SqlSumOther
		END
	END
	ELSE
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += '
	SELECT DISTINCT o.* FROM ( '
			SET @Sql += @SqlHead + @StrStt + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + @StrStt + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + ',2[Stt] 
		FROM PD_AllotReqBill_His b ' + @SqlJoin + @SqlParam_His + '
		UNION ALL ' + @SqlHead + ',2[Stt] 
		FROM PD_AllotReqBill_His b ' + @SqlJoin + @SqlParam_His + '
	) AS o ' + @InnerStt + '
) '
			SET @SqlSum = @SqlSumHead + @SqlSumOther + '
				UNION ALL 
	' + @SqlSumHead_His + @SqlSumOther_His
		END
		ELSE
		BEGIN
			SET @Sql += '
	SELECT o.* FROM ( '
			SET @Sql += @SqlHead + @StrStt + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + ',2[Stt] 
		FROM PD_AllotReqBill_His b ' + @SqlJoin + @SqlParam_His + '
	) AS o ' + @InnerStt + '
) '
			SET @SqlSum = @SqlSumHead + @SqlSumOther + '
				UNION ALL 
	' + @SqlSumHead_His + @SqlSumOther_His
		END
	END
	SET @Sql += '
SELECT * INTO #tempbo 
FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillNo) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
WHERE B.ROWID>(@PageNo-1)*@PageSize
AND B.ROWID<=@PageNo*@PageSize
SELECT o.*,s.FHQty,s.FHTotal,w1.WhsName[InWhsName],w2.WhsName[OutWhsName],e.ElyName,d.DeptName,CASE o.StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow] 
,CASE o.IsDraft WHEN 0 THEN ''已生效'' ELSE ''未生效'' END [IsDraftShow] 
FROM #tempbo o 
INNER JOIN BD_Whs w1 ON w1.WhsID=o.InWhsID 
INNER JOIN BD_Whs w2 ON w2.WhsID=o.OutWhsID 
INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
INNER JOIN (' + @SqlSum + ') s ON s.BillNo = o.BillNo 
DROP TABLE #tempbo '
END
ELSE
BEGIN
	IF @IsHistory = 0 
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += '
	SELECT DISTINCT o.* FROM (' + @SqlHead + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + '
		FROM PD_AllotReqBill b ' + @SqlJoin2 + @SqlParam + '
	) AS o 
) '
			SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,3)[Stt] ' + @SqlSumOther
		END
		ELSE
		BEGIN
			SET @Sql += @SqlHead + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
) '
			SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,3)[Stt] ' + @SqlSumOther
		END
	END
	ELSE
	BEGIN
		IF(@SqlJoin2 <> '')
		BEGIN
			SET @Sql += '
	SELECT DISTINCT o.* FROM (' + @SqlHead + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + '
		FROM PD_AllotReqBill b ' + @SqlJoin2 + @SqlParam + '
		UNION ALL ' + @SqlHead + '
		FROM PD_AllotReqBill_His b ' + @SqlJoin + @SqlParam_His + '
		UNION ALL ' + @SqlHead + '
		FROM PD_AllotReqBill_His b ' + @SqlJoin2 + @SqlParam_His + '
	) AS o 
) '
			SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,3)[Stt] ' + @SqlSumOther + '
				UNION ALL 
				' + @SqlSumHead_His + ',dbo.UF_PD_GetBillStt(o.BillNo,3)[Stt] ' + @SqlSumOther_His
		END
		ELSE
		BEGIN
			SET @Sql += @SqlHead + '
		FROM PD_AllotReqBill b ' + @SqlJoin + @SqlParam + '
		UNION ALL ' + @SqlHead + '
		FROM PD_AllotReqBill_His b ' + @SqlJoin + @SqlParam_His + '
) '
			SET @SqlSum = @SqlSumHead + ',dbo.UF_PD_GetBillStt(o.BillNo,3)[Stt] ' + @SqlSumOther + '
				UNION ALL 
				' + @SqlSumHead_His + ',dbo.UF_PD_GetBillStt(o.BillNo,3)[Stt] ' + @SqlSumOther_His
		END
	END
	SET @Sql += '
SELECT * INTO #tempbo 
FROM (SELECT ROW_NUMBER() OVER( ORDER BY BillNo) AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData ) B
WHERE B.ROWID>(@PageNo-1)*@PageSize
AND B.ROWID<=@PageNo*@PageSize
SELECT o.*,s.InspectQty,s.Stt,s.FHQty,s.FHTotal,w1.WhsName[InWhsName],w2.WhsName[OutWhsName],e.ElyName,d.DeptName
	,CASE o.StopTag WHEN 1 THEN ''已中止'' ELSE ''未中止'' END [StopTagShow] 
	,CASE o.IsDraft WHEN 0 THEN ''已生效'' ELSE ''未生效'' END [IsDraftShow] 
FROM #tempbo o 
INNER JOIN BD_Whs w1 ON w1.WhsID=o.InWhsID 
INNER JOIN BD_Whs w2 ON w2.WhsID=o.OutWhsID 
INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
INNER JOIN (' + @SqlSum + ') s ON s.BillNo = o.BillNo 
DROP TABLE #tempbo '
END
IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--PRINT @Sql
EXEC SP_EXECUTESQL @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate VARCHAR(50),@BillEndDate VARCHAR(50),@DlvStartDate VARCHAR(50),@DlvEndDate VARCHAR(50),@BillCode VARCHAR(50),@InWhsID VARCHAR(1000),@OutWhsID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@GoodsID VARCHAR(1000),@Description VARCHAR(50),@Summary VARCHAR(50),@Stt VARCHAR(50),@StopTag INT=9,@IsDraft INT=9,@OperatorID INT,@AuditStatus VARCHAR(100), @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100)',@PageNo,@PageSize,@BillStartDate,@BillEndDate,@DlvStartDate,@DlvEndDate,@BillCode,@InWhsID,@OutWhsID,@DeptID,@ElyID,@GoodsID,@Description,@Summary,@Stt,@StopTag,@IsDraft,@OperatorID,@AuditStatus, @Model, @AbbName, @Brand, @Spec, @BarCode
END

GO








IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryStockBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryStockBill]
GO
/****** Object:  StoredProcedure [UP_PD_QueryStockBill]    Script Date: 06/16/2014 13:56:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/6/16
-- Description:	 查询盘点单
-- =============================================
CREATE PROCEDURE [UP_PD_QueryStockBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SqlMain NVARCHAR(4000), @SqlDetail NVARCHAR(4000), @SqlSerial NVARCHAR(4000), 
	        @MainTable NVARCHAR(40) = 'PD_StockBill', @DetailTable NVARCHAR(40) = 'PD_StockDetail', 
	        @SerialTable NVARCHAR(40) = 'PD_StockSerial'
	IF NOT EXISTS (SELECT 1 FROM PD_StockBill WHERE BillNo = @BillNo)
		BEGIN
			SET @MainTable += '_His'
			SET @DetailTable += '_His'
			SET @SerialTable += '_His'
		END
	SET @SqlMain = 'SELECT stock.BillNo, stock.BillCode, stock.BillDate, stock.DeptID, stock.ElyID, stock.WhsID, stock.BillQty, 
						   stock.Total, creator.ElyName AS CreatorName, stock.CreateTime, stock.Summary, stock.[Description], stock.Stt, 
						   stock.IsDraft, stock.Creator AS CreatorID, whs.WhsName, dept.DeptName, ely.ElyName 
						   FROM ' + @MainTable + ' stock
						   LEFT JOIN BD_Whs whs ON stock.WhsID = whs.WhsID
						   LEFT JOIN BD_Dept dept ON stock.DeptID = dept.DeptID
						   LEFT JOIN BD_Employee ely ON stock.ElyID = ely.ElyID
						   LEFT JOIN BD_Employee creator ON stock.Creator = creator.ElyID
						WHERE stock.BillNo = @BillNo'  --查询主表
						
	EXEC sp_executesql @SqlMain, N'@BillNo INT', @BillNo
        
    SET @SqlDetail = 'SELECT detail.DID, detail.BillNo, detail.BarCode, detail.GoodsID, detail.Ppt1ID, detail.Ppt2ID, detail.WhsID, 
						   detail.WhsPtID, detail.StockQty, detail.CheckQty, detail.PLQty, detail.Remark, goods.GoodsNo, 
						   goods.GoodsName, goods.Spec, goods.Model, price.Unit, ppt1.Value AS Ppt1Name, ppt2.Value AS Ppt2Name, goods.IsSerial,
						   whspt.WhsPtName, price.UnitID AS UnitID1, price.Unit AS Unit1, price.Convfactor AS Convfactor1, price.BarCode AS BarCode1,
						   price2.UnitID AS UnitID2, price2.Unit AS Unit2, price2.BarCode AS BarCode2,
						   case when price2.Convfactor IS null then 1 else price2.Convfactor end  AS Convfactor2,
						   price3.UnitID AS UnitID3, price3.Unit AS Unit3, price2.BarCode AS BarCode3,
						   case when price3.Convfactor IS null then 1 else price3.Convfactor end  AS Convfactor3,
						   detail.BatchNumber, detail.ProductDate, detail.EndDate, detail.CostPrice, goods.CostMethod,
						   goods.DateType, goods.ValidDays, goods.NearbyDays, detail.IsSelectBatch
						   FROM ' + @DetailTable + ' detail
						   LEFT JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID
						   LEFT JOIN BD_Goods_Price price ON price.GoodsID = detail.GoodsID
						   LEFT JOIN BD_Goods_Ppt1 ppt1 ON ppt1.Ppt1ID = detail.Ppt1ID
						   LEFT JOIN BD_Goods_Ppt2 ppt2 ON ppt2.Ppt2ID = detail.Ppt2ID
						   LEFT JOIN BD_Whs_Position whspt ON whspt.WhsPtID = detail.WhsPtID
						   LEFT JOIN BD_Goods_Price price2 ON price2.GoodsID = detail.GoodsID And price2.UnitID = 2
						   LEFT JOIN BD_Goods_Price price3 ON price3.GoodsID = detail.GoodsID And price3.UnitID = 3
						WHERE detail.BillNo = @BillNo AND price.UnitID = 1'  --查询明细表
						
	EXEC sp_executesql @SqlDetail, N'@BillNo INT', @BillNo
	
	SET @SqlSerial = 'SELECT Serial, BillDID, ps.Remark FROM dbo.' + @SerialTable + ' ps INNER JOIN dbo.' + @DetailTable + ' pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo'
						
	EXEC sp_executesql @SqlSerial, N'@BillNo INT', @BillNo
END
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2015-01-21
	描述：库存分布查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryStockDistribution]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@GoodsID INT=0,
	@OperatorID INT = 0	
)

AS
SET NOCOUNT ON
DECLARE @sql nvarchar(MAX)='',@SqlCreateTable nvarchar(max)='',@LimitKtypeSql varchar(Max)='',@KtypeLimit INT=0,@SqlAuUnit varchar(max)='',@SqlBase varchar(max)='' 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	if not exists(select 1 from SS_Role_Jur rj inner join SS_Role r on rj.RoleID = r.RoleID inner join SS_Oper_Role op on r.RoleID = op.RoleID where rj.JurID =  1431010 and rj.opp = 1 and op.OperID = @OperatorID )
	begin
		SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
		SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =a.WhsID '
	end
End		

Select @sql = ' select a.WhsID,w.WhsNO,w.WhsName,a.GoodsID,a.Qty as BSQty,a.Price as CostPrice,a.Total as GoodsCostTotal 
					from PD_GoodsStock a inner join BD_Whs w on a.WhsID = w.WhsID ' +@LimitKtypeSql+ ' where GoodsID = @GoodsID and Qty <> 0'

SELECT @sql= @SqlCreateTable +'
;WITH PagingData AS 
('	+@sql+'
)
'

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP1 on Data.GoodsID=BGP1.GoodsID And BGP1.UnitID=1 '
Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP2 on Data.GoodsID=BGP2.GoodsID And BGP2.UnitID = 2'
Set @SqlAuUnit += 'Left Join BD_Goods_Price BGP3 on Data.GoodsID=BGP3.GoodsID And BGP3.UnitID = 3'
Select @SqlBase += ' ,BGP1.Unit as Unit1,BGP1.Convfactor as Convfactor1 '
Select @SqlBase += ' ,BGP2.Unit as Unit2,case when BGP2.Convfactor IS NULL then 1 else BGP2.Convfactor end as Convfactor2'
Select @SqlBase += ' ,BGP3.Unit as Unit3,case when BGP3.Convfactor IS NULL then 1 else BGP3.Convfactor end as Convfactor3'

SELECT @sql += ',DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY WhsNO ) AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	select * into #tempTable from DATA
	'
select @sql +=' select Data.*,G.GoodsNO,G.GoodsName '+@SqlBase+'
	 from #tempTable Data  
	Inner Join BD_Goods G On Data.GoodsID = G.GoodsID	
	' + @SqlAuUnit
select @sql += ' ORDER BY ROWID '
Select @sql += ' drop table #tempTable '

exec sp_executesql @Sql,N'@PageNo Int,@PageSize Int,@GoodsID Int,@OperatorID Int'
			,@PageNo,@PageSize,@GoodsID,@OperatorID
			
GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：李文博
	日期：2014-06-11
	描述：获取商品辅助单位，价格跟踪[转换列数据]
-------------------------------------------*/
CREATE PROCEDURE UP_PD_QueryUnitPrice
(
	@GoodsID INT=0,
	@BtypeID INT=0,
	@Lvl VARCHAR(10),
	@PriceTrack BIT = 0,
	@DisTrack BIT = 0,
	@OperatorID INT = 0
)

AS
DECLARE @sql NVARCHAR(MAX) = '', @PrePriceSql NVARCHAR(MAX) = '', @PriceTrackSql NVARCHAR(MAX) = '', @BtypeTrack TINYINT = 1

IF @BtypeID <> 0
BEGIN
	SELECT @BtypeTrack = PriceTrack FROM BD_Btype WHERE BTypeID = @BtypeID
END

IF (@Lvl <> '0')
BEGIN
	IF NOT EXISTS(SELECT 1 FROM dbo.UF_OT_GoodsPriceLimit(@OperatorID) WHERE PriceLvl = CONVERT(INT,@Lvl))
		 SET @PrePriceSql = ',
			NULL AS PrePrice1,
			NULL AS PrePrice2,
			NULL AS PrePrice3
		 '
	ELSE
		 SET @PrePriceSql = ',
					PrePrice1,
					PrePrice2,
					PrePrice3
		'
END

--无最近进价权限
--IF EXISTS (SELECT 1 FROM dbo.UF_OT_GoodsPriceLimit(@OperatorID) WHERE PriceLvl = 6)
	
SET @PriceTrackSql = ',
			PchPrice1,
			PchPrice2,
			PchPrice3,
			SellPrice1,
			SellPrice2,
			SellPrice3	
	'


SET @sql = '
SELECT 
		TbUnit.GoodsID,
		Unit1,
		Unit2,
		Unit3,
		BarCode1,
		BarCode2,
		BarCode3,
		Convfactor1,
		Convfactor2,
		Convfactor3'

IF @BtypeID <> 0 AND @Lvl<>'0'
BEGIN
	SET @sql +=  @PrePriceSql
END
IF @PriceTrack = 1 AND @BtypeTrack = 1
BEGIN	
	SET @sql += @PriceTrackSql
END

IF @DisTrack = 1 AND @BtypeTrack = 1
BEGIN
	SET @sql +=',	
		PchDis1,
		PchDis2,
		PchDis3,
		SellDis1,
		SellDis2,
		SellDis3	
		'
END

SET @sql+='
FROM
(SELECT GoodsID ,[1] AS Unit1,[2] AS Unit2,[3] AS Unit3 
FROM (SELECT GoodsID, UnitID, Unit FROM BD_Goods_Price WHERE GoodsID = @GoodsID) AS SourceData PIVOT (MAX(Unit) FOR UnitID IN ([1],[2],[3])) AS A)
TbUnit  
INNER JOIN
(SELECT GoodsID ,[1] AS BarCode1,[2] AS BarCode2,[3] AS BarCode3
FROM (SELECT GoodsID, UnitID, BarCode FROM BD_Goods_Price WHERE GoodsID = @GoodsID) AS SourceData PIVOT (MAX(BarCode) FOR UnitID IN ([1],[2],[3]))AS A) 
TbBarCode 
ON TbUnit.GoodsID = TbBarCode.GoodsID
INNER JOIN
(SELECT GoodsID ,[1] AS Convfactor1,[2] AS Convfactor2,[3] AS Convfactor3
FROM (SELECT GoodsID, UnitID, Convfactor FROM BD_Goods_Price WHERE GoodsID = @GoodsID) AS SourceData PIVOT (MAX(Convfactor) FOR UnitID IN ([1],[2],[3]))AS A) 
TbConvfactor 
ON TbUnit.GoodsID = TbConvfactor.GoodsID
'
IF @BtypeID <> 0 AND @Lvl <>'0'
BEGIN
	SET @sql +=  '
	INNER JOIN 
	(SELECT GoodsID ,[1] AS PrePrice1,[2] AS PrePrice2,[3] AS PrePrice3
	FROM (SELECT GoodsID, UnitID, Price'+@Lvl+' FROM BD_Goods_Price WHERE GoodsID = @GoodsID) AS SourceData PIVOT (SUM(Price'+@Lvl+') FOR UnitID IN ([1],[2],[3]))AS A) 
	TbPrePrice 
	ON TbUnit.GoodsID = TbPrePrice.GoodsID
		'
END
IF @PriceTrack = 1 AND @BtypeTrack = 1
BEGIN	
	SET @sql +='	
		LEFT JOIN 
		(SELECT GoodsID ,[1] AS PchPrice1,[2] AS PchPrice2,[3] AS PchPrice3
		FROM (SELECT GoodsID, UnitID, PchPrice FROM PD_PriceTrail WHERE GoodsID = @GoodsID AND BtypeID = @BtypeID) AS SourceData PIVOT (SUM(PchPrice) FOR UnitID IN ([1],[2],[3]))AS A) 
		TbPchPrice 
		ON TbUnit.GoodsID = TbPchPrice.GoodsID
		LEFT JOIN 
		(SELECT GoodsID ,[1] AS SellPrice1,[2] AS SellPrice2,[3] AS SellPrice3
		FROM (SELECT GoodsID, UnitID, SellPrice FROM PD_PriceTrail WHERE GoodsID = @GoodsID AND BtypeID = @BtypeID) AS SourceData PIVOT (SUM(SellPrice) FOR UnitID IN ([1],[2],[3]))AS A) 
		TbSellPrice 
		ON TbUnit.GoodsID = TbSellPrice.GoodsID
		'
	
END
IF @DisTrack = 1 AND @BtypeTrack = 1
BEGIN
	SET @sql +='	
		LEFT JOIN 
		(SELECT GoodsID ,[1] AS PchDis1,[2] AS PchDis2,[3] AS PchDis3
		FROM (SELECT GoodsID, UnitID, PchDis FROM PD_PriceTrail WHERE GoodsID = @GoodsID AND BtypeID = @BtypeID) AS SourceData PIVOT (SUM(PchDis) FOR UnitID IN ([1],[2],[3]))AS A) 
		TbPchDis 
		ON TbUnit.GoodsID = TbPchDis.GoodsID
		LEFT JOIN 
		(SELECT GoodsID ,[1] AS SellDis1,[2] AS SellDis2,[3] AS SellDis3
		FROM (SELECT GoodsID, UnitID, SellDis FROM PD_PriceTrail WHERE GoodsID = @GoodsID AND BtypeID = @BtypeID) AS SourceData PIVOT (SUM(SellDis) FOR UnitID IN ([1],[2],[3]))AS A) 
		TbSellDis
		ON TbUnit.GoodsID = TbSellDis.GoodsID
		'
	
END
EXEC sp_executesql @sql,N'@GoodsID INT, @BtypeID INT, @Lvl VARCHAR(10)', @GoodsID,@BtypeID,@Lvl

GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_QueryVipChargeBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_QueryVipChargeBill]
GO
/****** Object:  StoredProcedure [UP_PD_QueryVipChargeBill]    Script Date: 06/16/2014 11:22:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2016/3/7
-- Description:	 查询会员充值单
-- =============================================
CREATE PROCEDURE [UP_PD_QueryVipChargeBill](
     @BillNo INT = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SqlMain NVARCHAR(4000), @SqlDetail NVARCHAR(4000), @IsAccounts INT = 0, @BillTypeID INT = 602,
	        @MainTable NVARCHAR(40) = 'VS_VipChargeBill', @DetailTable NVARCHAR(40) = 'VS_VipChargeDetail'
	IF EXISTS(SELECT 1 FROM PD_MulAccounts WHERE BillTypeID = @BillTypeID AND BillNo = @BillNo)
		SELECT @IsAccounts = 1
	IF NOT EXISTS (SELECT 1 FROM dbo.VS_VipChargeBill WHERE BillNo = @BillNo)
		BEGIN
			SET @MainTable += '_His'
			SET @DetailTable += '_His'
		END
	-- 查询主表
	SET @SqlMain = 'SELECT bill.BillNo, bill.BillCode, bill.BillDate, bill.DeptID, bill.ElyID, bill.FinanceID, bill.PayRecTotal, bill.PaidTotal,
						   bill.Privilege, bill.Total, creator.ElyName AS CreatorName, bill.CreateTime, bill.Summary, bill.[Description], bill.IsDraft,
						   bill.Creator AS CreatorID, dept.DeptName, ely.ElyName, bill.AuditStatus, bill.PosElyID, pos.ElyName AS PosName,
						   f.FinanceName, @IsAccounts AS IsAccounts, bill.Red
						   FROM dbo.' + @MainTable + ' bill
						   LEFT JOIN dbo.BD_Dept dept ON bill.DeptID = dept.DeptID
						   LEFT JOIN dbo.BD_Employee ely ON bill.ElyID = ely.ElyID 
						   LEFT JOIN dbo.BD_Employee creator ON bill.Creator = creator.ElyID
						   LEFT JOIN dbo.BD_Employee pos ON bill.PosElyID = pos.ElyID
		                   LEFT JOIN dbo.BD_Finance f ON bill.FinanceID=f.FinanceID
					 WHERE bill.BillNo = @BillNo'  
						
	EXEC sp_executesql @SqlMain, N'@BillNo INT, @IsAccounts INT', @BillNo, @IsAccounts
     
     -- 查询明细
     SET @SqlDetail = 'SELECT detail.DID, detail.BillNo, detail.VipCardID, detail.Total, detail.Privilege, detail.Remark, vip.Status,
                              vip.VipCardTypeID, vip.VipCardNO, vip.VipName, vip.CardHolder, vip.EndDate, vipType.TypeName, 
                              CASE bill.IsDraft WHEN 1 THEN vip.MoneyBalance ELSE detail.TotalBanlance END AS TotalBanlance, 
                              ((CASE bill.IsDraft WHEN 1 THEN vip.MoneyBalance ELSE detail.TotalBanlance END) + detail.Total) AS AfterBanlance, 
                              (detail.Total - detail.Privilege) AS PayRecTotal
							FROM dbo.' + @DetailTable + ' detail
							INNER JOIN dbo.' + @MainTable + ' bill ON bill.BillNo = detail.BillNo
							LEFT JOIN dbo.VS_VipCard vip ON vip.VipCardID = detail.VipCardID
							LEFT JOIN dbo.VS_VipCardType vipType ON vipType.VipCardTypeID = vip.VipCardTypeID
					  WHERE detail.BillNo = @BillNo
					   ORDER BY detail.DID' 
						
	EXEC sp_executesql @SqlDetail, N'@BillNo INT', @BillNo
		  
	-- 查询多账户信息
	SELECT FinanceID, Total FROM PD_MulAccounts WHERE BillTypeID = @BillTypeID and BillNo = @BillNo 
                                                      
END
GO




/****** Object:  StoredProcedure [UP_PD_QueryVipConsumSummaryList]    Script Date: 06/23/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_QueryVipConsumSummaryList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_QueryVipConsumSummaryList]
GO

/****** Object:  StoredProcedure [UP_PD_QueryVipConsumSummaryList]    Script Date: 06/23/2014 15:42:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：hlin
	日期：2015-12-11
	描述：会员消费统计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryVipConsumSummaryList]
(			   
	@pageNo INT=1,					--页码
	@pageSize INT=10,				--分页数
	@BillDateType INT=1,			--单据日期类型:1=录单日期,2=制单日期,3=过账日期  对应BillDate,CreateTime,PosTime
	@BillStartDate DATETIME,		--单据开始日期
	@BillEndDate DATETIME,			--单据结束日期
	@SaleBillOut INT=1,				--销售出库单勾选状态
	@SaleBillIn INT=1,				--销售退货单勾选状态
	@ExchangeBill INT=1,			--积分兑换单勾选状态
	@VipCardNo VARCHAR(30) = '',   
	@VipCardMatch INT = 0,          
	@VipCardTypeID VARCHAR(1000) = '',
	@VipName VARCHAR(50) = '',   
	@VipNameMatch INT = 0,       
	@CardHolder VARCHAR(50) = '',   
	@CardHolderMatch INT = 0,       
	@Tel VARCHAR(20) = '',   
	@TelMatch INT = 0,       
	@BTypeID VARCHAR(1000) = '',		--部门
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@CreatorID VARCHAR(1000)='',    --制单人
	@WhsID VARCHAR(1000) = '',		--仓库
	@GoodsID VARCHAR(1000) = '',	--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(20) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(50) = '',	--商品名称
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@Goods INT=0,					--商品汇总项：商品
	@Ppt1 INT=0,					--商品汇总项：属性一
	@Ppt2 INT=0,					--商品汇总项：属性二
	@GoodsC1 INT=0,					--商品汇总项：自定义字段一
	@GoodsC2 INT=0,					--商品汇总项：自定义字段二
	@GoodsC3 INT=0,					--商品汇总项：自定义字段三
	@GoodsC4 INT=0,					--商品汇总项：自定义字段四
	@GoodsC5 INT=0,					--商品汇总项：自定义字段五
	@GiftState INT=9,				--赠品状态：9=全部,1=是,0=否
	@Privilege INT=0,				--包含优惠：1=是,0=否
	@CollectType1 INT=0,			--汇总条件一:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer1 INT=0,					--汇总层级一:0:空 1-5:XX分类层级 6:XX
	@CollectType2 INT=0,			--汇总条件二:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer2 INT=0,					--汇总层级二:0:空 1-5:XX分类层级 6:XX
	@OrderType1 INT=0,				--排序条件一:1=商品分类编码,2=商品分类名称,3=商品编码,4=商品名称,5=往来单位分类编码,6=往来单位分类名称,7=往来单位编码,8=往来单位名称,9=仓库分类编码,10=仓库分类名称,11=仓库编码,12=仓库名称,13=地区编码,14=地区名称,15=部门编码,16=部门名称,17=职员编码,18=职员名称,19=数量,20=销售均价,21=销售金额,22=成本均价,23=成本金额,24=毛利,25=毛利率,26=赠品数量,27=属性一,28=属性二
	@OrderSeq1 INT=1,				--排序规则：1=升序，2=降序
	@OrderType2 INT=0,				--排序条件一:1=商品分类编码,2=商品分类名称,3=商品编码,4=商品名称,5=往来单位分类编码,6=往来单位分类名称,7=往来单位编码,8=往来单位名称,9=仓库分类编码,10=仓库分类名称,11=仓库编码,12=仓库名称,13=地区编码,14=地区名称,15=部门编码,16=部门名称,17=职员编码,18=职员名称,19=数量,20=销售均价,21=销售金额,22=成本均价,23=成本金额,24=毛利,25=毛利率,26=赠品数量,27=属性一,28=属性二
	@OrderSeq2 INT=1,				--排序规则：1=升序，2=降序
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)
AS
SET NOCOUNT ON
BEGIN
	-- 当日期类型为业务日期的场合，做归档日期的范围判断
	IF @BillDateType = 1
	BEGIN
		DECLARE @Re INT 
		EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
		IF( @Re=1 )RETURN @Re;
	END

DECLARE @Sql NVARCHAR(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlOrder VARCHAR(100)=''
	,@SumData NVARCHAR(MAX),@VbSumHead VARCHAR(MAx)='',@SumHead NVARCHAR(MAX),@SumHeadFH NVARCHAR(MAX),@SumJoin NVARCHAR(MAX)='',@SumParam NVARCHAR(MAX),@VbSumG VARCHAR(300)=''
	,@Sql_PPB NVARCHAR(MAX),@Sql_PPB_His NVARCHAR(MAX),@Sql_PRB NVARCHAR(MAX),@Sql_PRB_His NVARCHAR(MAX)
	,@BillData NVARCHAR(MAX),@VbBDHead VARCHAR(MAX)='',@BDHead VARCHAR(MAX),@VbSumBDHead VARCHAR(MAX)='',@VbBDJoin VARCHAR(MAX)='',@CFBDJoin NVARCHAR(MAX)='',@VbSumBDG VARCHAR(600)=''
	,@AVGPrice VARCHAR(150),@AVGCostPrice VARCHAR(150),@Profit VARCHAR(100),@ProfitRate VARCHAR(150)
	,@bg1 VARCHAR(500),@bt1 VARCHAR(500),@bw1 VARCHAR(500),@ba1 VARCHAR(500),@bd1 VARCHAR(500)
	,@bg2 VARCHAR(500),@bt2 VARCHAR(500),@bw2 VARCHAR(500),@ba2 VARCHAR(500),@bd2 VARCHAR(500)
	,@BtypeLimit INT=0,@KtypeLimit INT=0 ,@GoodsCSourceType1 int = 1,@GoodsCSourceType2 int = 1,@GoodsCSourceType3 int = 1,@GoodsCSourceType4 int = 1,@GoodsCSourceType5 int = 1
	,@GoodsSource1 int = 1,@GoodsSource2 int = 1,@GoodsSource3 int = 1,@GoodsSource4 int = 1,@GoodsSource5 int = 1
	,@Sql_Exchange NVARCHAR(MAX),@Sql_Exchange_His NVARCHAR(MAX),@SumHeadEX NVARCHAR(max),@VipTableStr NVARCHAR(max)
--INNER JOIN BEGIN
Select @GoodsCSourceType1 = SourceType from BD_Goods_CustomItem where CustItemID = 1
Select @GoodsCSourceType2 = SourceType from BD_Goods_CustomItem where CustItemID = 2
Select @GoodsCSourceType3 = SourceType from BD_Goods_CustomItem where CustItemID = 3
Select @GoodsCSourceType4 = SourceType from BD_Goods_CustomItem where CustItemID = 4
Select @GoodsCSourceType5 = SourceType from BD_Goods_CustomItem where CustItemID = 5

IF @BTypeID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _BType ON _BType.typeid = p.BTypeID '

IF @DeptID <> ''
BEGIN
	SET @SumJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=p.DeptID '
	--SET @Sql += 'DECLARE @TVP_Dept AS [TVP_Type] 
	--INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
	--SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
	--INNER JOIN BD_Dept cd ON cd.[Path] LIKE d.[Path] + ''%''
	--WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, '','') _Dept WHERE _Dept.typeid = d.DeptID) '
END
IF @ElyID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = p.ElyID '
IF @CreatorID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@CreatorID, '','') _PEly ON _PEly.typeid = p.Creator '
IF @WhsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = p.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SumJoin += '
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=p.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SumJoin += '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=p.WhsID '
/*权限使用非公用方法*/
/*
IF @OperatorID <> 1 
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SumJoin +='
	INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=p.BTypeID '
	END
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @SumJoin +='
	INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=p.WhsID '
	END
END
*/
IF @GoodsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID '
IF @GoodsNo <> '' OR @GoodsName <> '' 
	SET @SumJoin +='
	INNER JOIN BD_Goods g ON g.GoodsID=dtl.GoodsID '
IF @BarCode <> ''
BEGIN 
	SET @SumJoin += ' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID and pri.UnitID = 1 '
END 

IF @VipCardNo<>'' OR @VipCardTypeID<> '' OR @VipName <>'' OR  @CardHolder<>'' OR @Tel<>''       
  SET @SumJoin += ' 
  INNER JOIN Vs_VipCard V ON V.VipCardID = p.VipCardID '
IF @VipCardTypeID<> ''
	SET @SumJoin += ' 
	INNER JOIN Vs_VipCardType Vt ON V.VipCardTypeID = vt.VipCardTypeID
	INNER JOIN dbo.UF_OT_Split_Int(@VipCardTypeID, '','') vtype ON vtype.typeid=vt.VipCardTypeID  '
--INNER JOIN END

--条件BEGIN
IF @BillDateType=1
	SET @SqlDTStr='dtl.BillDate'
IF @BillDateType=2
	SET @SqlDTStr='p.CreateTime'	
IF @BillDateType=3
	SET @SqlDTStr='p.PosTime'	
SET @SumParam = '
	WHERE '+@SqlDTStr+' BETWEEN @BillStartDate AND @BillEndDate AND p.IsDraft=0 AND p.Red=0 AND p.VipCardID<>0 '
	
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0 SET @SumParam += 'AND g.GoodsNo LIKE ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch=1 SET @SumParam += 'AND g.GoodsNo=@GoodsNo '  
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0 SET @SumParam += 'AND g.GoodsName LIKE ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch=1 SET @SumParam += 'AND g.GoodsName=@GoodsName '  
END

--商品条码
IF @BarCode <> ''      
BEGIN 
	IF @BarCodeMatch = 0
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=dtl.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=dtl.GoodsID)'
END

IF @VipCardNo<>''
BEGIN
	IF @VipCardMatch=0 SET @SumParam += 'AND v.VipCardNO LIKE ''%''+@VipCardNO+''%'' '  
	IF @VipCardMatch=1 SET @SumParam += 'AND v.VipCardNO=@VipCardNO ' 
END
IF @VipName<>''
BEGIN
	IF @VipNameMatch=0 SET @SumParam += 'AND v.VipName LIKE ''%''+@VipName+''%'' '  
	IF @VipNameMatch=1 SET @SumParam += 'AND v.VipName=@VipName ' 
END
IF @CardHolder<>''
BEGIN
	IF @CardHolderMatch=0 SET @SumParam += 'AND v.CardHolder LIKE ''%''+@CardHolder+''%'' '  
	IF @CardHolderMatch=1 SET @SumParam += 'AND v.CardHolder=@CardHolder ' 
END
IF @Tel<>''
BEGIN
	IF @TelMatch=0 SET @SumParam += 'AND v.Tel LIKE ''%''+@Tel+''%'' '  
	IF @TelMatch=1 SET @SumParam += 'AND v.Tel=@Tel ' 
END
  
 

--条件END

--
--商品分类
SET @bg1 = '
			SELECT pbs.BaseID,[_bg].GoodsID 
			FROM (
				SELECT GT.GoodsTypeID AS BaseID,T.GoodsTypeID FROM BD_Goods_Type GT 
				INNER JOIN BD_Goods_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) pbs
			INNER JOIN BD_Goods _bg ON [_bg].GoodsTypeID = pbs.GoodsTypeID '

--仓库分类
SET @bw1 = '
			SELECT wbs.BaseID,[_bw].WhsID 
			FROM (
				SELECT GT.WhsTypeID AS BaseID,T.WhsTypeID FROM BD_Whs_Type GT 
				INNER JOIN BD_Whs_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) wbs
			INNER JOIN BD_Whs _bw ON [_bw].WhsTypeID = wbs.WhsTypeID '

--部门分类
SET @bd1 = '
			SELECT dbs.BaseID,_bd.DeptID 
			FROM (
				SELECT GT.DeptID AS BaseID,T.DeptID 
				FROM BD_Dept GT 
				INNER JOIN BD_Dept T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer1 AND GT.SonNum = 0) OR (GT.Lvl = @Layer1 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Dept _bd ON [_bd].DeptID = dbs.DeptID '
--

-----汇总层级一-----begin
IF @CollectType1 <> 0
BEGIN
	IF @CollectType1 = 1
	BEGIN
		IF @Layer1 <> 6 --汇总层级:商品分类1-5
		BEGIN
			SET @VbSumHead += ',dtl.GoodsID '
			SET @VbSumG += 'dtl.GoodsID '
			SET @VbBDHead += ',gt.TypeCode[Code1],gt.TypeName[Name1] '
			SET @VbSumBDHead += ',pbs.BaseID[ID1] '
			SET @VbSumBDG += 'pbs.BaseID '
			SET @VbBDJoin += '
		INNER JOIN BD_Goods_Type gt ON gt.GoodsTypeID=o.ID1'
			SET @CFBDJoin += '
		INNER JOIN ('+@bg1+'
		) pbs ON pbs.GoodsID = sd.GoodsID '
		END
		ELSE
		BEGIN
			IF @Ppt1=0 AND @Ppt2=0 And @GoodsC1 = 0 And @GoodsC2 = 0 And @GoodsC3 = 0 And @GoodsC4 = 0 And @GoodsC5 = 0
			BEGIN
				SET @VbSumHead += ',dtl.GoodsID '
				SET @VbSumG += 'dtl.GoodsID '
				SET @VbBDHead += ',g.GoodsNo[Code1],g.GoodsName[Name1],g.Model[Model1],g.GoodsAbbName[GoodsAbbName1],g.Brand[Brand1],g.Spec[Spec1],pri.BarCode[BarCode1] '
				SET @VbSumBDHead += ',sd.GoodsID[ID1] '
				SET @VbSumBDG += ' sd.GoodsID '
				SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID1 
	INNER JOIN BD_Goods_Price pri ON o.ID1 = pri.GoodsID AND pri.UnitID = 1 '
			END
			ELSE
			BEGIN
				IF @Goods<>0 
				BEGIN
					SET @VbSumHead += ',dtl.GoodsID '
					SET @VbSumG += 'dtl.GoodsID '
					SET @VbBDHead += ',g.GoodsNo[Code1],g.GoodsName[Name1],g.Model[Model1],g.GoodsAbbName[GoodsAbbName1],g.Brand[Brand1],g.Spec[Spec1],pri.BarCode[BarCode1] '
					SET @VbSumBDHead += ',sd.GoodsID[ID1] '
					SET @VbSumBDG += 'sd.GoodsID '
					SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID1 
	INNER JOIN BD_Goods_Price pri ON o.ID1 = pri.GoodsID AND pri.UnitID = 1'
				END
				IF @Ppt1<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt1ID '
					SET @VbBDHead += ',p1.Value[Ppt1Name1] '
					SET @VbSumBDHead += ',sd.Ppt1ID '
					IF @Goods<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt1ID ' 
						SET @VbSumBDG += ',sd.Ppt1ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += 'dtl.Ppt1ID '
						SET @VbSumBDG += 'sd.Ppt1ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt1 p1 ON p1.Ppt1ID=o.Ppt1ID '
				END
				IF @Ppt2<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt2ID '
					SET @VbBDHead += ',p2.Value[Ppt2Name1] '
					SET @VbSumBDHead += ',sd.Ppt2ID '
					IF @Goods<>0 OR @Ppt1<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt2ID '
						SET @VbSumBDG += ',sd.Ppt2ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += 'dtl.Ppt2ID '
						SET @VbSumBDG += 'sd.Ppt2ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt2 p2 ON p2.Ppt2ID=o.Ppt2ID '
				END
			END
			
			--自定义字段分类
			IF @Goods = 0
			BEGIN
				IF(@GoodsC1 <> 0)
				BEGIN
				   Set @VbSumHead += ' ,BGC.CustVal1 '
				   SET @VbSumBDG += ',sd.CustVal1 '				       
				   Set @VbSumBDHead += ',sd.CustVal1 '
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal1 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal1 '
				    
				   Set @VbBDHead += ',o.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=o.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=o.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=o.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=o.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=o.CustVal1 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType1 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=o.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal2'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal2 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal2 '
				   Set @VbSumBDHead += ',sd.CustVal2 '
				   SET @VbSumBDG += ',sd.CustVal2 '	
				   Set @VbBDHead += ',o.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=o.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=o.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=o.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=o.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=o.CustVal2 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType2 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=o.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal3'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal3 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal3 '
				   Set @VbSumBDHead += ',sd.CustVal3 '
				   SET @VbSumBDG += ',sd.CustVal3 '				       
				   Set @VbBDHead += ',o.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=o.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=o.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=o.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=o.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=o.CustVal3 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType3 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=o.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal4'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal4 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal4 '
				   Set @VbSumBDHead += ',sd.CustVal4 '
				   SET @VbSumBDG += ',sd.CustVal4 '				       
				   Set @VbBDHead += ',o.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=o.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=o.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=o.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=o.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=o.CustVal4 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType4 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=o.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal5'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal5 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal5 '
				   Set @VbSumBDHead += ',sd.CustVal5 '
				   SET @VbSumBDG += ',sd.CustVal5 '				       
				   Set @VbBDHead += ',o.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=o.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=o.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=o.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=o.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=o.CustVal5 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType5 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=o.CustVal5 '
				   END
				END
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @SumJoin += ' Inner Join BD_Goods_CustomVal BGC ON dtl.GoodsID = BGC.BaseID '
			END
			ELSE
			BEGIN
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @VbBDJoin += ' Inner Join BD_Goods_CustomVal BGC ON o.ID1 = BGC.BaseID '
				IF(@GoodsC1 <> 0)
				BEGIN			
				   Set @VbBDHead += ',BGC.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=BGC.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=BGC.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=BGC.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=BGC.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=BGC.CustVal1 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=BGC.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=BGC.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=BGC.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=BGC.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=BGC.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=BGC.CustVal2 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=BGC.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=BGC.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=BGC.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=BGC.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=BGC.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=BGC.CustVal3 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=BGC.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=BGC.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=BGC.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=BGC.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=BGC.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=BGC.CustVal4 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=BGC.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=BGC.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=BGC.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=BGC.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=BGC.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=BGC.CustVal5 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=BGC.CustVal5 '
				   END
				END				
			END
		END
	END
	IF @CollectType1 = 2
	BEGIN
		SET @VbSumHead += ',p.VipCardID '
		SET @VbSumG += 'p.VipCardID '
		IF @Layer1=1
		BEGIN
			SET @VbBDHead += ',v.VipCardNo[Code1],v.VipCardID '
			SET @VbSumBDHead += ',sd.VipCardID[ID1] '
			SET @VbSumBDG += 'sd.VipCardID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ' ,vt.TypeName[Code1]'
			SET @VbSumBDHead += ',vt.VipCardTypeID[ID1]'
			SET @VbSumBDG += 'vt.VipCardTypeID '
		END
		IF @Layer1=1
			SET @VbBDJoin += '
		INNER JOIN VS_VipCard v ON v.VipCardID=o.ID1'
		ELSE
		BEGIN
			SET @VbBDJoin += '
			INNER JOIN VS_VipCardType vt ON vt.VipCardTypeID=o.ID1'
			SET @CFBDJoin += '
			INNER JOIN VS_VipCard v ON v.VipCardID=sd.VipCardID
			INNER JOIN VS_VipCardType vt ON v.VipCardTypeID=vt.VipCardTypeID '
		END
	END
	IF @CollectType1 = 3
	BEGIN
		SET @VbSumHead += ',dtl.WhsID ' 
		SET @VbSumG += 'dtl.WhsID '
		IF @Layer1 <> 6 --汇总层级:仓库分类1-5
		BEGIN
			SET @VbBDHead += ',wt.TypeCode[Code1],wt.TypeName[Name1] '
			SET @VbSumBDHead += ',kbs.BaseID[ID1] '
			SET @VbSumBDG += 'kbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs_Type wt ON wt.WhsTypeID=o.ID1 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bw1+'
		) kbs ON kbs.WhsID = sd.WhsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',w.WhsNO[Code1],w.WhsName[Name1] '
			SET @VbSumBDHead += ',sd.WhsID[ID1] '
			SET @VbSumBDG += 'sd.WhsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs w ON w.WhsID=o.ID1 '
		END
	END
	IF @CollectType1 = 5
	BEGIN
		SET @VbSumHead += ',p.DeptID '
		SET @VbSumG += 'p.DeptID '
		SET @VbBDHead += ',d.DeptCode[Code1],d.DeptName[Name1] '
		SET @VbBDJoin += '
	INNER JOIN BD_Dept d ON d.DeptID=o.ID1 '
		IF @Layer1<>5 
		BEGIN
			SET @VbSumBDHead += ',dbs.BaseID[ID1] '
			SET @VbSumBDG += 'dbs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@bd1+'
		) dbs ON dbs.DeptID = sd.DeptID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.DeptID[ID1] '
			SET @VbSumBDG += 'sd.DeptID '
		END
	END
	IF @CollectType1 = 6
	BEGIN
		SET @VbSumHead += ',p.ElyID '
		SET @VbSumG += 'p.ElyID '
		SET @VbBDHead += ',e.ElyCode[Code1],e.ElyName[Name1] '
		SET @VbSumBDHead += ',sd.ElyID[ID1] '
		SET @VbSumBDG += 'sd.ElyID '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee e ON e.ElyID=o.ID1 '
	END
	IF @CollectType1 = 7
	BEGIN
		SET @VbSumHead += ',p.Creator '
		SET @VbSumG += 'p.Creator '
		SET @VbBDHead += ',pe.ElyCode[Code1],pe.ElyName[Name1] '
		SET @VbSumBDHead += ',sd.Creator[ID1] '
		SET @VbSumBDG += 'sd.Creator '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee pe ON pe.ElyID=o.ID1 '
	END
END
-----汇总层级一-----END
--
--商品分类
SET @bg2 = '
			SELECT pbs.BaseID,[_bg].GoodsID 
			FROM (
				SELECT GT.GoodsTypeID AS BaseID,T.GoodsTypeID FROM BD_Goods_Type GT 
				INNER JOIN BD_Goods_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) pbs
			INNER JOIN BD_Goods _bg ON [_bg].GoodsTypeID = pbs.GoodsTypeID '

--仓库分类
SET @bw2 = '
			SELECT wbs.BaseID,[_bw].WhsID 
			FROM (
				SELECT GT.WhsTypeID AS BaseID,T.WhsTypeID FROM BD_Whs_Type GT 
				INNER JOIN BD_Whs_Type T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) wbs
			INNER JOIN BD_Whs _bw ON [_bw].WhsTypeID = wbs.WhsTypeID '


--部门分类
SET @bd2 = '
			SELECT dbs.BaseID,_bd.DeptID 
			FROM (
				SELECT GT.DeptID AS BaseID,T.DeptID 
				FROM BD_Dept GT 
				INNER JOIN BD_Dept T ON T.[Path] LIKE GT.[Path]+''%''
				WHERE (GT.Lvl < @Layer2 AND GT.SonNum = 0) OR (GT.Lvl = @Layer2 AND T.SonNum=0)
			) dbs
			INNER JOIN BD_Dept _bd ON [_bd].DeptID = dbs.DeptID '
--
-----汇总层级二-----BEGIN
IF @CollectType2 <> 0
BEGIN
	IF @CollectType2 = 1
	BEGIN
		IF @Layer2 <> 6 --汇总层级:商品分类1-5
		BEGIN
			SET @VbSumHead += ',dtl.GoodsID '
			SET @VbSumG += ',dtl.GoodsID '
			SET @VbBDHead += ',gt.TypeCode[Code2],gt.TypeName[Name2] '
			SET @VbSumBDHead += ',pbs.BaseID[ID2] '
			SET @VbSumBDG += ',pbs.BaseID '
			SET @VbBDJoin += '
		INNER JOIN BD_Goods_Type gt ON gt.GoodsTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bg2+'
		) pbs ON pbs.GoodsID = sd.GoodsID '
		END
		ELSE
		BEGIN
			IF @Ppt1=0 AND @Ppt2=0 And @GoodsC1 = 0 And @GoodsC2 = 0 And @GoodsC3 = 0 And @GoodsC4 = 0 And @GoodsC5 = 0			
			BEGIN
				SET @VbSumHead += ',dtl.GoodsID '
				SET @VbSumG += ',dtl.GoodsID '
				SET @VbBDHead += ',g.GoodsNo[Code2],g.GoodsName[Name2],g.Model[Model2],g.GoodsAbbName[GoodsAbbName2],g.Brand[Brand2],g.Spec[Spec2],pri.BarCode[BarCode2] '
				SET @VbSumBDHead += ',sd.GoodsID[ID2] '
				SET @VbSumBDG += ',sd.GoodsID '
				SET @VbBDJoin += '
	INNER JOIN BD_Goods g ON g.GoodsID=o.ID2 
	INNER JOIN BD_Goods_Price pri ON o.ID2 = pri.GoodsID AND pri.UnitID = 1 '
			END
			ELSE
			BEGIN
				IF @Goods<>0 
				BEGIN
					SET @VbSumHead += ',dtl.GoodsID '
					SET @VbSumG += ',dtl.GoodsID '
					SET @VbBDHead += ',g.GoodsNo[Code2],g.GoodsName[Name2],g.Model[Model2],g.GoodsAbbName[GoodsAbbName2],g.Brand[Brand2],g.Spec[Spec2],pri.BarCode[BarCode2] '
					SET @VbSumBDHead += ',sd.GoodsID[ID2] '
					SET @VbSumBDG += ',sd.GoodsID '
					SET @VbBDJoin += '
						INNER JOIN BD_Goods g ON g.GoodsID=o.ID2 
						INNER JOIN BD_Goods_Price pri ON o.ID2 = pri.GoodsID AND pri.UnitID = 1 '
				END
				IF @Ppt1<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt1ID '
					SET @VbBDHead += ',p1.Value[Ppt1Name2] '
					SET @VbSumBDHead += ',sd.Ppt1ID '
					IF @Goods<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt1ID ' 
						SET @VbSumBDG += ',sd.Ppt1ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += ',dtl.Ppt1ID '
						SET @VbSumBDG += ',sd.Ppt1ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt1 p1 ON p1.Ppt1ID=o.Ppt1ID '
				END
				IF @Ppt2<>0
				BEGIN
					SET @VbSumHead += ',dtl.Ppt2ID '
					SET @VbBDHead += ',p2.Value[Ppt2Name2] '
					SET @VbSumBDHead += ',sd.Ppt2ID '
					IF @Goods<>0 OR @Ppt1<>0 
					BEGIN 
						SET @VbSumG += ',dtl.Ppt2ID '
						SET @VbSumBDG += ',sd.Ppt2ID '
					END 
					ELSE
					BEGIN 
						SET @VbSumG += ',dtl.Ppt2ID '
						SET @VbSumBDG += ',sd.Ppt2ID '
					END
					SET @VbBDJoin += '
	LEFT JOIN BD_Goods_Ppt2 p2 ON p2.Ppt2ID=o.Ppt2ID '
				END
			END
			--自定义字段分类
			IF @Goods = 0
			BEGIN
				IF(@GoodsC1 <> 0)
				BEGIN
				   Set @VbSumHead += ' ,BGC.CustVal1 '
				   SET @VbSumBDG += ',sd.CustVal1 '				       
				   Set @VbSumBDHead += ',sd.CustVal1 '
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal1 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal1 '
				   Set @VbBDHead += ',o.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=o.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=o.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=o.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=o.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=o.CustVal1 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType1 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=o.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal2'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal2 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal2 '
				   Set @VbSumBDHead += ',sd.CustVal2 '
				   SET @VbSumBDG += ',sd.CustVal2 '				       
				   Set @VbBDHead += ',o.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal2 '		
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=o.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=o.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=o.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=o.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=o.CustVal2 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType2 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=o.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal3'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal3 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal3 '
				   Set @VbSumBDHead += ',sd.CustVal3 '
				   SET @VbSumBDG += ',sd.CustVal3 '				       
				   Set @VbBDHead += ',o.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal3 '		
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=o.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=o.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=o.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=o.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=o.CustVal3 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType3 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=o.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal4'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal4 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal4 '
				   Set @VbSumBDHead += ',sd.CustVal4 '
				   SET @VbSumBDG += ',sd.CustVal4 '				       
				   Set @VbBDHead += ',o.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal4 '		
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=o.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=o.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=o.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=o.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=o.CustVal4 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType4 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=o.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbSumHead += ',BGC.CustVal5'
				   IF(@VbSumG = '')
				       Set @VbSumG+= ' BGC.CustVal5 '
				   else
				       Set @VbSumG+= ' ,BGC.CustVal5 '
				   Set @VbSumBDHead += ',sd.CustVal5 '
				   SET @VbSumBDG += ',sd.CustVal5 '				       
				   Set @VbBDHead += ',o.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',o.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
					   SET @VbSumBDG += ',sd.CustVal5 '		
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=o.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=o.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=o.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=o.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=o.CustVal5 '	
					   END		        
				   END
				   ELSE IF( @GoodsCSourceType5 = 3)
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=o.CustVal5 '
				   END
				END
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @SumJoin += ' Inner Join BD_Goods_CustomVal BGC ON dtl.GoodsID = BGC.BaseID '
			END
			ELSE
			BEGIN
				IF(@GoodsC1 <> 0 OR @GoodsC2 <> 0 OR @GoodsC3 <> 0 OR @GoodsC4 <> 0 OR @GoodsC5 <> 0)
					Set @VbBDJoin += ' Inner Join BD_Goods_CustomVal BGC ON o.ID2 = BGC.BaseID '
				IF(@GoodsC1 <> 0)
				BEGIN			
				   Set @VbBDHead += ',BGC.CustVal1 [GoodsDataFile1] '
				   IF(@GoodsCSourceType1 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal1 [GoodsCName1] '
				   END	   
				   ELSE IF(@GoodsCSourceType1 = 2)
				   BEGIN
				       select @GoodsSource1 = Source from BD_Goods_CustomItem where CustItemID = 1
					   IF(@GoodsSource1 = 1)
					   BEGIN
						   Set @VbBDHead += ',g1.GoodsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g1 ON g1.GoodsID=BGC.CustVal1 '	
					   END	 
					   Else IF(@GoodsSource1 = 2)
					   BEGIN
						   Set @VbBDHead += ',B1.BTypeName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B1 ON B1.BTypeID=BGC.CustVal1 '	
					   END	
					   Else IF(@GoodsSource1 = 3)
					   BEGIN
						   Set @VbBDHead += ',W1.WhsName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W1 ON W1.WhsID=BGC.CustVal1 '	
					   END
					   Else IF(@GoodsSource1 = 4)
					   BEGIN
						   Set @VbBDHead += ',D1.DeptName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D1 ON D1.DeptID=BGC.CustVal1 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E1.ElyName [GoodsCName1] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E1 ON E1.ElyID=BGC.CustVal1 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC1.CustName [GoodsCName1] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC1 ON BC1.CustID=BGC.CustVal1 '
				   END
				END
				IF(@GoodsC2 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal2 [GoodsDataFile2] '
				   IF(@GoodsCSourceType2 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal2 [GoodsCName2] '
				   END	   
				   ELSE IF(@GoodsCSourceType2 = 2)
				   BEGIN
				       select @GoodsSource2 = Source from BD_Goods_CustomItem where CustItemID = 2
					   IF(@GoodsSource2 = 1)
					   BEGIN
						   Set @VbBDHead += ',g2.GoodsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g2 ON g2.GoodsID=BGC.CustVal2 '	
					   END	 
					   Else IF(@GoodsSource2 = 2)
					   BEGIN
						   Set @VbBDHead += ',B2.BTypeName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B2 ON B2.BTypeID=BGC.CustVal2 '	
					   END	
					   Else IF(@GoodsSource2 = 3)
					   BEGIN
						   Set @VbBDHead += ',W2.WhsName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W2 ON W2.WhsID=BGC.CustVal2 '	
					   END
					   Else IF(@GoodsSource2 = 4)
					   BEGIN
						   Set @VbBDHead += ',D2.DeptName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D2 ON D2.DeptID=BGC.CustVal2 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E2.ElyName [GoodsCName2] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E2 ON E2.ElyID=BGC.CustVal2 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC2.CustName [GoodsCName2] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC2 ON BC2.CustID=BGC.CustVal2 '
				   END
				END
				IF(@GoodsC3 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal3 [GoodsDataFile3] '
				   IF(@GoodsCSourceType3 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal3 [GoodsCName3] '
				   END	   
				   ELSE IF(@GoodsCSourceType3 = 2)
				   BEGIN
				       select @GoodsSource3 = Source from BD_Goods_CustomItem where CustItemID = 3
					   IF(@GoodsSource3 = 1)
					   BEGIN
						   Set @VbBDHead += ',g3.GoodsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g3 ON g3.GoodsID=BGC.CustVal3 '	
					   END	 
					   Else IF(@GoodsSource3 = 2)
					   BEGIN
						   Set @VbBDHead += ',B3.BTypeName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B3 ON B3.BTypeID=BGC.CustVal3 '	
					   END	
					   Else IF(@GoodsSource3 = 3)
					   BEGIN
						   Set @VbBDHead += ',W3.WhsName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W3 ON W3.WhsID=BGC.CustVal3 '	
					   END
					   Else IF(@GoodsSource3 = 4)
					   BEGIN
						   Set @VbBDHead += ',D3.DeptName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D3 ON D3.DeptID=BGC.CustVal3 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E3.ElyName [GoodsCName3] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E3 ON E3.ElyID=BGC.CustVal3 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC3.CustName [GoodsCName3] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC3 ON BC3.CustID=BGC.CustVal3 '
				   END
				END
				IF(@GoodsC4 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal4 [GoodsDataFile4] '
				   IF(@GoodsCSourceType4 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal4 [GoodsCName4] '
				   END	   
				   ELSE IF(@GoodsCSourceType4 = 2)
				   BEGIN
				       select @GoodsSource4 = Source from BD_Goods_CustomItem where CustItemID = 4
					   IF(@GoodsSource4 = 1)
					   BEGIN
						   Set @VbBDHead += ',g4.GoodsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g4 ON g4.GoodsID=BGC.CustVal4 '	
					   END	 
					   Else IF(@GoodsSource4 = 2)
					   BEGIN
						   Set @VbBDHead += ',B4.BTypeName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B4 ON B4.BTypeID=BGC.CustVal4 '	
					   END	
					   Else IF(@GoodsSource4 = 3)
					   BEGIN
						   Set @VbBDHead += ',W4.WhsName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W4 ON W4.WhsID=BGC.CustVal4 '	
					   END
					   Else IF(@GoodsSource4 = 4)
					   BEGIN
						   Set @VbBDHead += ',D4.DeptName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D4 ON D4.DeptID=BGC.CustVal4 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E4.ElyName [GoodsCName4] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E4 ON E4.ElyID=BGC.CustVal4 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC4.CustName [GoodsCName4] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC4 ON BC4.CustID=BGC.CustVal4 '
				   END
				END
				IF(@GoodsC5 <> 0)
				BEGIN
				   Set @VbBDHead += ',BGC.CustVal5 [GoodsDataFile5] '
				   IF(@GoodsCSourceType5 = 1)
				   BEGIN
				       Set @VbBDHead += ',BGC.CustVal5 [GoodsCName5] '
				   END	   
				   ELSE IF(@GoodsCSourceType5 = 2)
				   BEGIN
				       select @GoodsSource5 = Source from BD_Goods_CustomItem where CustItemID = 5
					   IF(@GoodsSource5 = 1)
					   BEGIN
						   Set @VbBDHead += ',g5.GoodsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Goods g5 ON g5.GoodsID=BGC.CustVal5 '	
					   END	 
					   Else IF(@GoodsSource5 = 2)
					   BEGIN
						   Set @VbBDHead += ',B5.BTypeName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Btype B5 ON B5.BTypeID=BGC.CustVal5 '	
					   END	
					   Else IF(@GoodsSource5 = 3)
					   BEGIN
						   Set @VbBDHead += ',W5.WhsName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Whs W5 ON W5.WhsID=BGC.CustVal5 '	
					   END
					   Else IF(@GoodsSource5 = 4)
					   BEGIN
						   Set @VbBDHead += ',D5.DeptName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Dept D5 ON D5.DeptID=BGC.CustVal5 '	
					   END	
					   Else 
					   BEGIN
						   Set @VbBDHead += ',E5.ElyName [GoodsCName5] '
						   SET @VbBDJoin += ' left JOIN BD_Employee E5 ON E5.ElyID=BGC.CustVal5 '	
					   END		        
				   END
				   ELSE
				   BEGIN
				       Set @VbBDHead += ',BC5.CustName [GoodsCName5] '
					   SET @VbBDJoin += ' left JOIN BD_Custom BC5 ON BC5.CustID=BGC.CustVal5 '
				   END
				END				
			END
		END
	END
	IF @CollectType2 = 2
	BEGIN
	BEGIN
		SET @VbSumHead += ',p.VipCardID '
		SET @VbSumG += ',p.VipCardID '
		IF @Layer2=1
		BEGIN
			SET @VbBDHead += ',v.VipCardNo[Code2],v.VipCardID '
			SET @VbSumBDHead += ',sd.VipCardID[ID2] '
			SET @VbSumBDG += ',sd.VipCardID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ' ,vt.TypeName[Code2]'
			SET @VbSumBDHead += ',vt.VipCardTypeID[ID2]'
			SET @VbSumBDG += ',vt.VipCardTypeID '
		END
		IF @Layer2=1
			SET @VbBDJoin += '
		INNER JOIN VS_VipCard v ON v.VipCardID=o.ID2'
		ELSE
		BEGIN
			SET @VbBDJoin += '
			INNER JOIN VS_VipCardType vt ON vt.VipCardTypeID=o.ID2'
			SET @CFBDJoin += '
			INNER JOIN VS_VipCard v ON v.VipCardID=sd.VipCardID
			INNER JOIN VS_VipCardType vt ON v.VipCardTypeID=vt.VipCardTypeID '
		END
	END
	END
	IF @CollectType2 = 3
	BEGIN
		SET @VbSumHead += ',dtl.WhsID '
		SET @VbSumG += ',dtl.WhsID '
		IF @Layer2 <> 6 --汇总层级:仓库分类1-5
		BEGIN
			SET @VbBDHead += ',wt.TypeCode[Code2],wt.TypeName[Name2] '
			SET @VbSumBDHead += ',kbs.BaseID[ID2] '
			SET @VbSumBDG += ',kbs.BaseID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs_Type wt ON wt.WhsTypeID=o.ID2 '
			SET @CFBDJoin += '
		INNER JOIN ('+@bw2+'
		) kbs ON kbs.WhsID = sd.WhsID '
		END
		ELSE
		BEGIN
			SET @VbBDHead += ',w.WhsNO[Code2],w.WhsName[Name2] '
			SET @VbSumBDHead += ',sd.WhsID[ID2] '
			SET @VbSumBDG += ',sd.WhsID '
			SET @VbBDJoin += '
	INNER JOIN BD_Whs w ON w.WhsID=o.ID2 '
		END
	END
	IF @CollectType2 = 5
	BEGIN
		SET @VbSumHead += ',p.DeptID '
		SET @VbSumG += ',p.DeptID '
		SET @VbBDHead += ',d.DeptCode[Code2],d.DeptName[Name2] '
		SET @VbBDJoin += '
	INNER JOIN BD_Dept d ON d.DeptID=o.ID2 '
		IF @Layer2<>5 
		BEGIN
			SET @VbSumBDHead += ',dbs.BaseID[ID2] '
			SET @VbSumBDG += ',dbs.BaseID '
			SET @CFBDJoin += '
		INNER JOIN ('+@bd2+'
		) dbs ON dbs.DeptID = sd.DeptID '
		END
		ELSE
		BEGIN
			SET @VbSumBDHead += ',sd.DeptID[ID2] '
			SET @VbSumBDG += ',sd.DeptID '
		END
	END
	IF @CollectType2 = 6
	BEGIN
		SET @VbSumHead += ',p.ElyID '
		SET @VbSumG += ',p.ElyID '
		SET @VbBDHead += ',e.ElyCode[Code2],e.ElyName[Name2] '
		SET @VbSumBDHead += ',sd.ElyID[ID2] '
		SET @VbSumBDG += ',sd.ElyID '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee e ON e.ElyID=o.ID2 '
	END
	IF @CollectType2 = 7
	BEGIN
		SET @VbSumHead += ',p.Creator '
		SET @VbSumG += ',p.Creator '
		SET @VbBDHead += ',pe.ElyCode[Code2],pe.ElyName[Name2] '
		SET @VbSumBDHead += ',sd.Creator[ID2] '
		SET @VbSumBDG += ',sd.Creator '
		SET @VbBDJoin += '
	INNER JOIN BD_Employee pe ON pe.ElyID=o.ID2 '
	END
END
-----汇总层级二-----END
declare @str varchar(10)
select @str = SUBSTRING(@VbSumG,1,1)
if(@str = ',')
	Select @VbSumG = SUBSTRING(@VbSumG,2,len(@VbSumG))
IF @VbSumG <> ''
	SET @VbSumG = '
	GROUP BY ' + @VbSumG
select @str = SUBSTRING(@VbSumBDG,1,1)
if(@str = ',')
	Select @VbSumBDG = SUBSTRING(@VbSumBDG,2,len(@VbSumBDG))
IF @VbSumBDG <> ''
	SET @VbSumBDG = '
		GROUP BY ' + @VbSumBDG

--排序BEGIN
SET @SqlOrder=''
--select @CollectType1,@OrderType1,@CollectType2,@OrderType2
IF @OrderType1<>0
BEGIN
	IF (@CollectType1 = 1 AND @OrderType1 IN (1,3)) OR (@CollectType1 = 2 AND @OrderType1 IN (5,6)) OR (@CollectType1 = 3 AND @OrderType1 IN (9,11)) OR (@CollectType1 = 4 AND @OrderType1 = 13) OR (@CollectType1 = 5 AND @OrderType1 = 15) OR (@CollectType1 = 6 AND @OrderType1 = 17) OR (@CollectType1 = 7 AND @OrderType1 = 29)
		SET @SqlOrder += 'Code1'
	IF (@CollectType1 = 1 AND @OrderType1 IN (2,4)) OR (@CollectType1 = 3 AND @OrderType1 IN (10,12)) OR (@CollectType1 = 4 AND @OrderType1 = 14) OR (@CollectType1 = 5 AND @OrderType1 = 16) OR (@CollectType1 = 6 AND @OrderType1 = 18) OR (@CollectType1 = 7 AND @OrderType1 = 30)
		SET @SqlOrder += 'Name1'
	IF (@CollectType2 = 1 AND @OrderType1 IN (1,3)) OR (@CollectType2 = 2 AND @OrderType1 IN (5,6)) OR (@CollectType2 = 3 AND @OrderType1 IN (9,11)) OR (@CollectType2 = 4 AND @OrderType1 = 13) OR (@CollectType2 = 5 AND @OrderType1 = 15) OR (@CollectType2 = 6 AND @OrderType1 = 17) OR (@CollectType2 = 7 AND @OrderType1 = 29)
		SET @SqlOrder += 'Code2'
	IF (@CollectType2 = 1 AND @OrderType1 IN (2,4)) OR (@CollectType2 = 3 AND @OrderType1 IN (10,12)) OR (@CollectType2 = 4 AND @OrderType1 = 14) OR (@CollectType2 = 5 AND @OrderType1 = 16) OR (@CollectType2 = 6 AND @OrderType1 = 18) OR (@CollectType2 = 7 AND @OrderType1 = 30)
		SET @SqlOrder += 'Name2'
	IF @OrderType1=19 SET @SqlOrder+='BSQty' IF @OrderType1=20 SET @SqlOrder+='AVGPrice' IF @OrderType1=21 SET @SqlOrder+='SaleTotal' IF @OrderType1=22 SET @SqlOrder+='AVGCostPrice'
	IF @OrderType1=23 SET @SqlOrder+='CostTotal' IF @OrderType1=24 SET @SqlOrder+='Profit' IF @OrderType1=25 SET @SqlOrder+='ProfitRate' IF @OrderType1=26 SET @SqlOrder+='GiftQty'
	IF @CollectType1=1 AND @OrderType1=27 SET @SqlOrder+='Ppt1Name1' IF @CollectType1=1 AND @OrderType1=28 SET @SqlOrder+='Ppt2Name1'
	IF @CollectType2=1 AND @OrderType1=27 SET @SqlOrder+='Ppt1Name2' IF @CollectType2=1 AND @OrderType1=28 SET @SqlOrder+='Ppt2Name2'
	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=31 SET @SqlOrder+='GoodsCName1'	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=32 SET @SqlOrder+='GoodsCName2'
	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=33 SET @SqlOrder+='GoodsCName3'  IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=34 SET @SqlOrder+='GoodsCName4'
	IF (@CollectType1=1 or @CollectType2 = 1) AND @OrderType1=35 SET @SqlOrder+='GoodsCName5'
	IF @OrderSeq1=2 SET @SqlOrder+= ' DESC'
END
IF @OrderType2<>0
BEGIN
	IF (@CollectType1 = 1 AND @OrderType2 IN (1,3)) OR (@CollectType1 = 2 AND @OrderType2 IN (5,6)) OR (@CollectType1 = 3 AND @OrderType2 IN (9,11)) OR (@CollectType1 = 4 AND @OrderType2 = 13) OR (@CollectType1 = 5 AND @OrderType2 = 15) OR (@CollectType1 = 6 AND @OrderType2 = 17) OR (@CollectType1 = 7 AND @OrderType2 = 29)
		SET @SqlOrder += ',Code1'
	IF (@CollectType1 = 1 AND @OrderType2 IN (2,4)) OR (@CollectType1 = 3 AND @OrderType2 IN (10,12)) OR (@CollectType1 = 4 AND @OrderType2 = 14) OR (@CollectType1 = 5 AND @OrderType2 = 16) OR (@CollectType1 = 6 AND @OrderType2 = 18) OR (@CollectType1 = 7 AND @OrderType2 = 30)
		SET @SqlOrder += ',Name1'
	IF (@CollectType2 = 1 AND @OrderType2 IN (1,3)) OR (@CollectType2 = 2 AND @OrderType2 IN (5,6)) OR (@CollectType2 = 3 AND @OrderType2 IN (9,11)) OR (@CollectType2 = 4 AND @OrderType2 = 13) OR (@CollectType2 = 5 AND @OrderType2 = 15) OR (@CollectType2 = 6 AND @OrderType2 = 17) OR (@CollectType2 = 7 AND @OrderType2 = 29)
		SET @SqlOrder += ',Code2'
	IF (@CollectType2 = 1 AND @OrderType2 IN (2,4)) OR (@CollectType2 = 3 AND @OrderType2 IN (10,12)) OR (@CollectType2 = 4 AND @OrderType2 = 14) OR (@CollectType2 = 5 AND @OrderType2 = 16) OR (@CollectType2 = 6 AND @OrderType2 = 18) OR (@CollectType2 = 7 AND @OrderType2 = 30)
		SET @SqlOrder += ',Name2'
	IF @OrderType2=19 SET @SqlOrder+=',BSQty' IF @OrderType2=20 SET @SqlOrder+=',AVGPrice' IF @OrderType2=21 SET @SqlOrder+=',SaleTotal' IF @OrderType2=22 SET @SqlOrder+=',AVGCostPrice'
	IF @OrderType2=23 SET @SqlOrder+=',CostTotal' IF @OrderType2=24 SET @SqlOrder+=',Profit' IF @OrderType2=25 SET @SqlOrder+=',ProfitRate' IF @OrderType2=26 SET @SqlOrder+=',GiftQty'
	IF @CollectType1=1 AND @OrderType2=27 SET @SqlOrder+=',Ppt1Name1' IF @CollectType1=1 AND @OrderType2=28 SET @SqlOrder+=',Ppt2Name1'
	IF @CollectType2=1 AND @OrderType2=27 SET @SqlOrder+=',Ppt1Name2' IF @CollectType2=1 AND @OrderType2=28 SET @SqlOrder+=',Ppt2Name2'
	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=31 SET @SqlOrder+=',GoodsCName1'	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=32 SET @SqlOrder+=',GoodsCName2'
	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=33 SET @SqlOrder+=',GoodsCName3'  IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=34 SET @SqlOrder+=',GoodsCName4'
	IF (@CollectType1=1 or @CollectType2=1 ) AND @OrderType2=35 SET @SqlOrder+=',GoodsCName5'
	IF @OrderSeq2=2 SET @SqlOrder+= ' DESC'
END
IF @SqlOrder='' SET @SqlOrder='BSQty'
--排序END

SET @SumData=';WITH SumData AS('

SET @SumHead='SUM(dtl.BSQty)[BSQtyST]
	,SUM(dtl.TaxTotal)[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)[GiftQtyST] 
	,0 ExchangeQty '
	+CASE @Privilege WHEN 0 THEN '
	,0 Privilege
	,SUM(dtl.TaxTotal) AfterPrivilege'
	ELSE '
	,MAX(Privilege) Privilege
	,SUM(dtl.TaxTotal)-MAX(Privilege) AfterPrivilege' END
SET @SumHeadFH='SUM(dtl.BSQty)*-1[BSQtyST]
	,SUM(dtl.TaxTotal)*-1[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)*-1[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)*-1[GiftQtyST]
	,0 ExchangeQty'
	+CASE @Privilege WHEN 0 THEN '
	,0 Privilege
	,-SUM(dtl.TaxTotal) AfterPrivilege '
	ELSE '
	,MAX(Privilege)*-1 Privilege
	,MAX(Privilege)-SUM(dtl.TaxTotal) AfterPrivilege ' END
	
SET @SumHeadEX='SUM(dtl.BSQty) [BSQtyST]
	,0 [SaleTotalST]
	,SUM(dtl.GoodsCostTotal) [CostTotalST]
	,0 [GiftQtyST] 
	,SUM(dtl.BSQty) ExchangeQty
	,0 Privilege
	,0 AfterPrivilege '


SET @Sql_Exchange='
	SELECT ' + @SumHeadEX + @VbSumHead + '
	FROM PD_InoutWhsBill p 
	INNER JOIN PD_InoutWhsDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam+CASE WHEN @GiftState<>1 THEN '' ELSE ' AND 1<>1' END + @VbSumG
SET @Sql_Exchange_His='
	SELECT ' + @SumHeadEX + @VbSumHead + '
	FROM PD_InoutWhsBill_His p 
	INNER JOIN PD_InoutWhsDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam+CASE WHEN @GiftState<>1 THEN '' ELSE ' AND 1<>1' END  + @VbSumG

IF @GiftState<>9 
	SET @SumParam += 'AND Gift=@GiftState '	

	
IF NOT((@SaleBillOut<>0 OR @ExchangeBill<>0) AND @SaleBillIn<>0)
	SET @SumHeadFH = @SumHead
	
SET @Sql_PPB='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill p 
	INNER JOIN PD_SellDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PPB_His='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill_His p 
	INNER JOIN PD_SellDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PRB='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill p 
	INNER JOIN PD_SellRetDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PRB_His='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill_His p 
	INNER JOIN PD_SellRetDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG



IF @SaleBillOut<>0
BEGIN
	SET @SumData+=@Sql_PPB+'
	UNION ALL '
END
IF @SaleBillIn<>0
BEGIN
	SET @SumData+=@Sql_PRB++'
	UNION ALL '
END
IF @ExchangeBill<>0
BEGIN
	SET @SumData+=@Sql_Exchange+'
	UNION ALL '
END

IF @IsHistory = 1
BEGIN
	IF @SaleBillOut<>0
	BEGIN
		SET @SumData+=@Sql_PRB_His+'
		UNION ALL '
	END
	IF @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PPB_His+'
		UNION ALL '
	END
	IF @ExchangeBill<>0
	BEGIN
		SET @SumData+=@Sql_Exchange_His+'
		UNION ALL '
	END
END
SET @SumData=SUBSTRING(@SumData,0,LEN(@SumData)-11)
SET @SumData+=')'
SET @BillData = '
,BillData AS( 
	SELECT o.*'
	
SET @BDHead='SUM(sd.BSQtyST)[BSQty]
		,SUM(sd.SaleTotalST)[SaleTotal]
		,SUM(sd.CostTotalST)[CostTotal]
		,SUM(sd.GiftQtyST)[GiftQty]
		,SUM(sd.ExchangeQty)[ExchangeQty]
		,SUM(sd.Privilege)[PrivilegeTotal]
		,SUM(sd.AfterPrivilege)[AfterPrivilege] '

SET @AVGPrice = '
	,CASE WHEN o.BSQty=0 THEN NULL ELSE ABS(CAST( CAST(o.SaleTotal AS FLOAT)/o.BSQty AS DECIMAL(20,8) )) END [AVGPrice] '
SET @AVGCostPrice = '
	,CASE WHEN o.BSQty=0  THEN NULL ELSE  ABS(CAST( CAST(o.CostTotal AS FLOAT)/o.BSQty AS DECIMAL(20,8) )) END[AVGCostPrice] '
SET	@Profit ='
	,o.AfterPrivilege-o.CostTotal [Profit] '
SET @ProfitRate = '
	,CASE WHEN o.AfterPrivilege=0 THEN NULL ELSE CAST( ((o.AfterPrivilege-o.CostTotal)/o.AfterPrivilege)*100 AS DECIMAL(20,2) ) END[ProfitRate] '
IF @OrderType1 = 20 OR @OrderType2 = 20 SET @VbBDHead += @AVGPrice
IF @OrderType1 = 22 OR @OrderType2 = 22 SET @VbBDHead += @AVGCostPrice
IF @OrderType1 = 24 OR @OrderType2 = 24 SET @VbBDHead += @Profit
IF @OrderType1 = 25 OR @OrderType2 = 25 SET @VbBDHead += @ProfitRate
SET @BillData += @VbBDHead + '
	FROM ( 
		SELECT ' + @BDHead + @VbSumBDHead + '
		FROM SumData sd ' + @CFBDJoin + @VbSumBDG + '
	) o ' + @VbBDJoin + '
)'

SET @Sql += 'SET NOCOUNT ON;
' + @SumData + @BillData + '
,PageData as(
	SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ' + @SqlOrder + ') AS ROWID,COUNT(1) OVER() AS ''ROWCOUNT'',* FROM BillData) AS B
	WHERE ROWID>(@pageNo-1)*@pageSize 
	AND ROWID<=@pageNo*@pageSize 
)

SELECT o.* '
IF @OrderType1 <> 20 AND @OrderType2 <> 20 SET @Sql += @AVGPrice
IF @OrderType1 <> 22 AND @OrderType2 <> 22 SET @Sql += @AVGCostPrice
IF @OrderType1 <> 24 AND @OrderType2 <> 24 SET @Sql += @Profit
IF @OrderType1 <> 25 AND @OrderType2 <> 25 SET @Sql += @ProfitRate
IF (@CollectType1=1 AND @Layer1=6) OR (@CollectType2=1 AND @Layer2=6)
	IF @Goods<>0 OR (@Ppt1=0 AND @Ppt2=0 And @GoodsC1=0 And @GoodsC2=0 And @GoodsC3=0 And @GoodsC4=0 And @GoodsC5=0 )
		SET @Sql += '
	,gp1.Unit[Unit]
	,gp1.Unit[Unit1],gp2.Unit[Unit2],gp3.Unit[Unit3]
	,gp1.Convfactor[Convfactor1],ISNULL(gp2.Convfactor,1)[Convfactor2],ISNULL(gp3.Convfactor,1)[Convfactor3] '
IF @CollectType1=2 AND @Layer1=1 OR @CollectType2=2 AND @Layer2=1 
SET @Sql += ',Vt.TypeName,v.VipName,V.CardHolder
	,CASE WHEN v.EndDate<DATEADD(day,-1,GETDATE())THEN ''已过期'' WHEN STATUS=1 THEN ''使用中'' WHEN STATUS=2 THEN ''已停用'' ELSE ''已挂失'' END AS CardStatus
	,v.Address,v.IDNO,v.Sex,v.Birthday,v.Email,v.Tel '
SET @Sql += '
	FROM PageData o '
IF @CollectType1=1 AND @Layer1=6
	IF @Goods<>0 OR (@Ppt1=0 AND @Ppt2=0 And @GoodsC1=0 And @GoodsC2=0 And @GoodsC3=0 And @GoodsC4=0 And @GoodsC5=0 )
		SET @Sql += '
	LEFT JOIN BD_Goods_Price gp1 ON gp1.GoodsID=o.ID1 AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON gp2.GoodsID=o.ID1 AND gp2.UnitID=2 
	LEFT JOIN BD_Goods_Price gp3 ON gp3.GoodsID=o.ID1 AND gp3.UnitID=3 '
IF @CollectType2=1 AND @Layer2=6
	IF @Goods<>0 OR (@Ppt1=0 AND @Ppt2=0 And @GoodsC1=0 And @GoodsC2=0 And @GoodsC3=0 And @GoodsC4=0 And @GoodsC5=0 )
		SET @Sql += '
	LEFT JOIN BD_Goods_Price gp1 ON gp1.GoodsID=o.ID2 AND gp1.UnitID=1 
	LEFT JOIN BD_Goods_Price gp2 ON gp2.GoodsID=o.ID2 AND gp2.UnitID=2 
	LEFT JOIN BD_Goods_Price gp3 ON gp3.GoodsID=o.ID2 AND gp3.UnitID=3 '
IF @CollectType1=2 AND @Layer1=1 OR @CollectType2=2 AND @Layer2=1
SET @Sql += '
	INNER JOIN Vs_VipCard v ON v.VipCardID=o.VipCardID
	INNER JOIN Vs_VipCardType vt ON vt.VipCardTypeID=v.VipCardTypeID '
SET @Sql += '
	ORDER BY ROWID '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
--print @Sql
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END 

EXEC SP_EXECUTESQL @Sql,N'@pageNo INT,@pageSize INT,@BillDateType INT,@BillStartDate DATETIME,@BillEndDate DATETIME
,@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@CreatorID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000)
,@GoodsNo VARCHAR(20),@GoodsName VARCHAR(50),@GiftState INT
,@CollectType1 INT,@Layer1 INT,@CollectType2 INT,@Layer2 INT,@OperatorID INT, @BarCode VARCHAR(100), @BarCodeMatch INT
,@VipCardNo VARCHAR(30), @VipCardMatch INT,@VipCardTypeID VARCHAR(1000),@VipName VARCHAR(50), @VipNameMatch INT,@CardHolder VARCHAR(50)
,@CardHolderMatch INT,  @Tel VARCHAR(20),   @TelMatch INT '
,@pageNo,@pageSize,@BillDateType,@BillStartDate,@BillEndDate
,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@GoodsID,@GoodsNo,@GoodsName,@GiftState
,@CollectType1,@Layer1,@CollectType2,@Layer2,@OperatorID, @BarCode, @BarCodeMatch
,@VipCardNo,@VipCardMatch ,@VipCardTypeID,@VipName ,@VipNameMatch,@CardHolder 
,@CardHolderMatch ,@Tel ,@TelMatch   
END


GO






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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：单据往来对账查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_QueryWLDZSum]
(
	@BeginDate DATE,
	@EndDate DATE,
	@BTypeID Int=0,
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@ShowDZ INT=0,
	@RedFlag Int = 0,	
	@isHistory INT=0				--是否包含历史数据
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;

IF (@BTypeID<=0) 
BEGIN
	 RAISERROR ('请选择“往来单位”进行查询！' , 16, 1) WITH NOWAIT
      RETURN 1
END

DECLARE @sql nvarchar(MAX)='',@SqlSell VARCHAR(max)='',@sqlHis nvarchar(MAX)='',@SqlSellHis VARCHAR(max)='',@RowCount int=0,@SqlTable VARCHAR(max)='',@SqlGoods nvarchar(max),@SqlRed varchar(100)='',
		@SqlCreateTable varchar(max)='',@SqlBaseTable varchar(max)='',@sqlListTable varchar(max)='',@SqlDZ varchar(100)='',@SqlSellLogistHis VARCHAR(max)=''
		,@SqlSellLogist VARCHAR(max)='',@SqlBuyLogistHis VARCHAR(max)='',@SqlBuyLogist VARCHAR(max)='',@SqlBuy VARCHAR(max)='',@SqlBuyHis VARCHAR(max)=''
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlBaseTable+=' INNER JOIN @DType D ON I.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlBaseTable+=' INNER JOIN @EType E ON I.ElyID=E.TypeID ' 
END	
if(@RedFlag = 0) 
	Select @SqlRed = ' And Red = 0 '
if @isHistory = 1
	Set @sqlListTable += ' (select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,JTotal,DTotal,IsReconciled,[Order],Red from PD_ListTable
						union all
						select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,DeptID,ElyID,JTotal,DTotal,IsReconciled,[Order],Red from PD_ListTable_His)'
else
	Set @sqlListTable += 'PD_ListTable'
SELECT @sql+='
UNION ALL 
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,BTypeID ,I.BillNo'
	+' FROM '+BillTable+' I ' + @SqlBaseTable 
	+' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
FROM PD_BillType b
WHERE CanPost=1 And BillTypeID in (102,401,402,404,405,501,502,503,504)

SELECT @SqlBuy+='
UNION ALL 
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
		BTypeID,I.BillNo,I.Freight,I.Red
	 FROM '+BillTable+' I ' + @SqlBaseTable 
	+' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
FROM PD_BillType b
WHERE CanPost=1 And BillTypeID = 101
SELECT @sqlSell+='
UNION ALL 
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,
		BTypeID,I.BillNo
	 FROM '+BillTable+' I ' + @SqlBaseTable 
	+' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
FROM PD_BillType b
WHERE CanPost=1 And BillTypeID in (201,202)
Select @SqlSellLogist += '
SELECT  201 AS BillTypeID,LogistBTypeID as BTypeID,I.BillNo 
		FROM PD_SellBill I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID ' 
Select @SqlBuyLogist += '
SELECT  101 AS BillTypeID,LogistBTypeID as BTypeID,I.BillNo,I.Freight,I.Red 
		FROM PD_PchBill I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID ' 

IF @isHistory=1
Begin
	SELECT @sqlHis+='
UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,BTypeID ,I.BillNo'
		+' FROM '+BillTable+'_His I ' + @SqlBaseTable 
		+' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID	' 
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	FROM PD_BillType b
	WHERE CanPost=1 And BillTypeID in (102,401,402,404,405,501,502,503,504)
SELECT @SqlBuyHis+='
UNION ALL 
SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,BTypeID,I.BillNo,I.Freight,I.Red
	 FROM '+BillTable+'_His I ' + @SqlBaseTable 
	+' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
		+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
FROM PD_BillType b
WHERE CanPost=1 And BillTypeID = 101
	SELECT @SqlSellHis+='
UNION ALL 
	SELECT  '+Cast(BillTypeID AS varchar)+' AS BillTypeID,BTypeID,I.BillNo
		 FROM '+BillTable+'_His I ' + @SqlBaseTable 
		+' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And BTypeID = @BTypeID ' 
			+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND I.BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	FROM PD_BillType b
	WHERE CanPost=1 And BillTypeID in (201,202)
	Select @SqlSellLogistHis += '
	SELECT  201 AS BillTypeID,LogistBTypeID as BTypeID,I.BillNo 
			FROM PD_SellBill_His I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID ' 
	Select @SqlBuyLogistHis += '
	SELECT  101 AS BillTypeID,LogistBTypeID as BTypeID,I.BillNo,I.Freight,I.Red 
		FROM PD_PchBill_His I '+ @SqlBaseTable +' WHERE BillDate BETWEEN @BeginDate AND @EndDate And IsDraft=0 '+@SqlRed+' And LogistBTypeID = @BTypeID And LogistBTypeID<>BTypeID ' 

End
		
SELECT @sql=@SqlCreateTable+@SqlTable + '
;WITH Bill AS 
('	+STUFF(@sql,1,12,'')+'
),BuyBill as
(' +STUFF(@SqlBuy,1,12,'')+
'),BuyLogistBill as
(' + @SqlBuyLogist +'
),SellBill as
(' +STUFF(@sqlSell,1,12,'')+
'),SellLogistBill as
(' + @SqlSellLogist +'
),BackTotal as
(
	select BillNo,BillTypeID,35 as FinanceID,DTotal ,Jtotal from pd_listtable where FinanceID = 20 
)'
IF @isHistory=1
Begin
	Select @sql += ',BillHis AS 
	('	+STUFF(@sqlHis,1,12,'')+'
	),BuyBillHis as
	(' +STUFF(@SqlBuyHis,1,12,'')+
	'),BuyLogistBillHis as
	(' + @SqlBuyLogistHis +
	'),SellBillHis as
	(' +STUFF(@SqlSellHis,1,12,'')+
	'),SellLogistBillHis as
	(' + @SqlSellLogistHis +
	'),BackTotalHis as
	(
		select BillNo,BillTypeID,35 as FinanceID,DTotal ,Jtotal from pd_listtable_His where FinanceID = 20 
	)'
End
SELECT @sql +=',AllData as
( Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal+isnull(G.DTotal,0) as DTotal,L.JTotal +isnull(G.jtotal,0) as JTotal
	from Bill A Left Join pd_listtable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo
		left join BackTotal G on L.FinanceID=G.FinanceID and L.BillNo = G.BillNo and L.BillTypeID = G.BillTypeID
	where L.FinanceID not in(33,37,20)
	Union ALL
  Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,case when FinanceID = 35 then (L.JTotal-(case when A.Red = 2 then A.Freight*-1 else A.Freight end )) else L.JTotal end as JTotal
	from BuyBill A Left Join pd_listtable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,20)
	Union All
	Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,L.JTotal
	from BuyLogistBill A Left Join pd_listtable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37)
	Union All
	Select A.BillTypeID,A.BillNO,A.BtypeID,0 as DTotal ,case When A.red = 2 then Freight*-1 else Freight end as JTotal
	from BuyLogistBill A
	Union ALL
  Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,L.JTotal
	from sellbill A Left Join pd_listtable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37,11,35)
	Union All
	Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,L.JTotal
	from SellLogistBill A Left Join pd_listtable L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
	where FinanceID not in(33,37)
	'
	IF @isHistory=1
	Begin
		SELECT @sql += '
		Union ALL
		 Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal+isnull(G.DTotal,0) as DTotal,L.JTotal +isnull(G.jtotal,0) as JTotal
			from BillHis A Left Join pd_listtable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo
				left join BackTotalHis G on L.FinanceID=G.FinanceID and L.BillNo = G.BillNo and L.BillTypeID = G.BillTypeID
			where L.FinanceID not in(33,37,20)
		Union ALL
		  Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,case when FinanceID = 35 then (L.JTotal-(case when A.Red = 2 then A.Freight*-1 else A.Freight end )) else L.JTotal end as JTotal
			from BuyBillHis A Left Join pd_listtable_his L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
			where FinanceID not in(33,37,20)
		Union All
			Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,L.JTotal
			from BuyLogistBillHis A Left Join pd_listtable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
			where FinanceID not in(33,37)
		Union All
			Select A.BillTypeID,A.BillNO,A.BtypeID,0 as DTotal ,case When A.red = 2 then Freight*-1 else Freight end as JTotal
			from BuyLogistBillHis A
		Union ALL
		  Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,L.JTotal
			from sellbillHis A Left Join pd_listtable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
			where FinanceID not in(33,37,11,35) 
		Union ALL
		  Select A.BillTypeID,L.BillNO,A.BtypeID,L.DTotal ,L.JTotal
			from SellLogistBillHis A Left Join pd_listtable_His L ON A.BillTypeID = L.BillTypeID And A.BillNO=L.BillNo And A.BtypeID=L.BtypeID
			where FinanceID not in(33,37) '
	End
SELECT @sql += ')
Select Sum(JTotal) as JTotal,SUm(DTotal) as DTotal from AllData

'
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

------------------添加参数---------------------------------------
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END

exec sp_executesql @sql,N'@BeginDate Date,@EndDate Date,@BTypeID VarChar(MAX),@DeptID VarChar(MAX),@ElyID VarChar(MAX),@RowCount Int',@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID,@RowCount

GO



/****** Object:  StoredProcedure [UP_PD_RGoodSDBBData]    Script Date: 10/13/2014 09:50:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_RGoodSDBBData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_RGoodSDBBData]
GO

/****** Object:  StoredProcedure [UP_PD_RGoodSDBBData]    Script Date: 2014-07-22 14:54:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-09-30
	描述：存货明细账_合计：此前存库数量、金额
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_RGoodSDBBData]
(
	@BillStartDate DATETIME,		--单据开始日期
	@WhsTypeID INT=0,				--仓库分类
	@WhsID VARCHAR(100) = '',		--仓库
	@GoodsTypeID INT=0,				--商品分类
	@GoodsID INT=0,					--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',	--商品名称
	@SpecMatch INT=0,				--规格配置模式:0=包含,1=等于
	@Spec VARCHAR(100) = '',		--规格
	@ModelMatch INT=0,				--型号配置模式:0=包含,1=等于
	@Model VARCHAR(100) = '',		--型号
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,			--品牌匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@ClickFlag INT=0				--是否跳转
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Sql NVARCHAR(MAX)=''
		,@SqlW NVARCHAR(MAX)='',@SqlG NVARCHAR(MAX)='',@wLimitJion NVARCHAR(300)='',@DISTINCT VARCHAR(10)='',@SqlGoodsParam NVARCHAR(MAX)='' --with 表达式  仓库和商品ID
		,@SqlOne NVARCHAR(MAX),@SqlOneJoinW NVARCHAR(300)='',@SqlOneJoinG NVARCHAR(300)='',@SqlOneParam VARCHAR(200)=''	--第一部分sql
		,@SqlTwoParam VARCHAR(200)='',@SqlTwoParamDtl VARCHAR(200)='',@SqlTwoParamDate VARCHAR(100)='',@SqlTwoJoinW NVARCHAR(300)='',@SqlTwoJoinWDtl NVARCHAR(300)='',@SqlTwoJoinWIn NVARCHAR(300)='',@SqlTwoJoinWOut NVARCHAR(300)='',@SqlTwoJoinG NVARCHAR(300)=''	--第二部分sql
		,@DateFlag INT,@Negative NVARCHAR(10)=''
		,@StartD DATETIME,@EndD DATETIME,@DayStart INT,@DayEnd INT
		,@KtypeLimit INT=0 
--在月结存里面找出时间点的最近的两个日期--即左边的最大日期和右边的最小日期
SELECT @StartD=MAX(mp.EndDate) FROM SS_MonthProc mp INNER JOIN SS_MonthStock b ON b.Period = mp.Period WHERE EndDate < @BillStartDate
SELECT @EndD=MIN(mp.EndDate) FROM SS_MonthProc mp INNER JOIN SS_MonthStock b ON b.Period = mp.Period WHERE EndDate > @BillStartDate
--计算离左边的天数和右边的天数
SELECT @DayStart=DATEDIFF(DAY,MAX(mp.EndDate), @BillStartDate) FROM SS_MonthProc mp INNER JOIN SS_MonthStock b ON b.Period = mp.Period WHERE EndDate < @BillStartDate
SELECT @DayEnd=DATEDIFF(DAY,@BillStartDate, MIN(mp.EndDate)) FROM SS_MonthProc mp INNER JOIN SS_MonthStock b ON b.Period = mp.Period WHERE EndDate > @BillStartDate

--判断@DayStart和@DayEnd都为空，则没有月结存数据，直接计算所有数据
IF @DayStart IS NULL AND @DayEnd IS NULL
BEGIN
	--根据开账日期，用查询的开始日期计算，离开账日期的天数Date1，和离当前日期的天数Date2，然后比较Date1和Date2的大小【Date1>Date2记为1，反之记为0】
	--当Date1大时，说明查询的开始日期离当前日期更加近，所以采用反算的方法
	--当Date2大时，说明查询的开始日期离开账日期更加近，所以采用正算的方法
	--（不根据单量，每次计算单量的时间会很长，不实际，除非有一个表已经记录了单量）
	SELECT @DateFlag=CASE WHEN DATEDIFF(DAY,MIN(StartDate), @BillStartDate) >= DATEDIFF(DAY,@BillStartDate,GETDATE()) THEN 1 ELSE 0 END  FROM SS_MonthProc
	IF @DateFlag=0
	BEGIN 
		SET @SqlOne='
	SELECT ISNULL(SUM(Qty),0)[BSQty],ISNULL(SUM(Total),0)[GoodsCostTotal] FROM BD_OpeningStock b '
		SET @SqlTwoParamDate=' dtl.BillDate<@BillStartDate '
		SET @IsHistory = 1  --正算的话，一定要把历史表加入，不然计算肯定是不正确的
	END
	ELSE
	BEGIN
		SET @SqlOne='
	SELECT ISNULL(SUM(Qty),0)[BSQty],ISNULL(SUM(Total),0)[GoodsCostTotal] FROM PD_GoodsStock b '
		SET @SqlTwoParamDate=' dtl.BillDate>=@BillStartDate '
		SET @Negative='*-1'
	END
END
--有月结存数据
ELSE
BEGIN
	--有月结存数据,并且查询的开始日期在两个月结存数据之间
	IF @DayStart IS NOT NULL AND @DayEnd IS NOT NULL
	BEGIN
		SET @SqlOne='
	SELECT ISNULL(SUM(Qty),0)[BSQty],ISNULL(SUM(Total),0)[GoodsCostTotal] FROM SS_MonthProc mp 
	INNER JOIN SS_MonthStock b ON b.Period = mp.Period '
		IF @DayStart < @DayEnd
		BEGIN
			SET @SqlOneParam='AND mp.EndDate=@StartD '
			SET @SqlTwoParamDate=' dtl.BillDate > @StartD AND dtl.BillDate < @BillStartDate '
		END
		ELSE
		BEGIN
			SET @SqlOneParam='AND mp.EndDate=@EndD '
			SET @SqlTwoParamDate=' dtl.BillDate BETWEEN @BillStartDate AND @EndD '
			SET @Negative='*-1'
		END
	END
	--有月结存数据（两种情况：左边靠近开账日期【1】 或者 右边超出了月结存最后一次的日期【2】）
	ELSE	
	BEGIN
		--【2】是空的
		IF @DayStart IS NOT NULL
		BEGIN
			--计算查询日期到当前日期的天数差
			SELECT @DayEnd=DATEDIFF(DAY,@BillStartDate, GETDATE())
			--【1】小，说明【1】近，应该用月结存的正算。
			IF @DayStart < @DayEnd
			BEGIN
				SET @SqlOne='
	SELECT ISNULL(SUM(Qty),0)[BSQty],ISNULL(SUM(Total),0)[GoodsCostTotal] FROM SS_MonthProc mp 
	INNER JOIN SS_MonthStock b ON b.Period = mp.Period '
				SET @SqlOneParam='AND mp.EndDate=@StartD '
				SET @SqlTwoParamDate=' dtl.BillDate > @StartD AND dtl.BillDate < @BillStartDate '
			END
			--【1】大，说明【1】远，应该用月结存的反算，由于右边无月结存数据，所以应该直接用所有数据进行反算
			ELSE
			BEGIN
				SET @SqlOne='
	SELECT ISNULL(SUM(Qty),0)[BSQty],ISNULL(SUM(Total),0)[GoodsCostTotal] FROM PD_GoodsStock b '
				SET @SqlTwoParamDate=' dtl.BillDate>=@BillStartDate '
				SET @Negative='*-1'
			END
		END
		--即【1】是空的
		ELSE
		BEGIN
			--计算开账日期到查询日期的天数差
			SELECT @DayStart=DATEDIFF(DAY,MIN(StartDate), @BillStartDate) FROM SS_MonthProc
			--【1】小，说明【1】近，应该用月结存的正算，由于左边无月结存数据，所以直接用所有数据进行正算
			IF @DayStart < @DayEnd
			BEGIN
				SET @SqlOne='
	SELECT ISNULL(SUM(Qty),0)[BSQty],ISNULL(SUM(Total),0)[GoodsCostTotal] FROM BD_OpeningStock b '
				SET @SqlTwoParamDate=' dtl.BillDate<@BillStartDate '
				SET @IsHistory = 1  --正算的话，一定要把历史表加入，不然计算肯定是不正确的
			END
			--【1】大，说明【1】远，应该用月结存的反算。
			ELSE
			BEGIN
				SET @SqlOne='
	SELECT ISNULL(SUM(Qty),0)[BSQty],ISNULL(SUM(Total),0)[GoodsCostTotal] FROM SS_MonthProc mp 
	INNER JOIN SS_MonthStock b ON b.Period = mp.Period '
				SET @SqlOneParam='AND mp.EndDate=@EndD '
				SET @SqlTwoParamDate=' dtl.BillDate BETWEEN @BillStartDate AND @EndD '
				SET @Negative='*-1'
			END
		END
	END
END 

SET @SqlTwoParam = @SqlTwoParamDate + 'AND Red=0 AND IsDraft=0 '
IF @GoodsID<>0
BEGIN
	SET @SqlOneParam+='AND b.GoodsID=@GoodsID '
	SET @SqlTwoParam+='AND dtl.GoodsID=@GoodsID '
END
SET @SqlTwoParamDtl = 'b'+ SUBSTRING(@SqlTwoParam,5,LEN(@SqlTwoParam)-2) --调整赋值顺序，不然拆装单拼接不到商品ID的条件 150907
IF @SqlOneParam<>''
	SET @SqlOneParam='
	WHERE 1=1 '+@SqlOneParam
IF @SqlTwoParam<>''
BEGIN
	SET @SqlTwoParam='
		WHERE '+@SqlTwoParam
	SET @SqlTwoParamDtl='
		WHERE '+@SqlTwoParamDtl
END
----------------------------------------------（with 表达式中）商品过滤条件begin----------------------------------------------
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0
		SET @SqlGoodsParam += 'AND GoodsNo Like ''%''+@GoodsNo+''%'' '
	IF @GoodsNoMatch=1
		SET @SqlGoodsParam += 'AND GoodsNo=@GoodsNo '
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0
		SET @SqlGoodsParam += 'AND GoodsName Like ''%''+@GoodsName+''%'' '
	IF @GoodsNameMatch=1
		SET @SqlGoodsParam += 'AND GoodsName=@GoodsName '
END
IF @Spec <> '' OR (@ClickFlag <> 0 AND @SpecMatch=1)
BEGIN
	IF @SpecMatch=0
		SET @SqlGoodsParam += 'AND Spec Like ''%''+@Spec+''%'' '
	IF @SpecMatch=1
		SET @SqlGoodsParam += 'AND Spec=@Spec '
END
IF @Model <> '' OR (@ClickFlag <> 0 AND @ModelMatch=1)
BEGIN
	IF @ModelMatch=0
		SET @SqlGoodsParam += 'AND Model Like ''%''+@Model+''%'' '
	IF @ModelMatch=1
		SET @SqlGoodsParam += 'AND Model=@Model '
END

/*新增商品查询条件 start 150901*/
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @SqlGoodsParam += N' AND g.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @SqlGoodsParam += N' AND g.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @SqlGoodsParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @SqlGoodsParam += N' AND g.Brand = @Brand ' 
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
       SET @SqlGoodsParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = g.GoodsID '
	   IF @BarCodeMatch = 0
		   SET @SqlGoodsParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlGoodsParam += N' AND barcode.BarCode = @BarCode ' 
	   SET @SqlGoodsParam += ' ) '
   END    
/*end*/
----------------------------------------------（with 表达式中）商品过滤条件end----------------------------------------------

/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
BEGIN
	SET @DISTINCT = 'DISTINCT '
	SET @wLimitJion += '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=w.WhsID '
END

/*权限使用非公用方法*/
/*
IF @OperatorID <> 1
BEGIN
	IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
	BEGIN
		SET @DISTINCT = 'DISTINCT '
		SET @wLimitJion +='
	INNER JOIN SS_Whs_Jur swj ON swj.WhsID = w.WhsID 
	WHERE EXISTS (SELECT RoleID FROM SS_Oper_Role sor WHERE sor.OperID = @OperatorID AND swj.RoleID = sor.RoleID) '
	END
END
*/
IF @WhsID<>'' 
	IF @WhsTypeID=0 OR @WhsTypeID=1
		SET @SqlW+='
,Whs AS(
	SELECT '+@DISTINCT+'w.WhsID FROM BD_Whs w 
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid=w.WhsID '+@wLimitJion+'
)'
	ELSE
		SET @SqlW+='
,_WhsType AS(
	SELECT wt2.WhsTypeID[typeid] 
	FROM BD_Whs_Type wt 
	INNER JOIN BD_Whs_Type wt2 ON wt2.[Path] LIKE wt.[Path]+''%'' 
	WHERE wt.WhsTypeID=@WhsTypeID AND wt2.Stt=1 
	GROUP BY wt2.WhsTypeID
)
,Whs AS(
	SELECT '+@DISTINCT+'w.WhsID FROM BD_Whs w 
	INNER JOIN _WhsType ON _WhsType.typeid=w.WhsTypeID 
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid=w.WhsID '+@wLimitJion+'
)'
ELSE
	IF @WhsTypeID<>0 AND @WhsTypeID<>1
		SET @SqlW+='
,_WhsType AS(
	SELECT wt2.WhsTypeID[typeid] 
	FROM BD_Whs_Type wt 
	INNER JOIN BD_Whs_Type wt2 ON wt2.[Path] LIKE wt.[Path]+''%'' 
	WHERE wt.WhsTypeID=@WhsTypeID AND wt2.Stt=1 
	GROUP BY wt2.WhsTypeID
)
,Whs AS(
	SELECT '+@DISTINCT+'w.WhsID FROM BD_Whs w 
	INNER JOIN _WhsType ON _WhsType.typeid=w.WhsTypeID '+@wLimitJion+'
)'
	ELSE
		IF @wLimitJion<>''
			SET @SqlW+='
,Whs AS(
	SELECT WhsID FROM UF_BD_KtypeLimit(@OperatorID)
)'
--			SET @SqlW+='
--,Whs AS(
--	SELECT '+@DISTINCT+'WhsID FROM SS_Whs_Jur swj 
--	WHERE EXISTS (SELECT RoleID FROM SS_Oper_Role sor WHERE sor.OperID = @OperatorID AND swj.RoleID = sor.RoleID) 
--)'


IF @GoodsTypeID<>0 AND @GoodsTypeID<>1 
BEGIN
	SET @SqlG+='
,_GoodsType AS(
	SELECT gt2.GoodsTypeID[typeid] 
	FROM BD_Goods_Type gt 
	INNER JOIN BD_Goods_Type gt2 ON gt2.[Path] LIKE gt.[Path]+''%'' 
	WHERE gt.GoodsTypeID=@GoodsTypeID AND gt2.Stt=1 
	GROUP BY gt2.GoodsTypeID
)

,Goods AS(
	SELECT g.GoodsID FROM BD_Goods g 
	INNER JOIN _GoodsType ON _GoodsType.typeid=g.GoodsTypeID '
	IF @SqlGoodsParam<>'' AND @GoodsID=0
		SET @SqlG+='
	WHERE 1=1 ' + @SqlGoodsParam + '
)'
	ELSE
		SET @SqlG+='
)'
END
ELSE
BEGIN
	IF @SqlGoodsParam<>'' AND @GoodsID=0 SET @SqlG+='
,Goods AS(
	SELECT g.GoodsID FROM BD_Goods g 
	WHERE 1=1 '+@SqlGoodsParam+'
)'
END

IF @SqlW<>'' 
BEGIN
	SET @SqlOneJoinW = '
	INNER JOIN Whs w ON w.WhsID=b.WhsID '
	SET @SqlTwoJoinW = '
		INNER JOIN Whs w ON w.WhsID=b.WhsID '
	SET @SqlTwoJoinWDtl = '
		INNER JOIN Whs w ON w.WhsID=dtl.WhsID '
	SET @SqlTwoJoinWIn = '
		INNER JOIN Whs w ON w.WhsID=b.InWhsID '
	SET @SqlTwoJoinWOut = '
		INNER JOIN Whs w ON w.WhsID=b.OutWhsID '
END 
IF @SqlG<>'' 
BEGIN
	SET @SqlOneJoinG = '
	INNER JOIN Goods g ON g.GoodsID=b.GoodsID '
	SET @SqlTwoJoinG = '
		INNER JOIN Goods g ON g.GoodsID=dtl.GoodsID '
END

SET @Sql+=';WITH PlaceHolder AS(SELECT '''' PlaceHolder ) '
SET @Sql+=@SqlW+@SqlG
SET @Sql+='
,BalanceData AS ('+@SqlOne+@SqlOneJoinW+@SqlOneJoinG+@SqlOneParam+'
	UNION ALL 
	SELECT SUM(BSQty)'+@Negative+'[BSQty],SUM(GoodsCostTotal)'+@Negative+'[GoodsCostTotal] 
	FROM 
	( '
SET @Sql+='
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_AllotBill b 
		INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWIn+@SqlTwoJoinG+@SqlTwoParam+'AND b.InspectTag=1 AND BillTypeID=301 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AllotBill b 
		INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWOut+@SqlTwoJoinG+@SqlTwoParam+'AND BillTypeID=301 
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(AllotTotal)[GoodsCostTotal] 
		FROM PD_AllotBill b 
		INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWIn+@SqlTwoJoinG+@SqlTwoParam+'AND b.InspectTag=1 AND BillTypeID=309 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AllotBill b 
		INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWOut+@SqlTwoJoinG+@SqlTwoParam+'AND BillTypeID=309 '
SET @Sql+='
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(dtl.AdjTotal)[GoodsCostTotal] 
		FROM PD_AdjPriceBill b 
		INNER JOIN PD_AdjPriceDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AdjPriceBill b 
		INNER JOIN PD_AdjPriceDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_PchBill b 
		INNER JOIN PD_PchDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_PchRetBill b 
		INNER JOIN PD_PchRetDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam
SET @Sql+='
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_SellBill b 
		INNER JOIN PD_SellDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_SellRetBill b 
		INNER JOIN PD_SellRetDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_InOutWhsBill b 
		INNER JOIN PD_InOutWhsDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=303 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_InOutWhsBill b 
		INNER JOIN PD_InOutWhsDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=304  
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_InOutWhsBill b 
		INNER JOIN PD_InOutWhsDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=600 '
SET @Sql+='
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_LossSpillBill b 
		INNER JOIN PD_LossSpillDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=305 
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_LossSpillBill b 
		INNER JOIN PD_LossSpillDetail dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=306 
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_AssemblyBill b 
		INNER JOIN PD_AssemblyDetail dtl ON b.BillNo=dtl.BillNo'+@SqlTwoJoinWDtl+@SqlTwoJoinG+@SqlTwoParamDtl+'AND dtl.DetailType=1 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AssemblyBill b 
		INNER JOIN PD_AssemblyDetail dtl ON b.BillNo=dtl.BillNo'+@SqlTwoJoinWDtl+@SqlTwoJoinG+@SqlTwoParamDtl+'AND dtl.DetailType=2 '
IF @IsHistory = 1
BEGIN
	SET @Sql+='
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_AllotBill_His b 
		INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWIn+@SqlTwoJoinG+@SqlTwoParam+'AND b.InspectTag=1 AND BillTypeID=301 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AllotBill_His b 
		INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWOut+@SqlTwoJoinG+@SqlTwoParam+'AND BillTypeID=301 
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(AllotTotal)[GoodsCostTotal] 
		FROM PD_AllotBill_His b 
		INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWIn+@SqlTwoJoinG+@SqlTwoParam+'AND b.InspectTag=1 AND BillTypeID=309 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AllotBill_His b 
		INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinWOut+@SqlTwoJoinG+@SqlTwoParam+'AND BillTypeID=309 '
	SET @Sql+='
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(dtl.AdjTotal)[GoodsCostTotal] 
		FROM PD_AdjPriceBill_His b 
		INNER JOIN PD_AdjPriceDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AdjPriceBill_His b 
		INNER JOIN PD_AdjPriceDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_PchBill_His b 
		INNER JOIN PD_PchDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_PchRetBill_His b 
		INNER JOIN PD_PchRetDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam
	SET @Sql+='
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_SellBill_His b 
		INNER JOIN PD_SellDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_SellRetBill_His b 
		INNER JOIN PD_SellRetDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_InOutWhsBill_His b 
		INNER JOIN PD_InOutWhsDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=303 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_InOutWhsBill_His b 
		INNER JOIN PD_InOutWhsDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=304 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_InOutWhsBill_His b 
		INNER JOIN PD_InOutWhsDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=600 '
	SET @Sql+='
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_LossSpillBill_His b 
		INNER JOIN PD_LossSpillDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=305 
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_LossSpillBill_His b 
		INNER JOIN PD_LossSpillDetail_His dtl ON b.BillNo=dtl.BillNo '+@SqlTwoJoinW+@SqlTwoJoinG+@SqlTwoParam+'AND b.BillTypeID=306 
		UNION ALL 
		SELECT SUM(BSQty)[BSQty],SUM(GoodsCostTotal)[GoodsCostTotal] 
		FROM PD_AssemblyBill_His b 
		INNER JOIN PD_AssemblyDetail_His dtl ON b.BillNo=dtl.BillNo'+@SqlTwoJoinWDtl+@SqlTwoJoinG+@SqlTwoParamDtl+'AND dtl.DetailType=1 
		UNION ALL 
		SELECT SUM(BSQty)*-1[BSQty],SUM(GoodsCostTotal)*-1[GoodsCostTotal] 
		FROM PD_AssemblyBill_His b 
		INNER JOIN PD_AssemblyDetail_His dtl ON b.BillNo=dtl.BillNo'+@SqlTwoJoinWDtl+@SqlTwoJoinG+@SqlTwoParamDtl+'AND dtl.DetailType=2 '
END 
SET @Sql+='
	) o 
) 
SELECT SUM(ISNULL(BSQty,0))[BFQty],SUM(ISNULL(GoodsCostTotal,0))[BFTotal] FROM BalanceData '
--SELECT CAST( SUM(ISNULL(BSQty,0)) AS DECIMAL(18,4) )[BFQty],CAST( SUM(ISNULL(GoodsCostTotal,0)) AS DECIMAL(18,4) )[BFTotal] FROM BalanceData '
IF @KtypeLimit = 0 SET @Sql = N' SELECT 0[BFQty],0[BFTotal] '

--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END  

EXEC SP_EXECUTESQL @Sql,N'@BillStartDate DATETIME,@WhsTypeID INT,@WhsID VARCHAR(100),@GoodsTypeID INT,@GoodsID INT
,@GoodsNoMatch INT,@GoodsNo VARCHAR(100),@GoodsNameMatch INT,@GoodsName VARCHAR(100),@SpecMatch INT,@Spec VARCHAR(100),@ModelMatch INT,@Model VARCHAR(100)
,@StartD DATETIME,@EndD DATETIME,@OperatorID INT,@AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100)',@BillStartDate,@WhsTypeID,@WhsID,@GoodsTypeID,@GoodsID
,@GoodsNoMatch,@GoodsNo,@GoodsNameMatch,@GoodsName,@SpecMatch,@Spec,@ModelMatch,@Model,@StartD,@EndD,@OperatorID,@AbbName,@Brand,@BarCode

END

GO






/****** Object:  StoredProcedure [UP_PD_RGoodSDList]    Script Date: 07/09/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_RGoodSDList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_RGoodSDList]
GO

/****** Object:  StoredProcedure [UP_PD_RGoodSDList]    Script Date: 07/09/2014 15:42:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-10-20
	描述：存货明细账
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_RGoodSDList]
(			   
	@pageNo INT=1,					--页码
	@pageSize INT=10,				--分页数
	@BillStartDate DATE,			--单据开始日期
	@BillEndDate DATE,				--单据结束日期
	@WhsTypeID INT=0,				--仓库分类
	@WhsID VARCHAR(100) = '',		--仓库
	@GoodsTypeID INT=0,				--商品分类
	@GoodsID INT=0,					--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',	--商品名称
	@SpecMatch INT=0,				--规格配置模式:0=包含,1=等于
	@Spec VARCHAR(100) = '',		--规格
	@ModelMatch INT=0,				--型号配置模式:0=包含,1=等于
	@Model VARCHAR(100) = '',		--型号
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,			--品牌匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@IsShowRed INT=0,				--显示红冲单据:1=显示,0=不显示
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@ClickFlag INT=0				--是否跳转
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX),@Sqlw NVARCHAR(MAX)='',@Sqlg NVARCHAR(MAX)='',@SqlParamOne VARCHAR(200),@SqlParamOneDtl VARCHAR(200),@SqlParam1 NVARCHAR(MAX)=''
		,@wLimitJion NVARCHAR(300)='',@DISTINCT VARCHAR(10)=''
		,@wStr VARCHAR(200)='',@wStrDtl VARCHAR(200)='',@wStr1 VARCHAR(200)='',@wStr2 VARCHAR(200)='',@gStr VARCHAR(100)='',@dStr1 VARCHAR(10)='',@dStr2 VARCHAR(10)=''
		,@KtypeLimit INT=0 
SET @SqlParamOneDtl='WHERE dtl.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft=0 '
IF @IsShowRed=0
	SET @SqlParamOneDtl+='AND Red=0 '
IF @GoodsID<>0
	SET @SqlParamOneDtl+='AND dtl.GoodsID=@GoodsID '
SET @SqlParamOne='WHERE b'+SUBSTRING(@SqlParamOneDtl,10,LEN(@SqlParamOneDtl)-8)

SET @Sql='SET NOCOUNT ON; 
IF OBJECT_ID(''tempdb..#tempPD'',''U'') IS NOT NULL DROP TABLE #tempPD '
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0
		SET @SqlParam1 += 'AND GoodsNo Like ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch=1
		SET @SqlParam1 += 'AND GoodsNo=@GoodsNo '  
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0
		SET @SqlParam1 += 'AND GoodsName Like ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch=1
		SET @SqlParam1 += 'AND GoodsName=@GoodsName '  
END
IF @Spec <> '' OR (@ClickFlag <> 0 AND @SpecMatch=1)
BEGIN
	IF @SpecMatch=0
		SET @SqlParam1 += 'AND Spec Like ''%''+@Spec+''%'' '  
	IF @SpecMatch=1
		SET @SqlParam1 += 'AND Spec=@Spec '  
END
IF @Model <> '' OR (@ClickFlag <> 0 AND @ModelMatch=1)
BEGIN
	IF @ModelMatch=0
		SET @SqlParam1 += 'AND Model Like ''%''+@Model+''%'' '  
	IF @ModelMatch=1
		SET @SqlParam1 += 'AND Model=@Model '  
END

/*新增商品查询条件 start 150901*/
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @SqlParam1 += N' AND g.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @SqlParam1 += N' AND g.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @SqlParam1 += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @SqlParam1 += N' AND g.Brand = @Brand ' 
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
       SET @SqlParam1 += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = g.GoodsID '
	   IF @BarCodeMatch = 0
		   SET @SqlParam1 += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlParam1 += N' AND barcode.BarCode = @BarCode ' 
	   SET @SqlParam1 += ' ) '
   END    
/*end*/
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
BEGIN
	SET @DISTINCT = 'DISTINCT '
	SET @wLimitJion += '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=w.WhsID '
END
IF @WhsID<>'' 
	IF @WhsTypeID=0 OR @WhsTypeID=1
		SET @Sqlw+='
,Whs AS(
	SELECT '+@DISTINCT+'w.WhsID FROM BD_Whs w 
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid=w.WhsID '+@wLimitJion+'
)'
	ELSE
		SET @Sqlw+='
,_WhsType AS(
	SELECT wt2.WhsTypeID[typeid] 
	FROM BD_Whs_Type wt 
	INNER JOIN BD_Whs_Type wt2 ON wt2.[Path] LIKE wt.[Path]+''%'' 
	WHERE wt.WhsTypeID=@WhsTypeID AND wt2.Stt=1 
	GROUP BY wt2.WhsTypeID
)
,Whs AS(
	SELECT '+@DISTINCT+'w.WhsID FROM BD_Whs w 
	INNER JOIN _WhsType ON _WhsType.typeid=w.WhsTypeID 
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid=w.WhsID '+@wLimitJion+'
)'
ELSE
	IF @WhsTypeID<>0 AND @WhsTypeID<>1
		SET @Sqlw+='
,_WhsType AS(
	SELECT wt2.WhsTypeID[typeid] 
	FROM BD_Whs_Type wt 
	INNER JOIN BD_Whs_Type wt2 ON wt2.[Path] LIKE wt.[Path]+''%'' 
	WHERE wt.WhsTypeID=@WhsTypeID AND wt2.Stt=1 
	GROUP BY wt2.WhsTypeID
)
,Whs AS(
	SELECT '+@DISTINCT+'w.WhsID FROM BD_Whs w 
	INNER JOIN _WhsType ON _WhsType.typeid=w.WhsTypeID '+@wLimitJion+'
)'
	ELSE
		IF @wLimitJion<>''
			SET @SqlW+='
,Whs AS(
	SELECT WhsID FROM UF_BD_KtypeLimit(@OperatorID)
)'
--			SET @Sqlw+='
--,Whs AS(
--	SELECT '+@DISTINCT+'WhsID FROM SS_Whs_Jur swj 
--	WHERE EXISTS (SELECT RoleID FROM SS_Oper_Role sor WHERE sor.OperID = @OperatorID AND swj.RoleID = sor.RoleID) 
--)'

IF @GoodsTypeID<>0 AND @GoodsTypeID<>1
BEGIN
	SET @Sqlg+='
,_GoodsType AS(
	SELECT gt2.GoodsTypeID[typeid] 
	FROM BD_Goods_Type gt 
	INNER JOIN BD_Goods_Type gt2 ON gt2.[Path] LIKE gt.[Path]+''%'' 
	WHERE gt.GoodsTypeID=@GoodsTypeID AND gt2.Stt=1 
	GROUP BY gt2.GoodsTypeID
)
,Goods AS(
	SELECT g.GoodsID FROM BD_Goods g 
	INNER JOIN _GoodsType ON _GoodsType.typeid=g.GoodsTypeID '
	IF @SqlParam1<>'' AND @GoodsID=0
		SET @Sqlg+='
	WHERE 1=1 ' + @SqlParam1 + '
)'
	ELSE
		SET @Sqlg+='
)'
END
ELSE
BEGIN
	IF @SqlParam1<>'' AND @GoodsID=0 SET @Sqlg+='
,Goods AS(
	SELECT g.GoodsID FROM BD_Goods g 
	WHERE 1=1 ' + @SqlParam1 + '
)'
END

IF @Sqlw<>'' 
BEGIN
	SET @wStr = '
	INNER JOIN Whs w ON w.WhsID=b.WhsID '
	SET @wStrDtl = '
	INNER JOIN Whs w ON w.WhsID=dtl.WhsID '
	SET @wStr1 = '
	INNER JOIN Whs w ON w.WhsID=b.InWhsID '
	SET @wStr2 = '
	INNER JOIN Whs w ON w.WhsID=b.OutWhsID '
END 
IF @Sqlg<>'' 
BEGIN
	SET @gStr = '
	INNER JOIN Goods g ON g.GoodsID=dtl.GoodsID '
END

SET @Sql+='
;WITH PlaceHolder AS(SELECT '''' PlaceHolder ) '
SET @Sql+=@Sqlw+@Sqlg+'
,PagingData AS('
SET @Sql+='
	SELECT b.BillNo,30101[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill b 
	INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@wStr1+@gStr+@SqlParamOneDtl+'AND b.InspectTag=1 AND BillTypeID=301 
	UNION ALL 
	SELECT b.BillNo,30102[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill b 
	INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@wStr2+@gStr+@SqlParamOneDtl+'AND BillTypeID=301 
	UNION ALL 
	SELECT b.BillNo,30901[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill b 
	INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@wStr1+@gStr+@SqlParamOneDtl+'AND b.InspectTag=1 AND BillTypeID=309 
	UNION ALL 
	SELECT b.BillNo,30902[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill b 
	INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo '+@wStr2+@gStr+@SqlParamOneDtl+'AND BillTypeID=309 '
SET @Sql+='
	UNION ALL 
	SELECT b.BillNo,30201[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_AdjPriceBill b 
	INNER JOIN PD_AdjPriceDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,30202[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_AdjPriceBill b 
	INNER JOIN PD_AdjPriceDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,101[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_PchBill b 
	INNER JOIN PD_PchDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,102[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_PchRetBill b 
	INNER JOIN PD_PchRetDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl
SET @Sql+='
	UNION ALL 
	SELECT b.BillNo,201[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_SellBill b 
	INNER JOIN PD_SellDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,202[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_SellRetBill b 
	INNER JOIN PD_SellRetDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,b.BillTypeID,b.BillDate,b.PosTime,dtl.DID 
	FROM PD_InOutWhsBill b 
	INNER JOIN PD_InOutWhsDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,b.BillTypeID,b.BillDate,b.PosTime,dtl.DID  
	FROM PD_LossSpillBill b 
	INNER JOIN PD_LossSpillDetail dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl
SET @Sql+='
	UNION ALL 
	SELECT b.BillNo,31001[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AssemblyBill b 
	INNER JOIN PD_AssemblyDetail dtl ON b.BillNo=dtl.BillNo '+@wStrDtl+@gStr+@SqlParamOne+'AND dtl.DetailType=1 
	UNION ALL 
	SELECT b.BillNo,31002[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AssemblyBill b 
	INNER JOIN PD_AssemblyDetail dtl ON b.BillNo=dtl.BillNo '+@wStrDtl+@gStr+@SqlParamOne+'AND dtl.DetailType=2 '
IF @IsHistory=1
BEGIN
	SET @Sql+='
	UNION ALL
	SELECT b.BillNo,30101[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill_His b 
	INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr1+@gStr+@SqlParamOneDtl+'AND b.InspectTag=1 AND BillTypeID=301 
	UNION ALL 
	SELECT b.BillNo,30102[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill_His b 
	INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr2+@gStr+@SqlParamOneDtl+'AND BillTypeID=301 
	UNION ALL
	SELECT b.BillNo,30901[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill_His b 
	INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr1+@gStr+@SqlParamOneDtl+'AND b.InspectTag=1 AND BillTypeID=309 
	UNION ALL 
	SELECT b.BillNo,30902[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AllotBill_His b 
	INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr2+@gStr+@SqlParamOneDtl+'AND BillTypeID=309 '
	SET @Sql+='
	UNION ALL 
	SELECT b.BillNo,30201[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_AdjPriceBill_His b 
	INNER JOIN PD_AdjPriceDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,30202[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_AdjPriceBill_His b 
	INNER JOIN PD_AdjPriceDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,101[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_PchBill_His b 
	INNER JOIN PD_PchDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,102[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_PchRetBill_His b 
	INNER JOIN PD_PchRetDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl
	SET @Sql+='
	UNION ALL 
	SELECT b.BillNo,201[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_SellBill_His b 
	INNER JOIN PD_SellDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,202[BillTypeID],b.BillDate,b.PosTime,dtl.DID  
	FROM PD_SellRetBill_His b 
	INNER JOIN PD_SellRetDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,b.BillTypeID,b.BillDate,b.PosTime,dtl.DID 
	FROM PD_InOutWhsBill_His b 
	INNER JOIN PD_InOutWhsDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl+'
	UNION ALL 
	SELECT b.BillNo,b.BillTypeID,b.BillDate,b.PosTime,dtl.DID  
	FROM PD_LossSpillBill_His b 
	INNER JOIN PD_LossSpillDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStr+@gStr+@SqlParamOneDtl
	SET @Sql+='
	UNION ALL 
	SELECT b.BillNo,31001[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AssemblyBill_His b 
	INNER JOIN PD_AssemblyDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStrDtl+@gStr+@SqlParamOne+'AND dtl.DetailType=1 
	UNION ALL 
	SELECT b.BillNo,31002[BillTypeID],b.BillDate,b.PosTime,dtl.DID 
	FROM PD_AssemblyBill_His b 
	INNER JOIN PD_AssemblyDetail_His dtl ON b.BillNo=dtl.BillNo '+@wStrDtl+@gStr+@SqlParamOne+'AND dtl.DetailType=2 '
END

SET @Sql +='
)
SELECT * INTO #tempPD FROM 
(SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
CROSS JOIN
(SELECT * FROM (SELECT *,ROW_NUMBER() OVER(ORDER BY BillDate,PosTime) AS ROWID FROM PagingData) AS B
WHERE ROWID>(@PageNo-1)*@PageSize 
AND ROWID<=@PageNo*@PageSize) C 
;WITH BillData AS ('

IF @IsShowRed=1
BEGIN
	SET @Sql +='
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.InspectQty*-1 ELSE dtl.InspectQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30101 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30102 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AllotPrice ELSE CAST(dtl.AllotPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30901 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30902 '
	SET @Sql+='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AdjPrice ELSE CAST(dtl.AdjPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=101
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchRetBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchRetDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=102 '
	SET @Sql+='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]  
	FROM #tempPD pd 
	INNER JOIN PD_SellBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_SellRetBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellRetDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=303 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=304 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''积分兑换单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=600 '
	SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报损单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=305 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报溢单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=306 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31001 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31002 '
END
ELSE
BEGIN
	SET @Sql +='
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.InspectQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30101 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30102 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AllotPrice ELSE CAST(dtl.AllotPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30901 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30902 '
	SET @Sql+='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AdjPrice ELSE CAST(dtl.AdjPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=101 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchRetBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchRetDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=102 '
	SET @Sql+='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]  
	FROM #tempPD pd 
	INNER JOIN PD_SellBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_SellRetBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellRetDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=303 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=304 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''积分兑换单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=600 '
	SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报损单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=305 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报溢单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=306 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31001
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31002 '
END
IF @IsHistory=1
BEGIN
	IF @IsShowRed=1
	BEGIN
		SET @Sql +='
	UNION ALL
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.InspectQty*-1 ELSE dtl.InspectQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30101 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30102 
	UNION ALL
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.InspectQty*-1 ELSE dtl.InspectQty END[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AllotPrice ELSE CAST(dtl.AllotPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30901 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30902 '
		SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AdjPrice ELSE CAST(dtl.AdjPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=101 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchRetBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchRetDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=102 '
	SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]  
	FROM #tempPD pd 
	INNER JOIN PD_SellBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_SellRetBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellRetDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=303 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=304 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''积分兑换单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=600 '
		SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报损单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=305 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报溢单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=306 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31001 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],CASE WHEN b.Red=2 THEN dtl.BSQty*-1 ELSE dtl.BSQty END[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31002 '
	END
	ELSE
	BEGIN
		SET @Sql +='
	UNION ALL
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.InspectQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30101 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,301[BillTypeID],pd.BillDate,pd.PosTime,''同价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30102 
	UNION ALL
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(入库)''[BillName],dtl.InWhsID[WhsID],dtl.InWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.InspectQty[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AllotPrice ELSE CAST(dtl.AllotPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30901 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,309[BillTypeID],pd.BillDate,pd.PosTime,''变价调拨单(出库)''[BillName],dtl.OutWhsID[WhsID],dtl.OutWhsPtID[WhsPtID],dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AllotBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AllotDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30902 '
		SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],CASE WHEN UnitID=1 THEN dtl.AdjPrice ELSE CAST(dtl.AdjPrice/dtl.Convfactor AS DECIMAL(20,8)) END[CostPrice],b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,302[BillTypeID],pd.BillDate,pd.PosTime,''调价单(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AdjPriceBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AdjPriceDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=30202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=101 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''采购退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_PchRetBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_PchRetDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=102 '
	SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]  
	FROM #tempPD pd 
	INNER JOIN PD_SellBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=201 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''销售退货单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_SellRetBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_SellRetDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=202 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他入库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=303 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''其他出库单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=304 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''积分兑换单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT]   
	FROM #tempPD pd 
	INNER JOIN PD_InOutWhsBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_InOutWhsDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=600'
	SET @Sql +='
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报损单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=305 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,pd.BillTypeID,pd.BillDate,pd.PosTime,''报溢单''[BillName],b.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_LossSpillBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_LossSpillDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=306 
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(入库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,dtl.BSQty[InBSQty],NULL[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31001
	UNION ALL 
	SELECT pd.ROWID,pd.BillNo,310[BillTypeID],pd.BillDate,pd.PosTime,''生产拆装(出库)''[BillName],dtl.WhsID,dtl.WhsPtID,dtl.GoodsID,dtl.Ppt1ID,dtl.Ppt2ID,b.DeptID,b.ElyID,b.BillCode,NULL[InBSQty],dtl.BSQty[OutBSQty],dtl.CostPrice,b.Summary,b.[Description],b.CreateTime,b.Red,pd.[ROWCOUNT] 
	FROM #tempPD pd 
	INNER JOIN PD_AssemblyBill_His b ON b.BillNo = pd.BillNo 
	INNER JOIN PD_AssemblyDetail_His dtl ON dtl.DID = pd.DID 
	WHERE pd.BillTypeID=31002 '
	END
END
SET @Sql +='
)
SELECT o.ROWID,o.[ROWCOUNT],o.BillNo,o.BillDate,o.BillTypeID,o.BillName
,w.WhsNO,w.WhsName
,wp.WhsPtNO,wp.WhsPtName
,g.GoodsNo,g.GoodsName,g.Spec,g.Model
,p1.Value[Ppt1Name],p2.Value[Ppt2Name]
,o.PosTime,d.DeptCode,d.DeptName,e.ElyCode,e.ElyName
,o.BillCode
,o.InBSQty,o.OutBSQty,o.CostPrice
,o.Summary,o.[Description],o.CreateTime,o.Red 
,g.Brand,g.GoodsAbbName,pri.BarCode
FROM BillData o
INNER JOIN BD_Whs w ON w.WhsID=o.WhsID 
LEFT JOIN BD_Whs_Position wp ON wp.WhsPtID=o.WhsPtID 
INNER JOIN BD_Goods g ON g.GoodsID=o.GoodsID 
LEFT JOIN BD_Goods_Ppt1 p1 ON p1.Ppt1ID=o.Ppt1ID 
LEFT JOIN BD_Goods_Ppt2 p2 ON p2.Ppt2ID=o.Ppt2ID 
INNER JOIN BD_Dept d ON d.DeptID=o.DeptID 
INNER JOIN BD_Employee e ON e.ElyID=o.ElyID 
INNER JOIN dbo.BD_Goods_Price pri ON g.GoodsID=pri.GoodsID AND pri.UnitID = 1 
ORDER BY BillDate,PosTime 
DROP TABLE #tempPD'
IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END  

EXEC SP_EXECUTESQL @Sql,N'@pageNo INT,@pageSize INT
,@BillStartDate DATE,@BillEndDate DATE,@WhsTypeID INT,@WhsID VARCHAR(1000),@GoodsTypeID INT,@GoodsID INT
,@GoodsNoMatch INT,@GoodsNo VARCHAR(100),@GoodsNameMatch INT,@GoodsName VARCHAR(100),@SpecMatch INT,@Spec VARCHAR(100),@ModelMatch INT,@Model VARCHAR(100)
,@OperatorID INT,@AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100)',@pageNo,@pageSize,@BillStartDate,@BillEndDate,@WhsTypeID,@WhsID,@GoodsTypeID,@GoodsID
,@GoodsNoMatch,@GoodsNo,@GoodsNameMatch,@GoodsName,@SpecMatch,@Spec,@ModelMatch,@Model,@OperatorID,@AbbName,@Brand,@BarCode

END

GO






/****** Object:  StoredProcedure [UP_PD_RGoodSDLSum]    Script Date: 06/23/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_RGoodSDLSum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_RGoodSDLSum]
GO

/****** Object:  StoredProcedure [UP_PD_RGoodSDLSum]    Script Date: 06/23/2014 15:42:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-22
	描述：存货明细账_合计：存库数量、金额
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_RGoodSDLSum]
(
	@BillStartDate DATETIME,		--单据结束日期
	@BillEndDate DATETIME,			--单据结束日期
	@WhsTypeID INT=0,				--仓库分类
	@WhsID VARCHAR(100) = '',		--仓库
	@GoodsTypeID INT=0,				--商品分类
	@GoodsID INT=0,					--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',	--商品名称
	@SpecMatch INT=0,				--规格配置模式:0=包含,1=等于
	@Spec VARCHAR(100) = '',		--规格
	@ModelMatch INT=0,				--型号配置模式:0=包含,1=等于
	@Model VARCHAR(100) = '',		--型号
	@AbbName VARCHAR(50) = '',      --简名
	@AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,			--品牌匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0,				--操作员ID
	@ClickFlag INT=0				--是否跳转
)

AS
SET NOCOUNT ON
BEGIN

DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX),@SqlParam1 VARCHAR(200)='',@SqlParamOne VARCHAR(200),@SqlParamOneDtl VARCHAR(200),@SqlParam NVARCHAR(MAX)='',@Sqlw NVARCHAR(MAX)='',@Sqlg NVARCHAR(MAX)='',@wStr NVARCHAR(300)='',@gStr NVARCHAR(300)='',@KtypeLimit INT=0 

SET @SqlParamOne='WHERE b.BillDate BETWEEN @BillStartDate AND @BillEndDate AND Red=0 AND IsDraft=0 '
SET @SqlParamOneDtl='WHERE dtl.BillDate BETWEEN @BillStartDate AND @BillEndDate AND Red=0 AND IsDraft=0 '
IF @GoodsID<>0
BEGIN
	SET @SqlParamOne+='AND dtl.GoodsID=@GoodsID '
	SET @SqlParamOneDtl+='AND dtl.GoodsID=@GoodsID '
END

SET @Sql='
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_PchBill b 
		INNER JOIN PD_PchDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_PchRetBill b 
		INNER JOIN PD_PchRetDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_SellBill b 
		INNER JOIN PD_SellDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_SellRetBill b 
		INNER JOIN PD_SellRetDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl
SET @Sql+='
		UNION ALL
		SELECT dtl.InspectQty[InBSQty],0[OutBSQty],GoodsID,b.InWhsID[WhsID] 
		FROM PD_AllotBill b 
		INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.InspectTag=1 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.OutWhsID[WhsID] 
		FROM PD_AllotBill b 
		INNER JOIN PD_AllotDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL 
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_AdjPriceBill b 
		INNER JOIN PD_AdjPriceDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL 
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_AdjPriceBill b 
		INNER JOIN PD_AdjPriceDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl
SET @Sql+='
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_InOutWhsBill b 
		INNER JOIN PD_InOutWhsDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=303 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_InOutWhsBill b 
		INNER JOIN PD_InOutWhsDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=304 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_InOutWhsBill b 
		INNER JOIN PD_InOutWhsDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=600
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_LossSpillBill b 
		INNER JOIN PD_LossSpillDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=305 
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_LossSpillBill b 
		INNER JOIN PD_LossSpillDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=306 '
SET @Sql+='
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,dtl.WhsID
		FROM PD_AssemblyBill b 
		INNER JOIN PD_AssemblyDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOne+'AND dtl.DetailType=1 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,dtl.WhsID
		FROM PD_AssemblyBill b 
		INNER JOIN PD_AssemblyDetail dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOne+'AND dtl.DetailType=2 '
IF @IsHistory=1
BEGIN
	SET @Sql+='
		UNION ALL 
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_PchBill_His b 
		INNER JOIN PD_PchDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_PchRetBill_His b 
		INNER JOIN PD_PchRetDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_SellBill_His b 
		INNER JOIN PD_SellDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_SellRetBill_His b 
		INNER JOIN PD_SellRetDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl
	SET @Sql+='
		UNION ALL
		SELECT dtl.InspectQty[InBSQty],0[OutBSQty],GoodsID,b.InWhsID[WhsID] 
		FROM PD_AllotBill_His b 
		INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.InspectTag=1 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.OutWhsID[WhsID] 
		FROM PD_AllotBill_His b 
		INNER JOIN PD_AllotDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL 
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_AdjPriceBill_His b 
		INNER JOIN PD_AdjPriceDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'
		UNION ALL 
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_AdjPriceBill_His b 
		INNER JOIN PD_AdjPriceDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl
	SET @Sql+='
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_InOutWhsBill_His b 
		INNER JOIN PD_InOutWhsDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=303 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_InOutWhsBill_His b 
		INNER JOIN PD_InOutWhsDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=304 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_InOutWhsBill_His b 
		INNER JOIN PD_InOutWhsDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=600
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,b.WhsID 
		FROM PD_LossSpillBill_His b 
		INNER JOIN PD_LossSpillDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=305 
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,b.WhsID 
		FROM PD_LossSpillBill_His b 
		INNER JOIN PD_LossSpillDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOneDtl+'AND b.BillTypeID=306 '
	SET @Sql+='
		UNION ALL
		SELECT dtl.BSQty[InBSQty],0[OutBSQty],GoodsID,dtl.WhsID
		FROM PD_AssemblyBill_His b 
		INNER JOIN PD_AssemblyDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOne+'AND dtl.DetailType=1 
		UNION ALL
		SELECT 0[InBSQty],dtl.BSQty[OutBSQty],GoodsID,dtl.WhsID
		FROM PD_AssemblyBill_His b 
		INNER JOIN PD_AssemblyDetail_His dtl ON b.BillNo=dtl.BillNo 
		'+@SqlParamOne+'AND dtl.DetailType=2 '
END
SET @Sql+='
	) a 
	GROUP BY a.GoodsID,a.WhsID
) '

IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0
		SET @SqlParam += ' AND GoodsNo Like ''%''+@GoodsNo+''%'' '
	IF @GoodsNoMatch=1
		SET @SqlParam += ' AND GoodsNo=@GoodsNo '
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0
		SET @SqlParam += ' AND GoodsName Like ''%''+@GoodsName+''%'' '
	IF @GoodsNameMatch=1
		SET @SqlParam += ' AND GoodsName=@GoodsName '
END
IF @Spec <> '' OR (@ClickFlag <> 0 AND @SpecMatch=1)
BEGIN
	IF @SpecMatch=0
		SET @SqlParam += ' AND Spec Like ''%''+@Spec+''%'' '
	IF @SpecMatch=1
		SET @SqlParam += ' AND Spec=@Spec '
END
IF @Model <> '' OR (@ClickFlag <> 0 AND @ModelMatch=1)
BEGIN
	IF @ModelMatch=0
		SET @SqlParam += ' AND Model Like ''%''+@Model+''%'' '
	IF @ModelMatch=1
		SET @SqlParam += ' AND Model=@Model '
END

/*新增商品查询条件 start 150901*/
IF @AbbName <> ''    --商品简名
   BEGIN 
	   IF @AbbNameMatch = 0
		   SET @SqlParam += N' AND g.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
	   ELSE IF @AbbNameMatch = 1
		   SET @SqlParam += N' AND g.GoodsAbbName = @AbbName ' 
   END       
IF @Brand <> ''      --商品品牌
   BEGIN 
	   IF @BrandMatch = 0
		   SET @SqlParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @SqlParam += N' AND g.Brand = @Brand ' 
   END
IF @BarCode <> ''      --商品条码
   BEGIN 
       SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = g.GoodsID '
	   IF @BarCodeMatch = 0
		   SET @SqlParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlParam += N' AND barcode.BarCode = @BarCode ' 
	   SET @SqlParam += ' ) '
   END    
/*end*/

IF @WhsID<>'' 
	IF @WhsTypeID=0 OR @WhsTypeID=1
		SET @Sqlw+=',Whs AS(SELECT w.WhsID FROM BD_Whs w INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid=w.WhsID )'
	ELSE
		SET @Sqlw+=',_WhsType AS(
		SELECT wt2.WhsTypeID[typeid] 
		FROM BD_Whs_Type wt 
		INNER JOIN BD_Whs_Type wt2 ON wt2.[Path] LIKE wt.[Path]+''%'' 
		WHERE wt.WhsTypeID=@WhsTypeID AND wt2.Stt=1 
		GROUP BY wt2.WhsTypeID
		)
		,Whs AS(
		SELECT w.WhsID FROM BD_Whs w 
		INNER JOIN _WhsType ON _WhsType.typeid=w.WhsTypeID 
		INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid=w.WhsID 
		)'
ELSE
	IF @WhsTypeID<>0 AND @WhsTypeID<>1
		SET @Sqlw+=',_WhsType AS(
		SELECT wt2.WhsTypeID[typeid] 
		FROM BD_Whs_Type wt 
		INNER JOIN BD_Whs_Type wt2 ON wt2.[Path] LIKE wt.[Path]+''%'' 
		WHERE wt.WhsTypeID=@WhsTypeID AND wt2.Stt=1 
		GROUP BY wt2.WhsTypeID
		)
		,Whs AS(
		SELECT w.WhsID FROM BD_Whs w 
		INNER JOIN _WhsType ON _WhsType.typeid=w.WhsTypeID 
		)'

IF @GoodsTypeID<>0 AND @GoodsTypeID<>1 
BEGIN
	SET @Sqlg+=',_GoodsType AS(
	SELECT gt2.GoodsTypeID[typeid] 
	FROM BD_Goods_Type gt 
	INNER JOIN BD_Goods_Type gt2 ON gt2.[Path] LIKE gt.[Path]+''%'' 
	WHERE gt.GoodsTypeID=@GoodsTypeID AND gt2.Stt=1 
	GROUP BY gt2.GoodsTypeID
	)

	,Goods AS(
	SELECT g.GoodsID FROM BD_Goods g 
	INNER JOIN _GoodsType ON _GoodsType.typeid=g.GoodsTypeID '
	IF @SqlParam<>'' AND @GoodsID=0
		SET @Sqlg+='WHERE 1=1 ' + @SqlParam + ')'
	ELSE
		SET @Sqlg+=')'
END
ELSE
BEGIN
	IF @SqlParam<>'' AND @GoodsID=0 SET @Sqlg+=',Goods AS(SELECT g.GoodsID FROM BD_Goods g WHERE 1=1 ' + @SqlParam + ')'
END


IF @Sqlw<>'' SET @wStr = 'INNER JOIN Whs w ON w.WhsID=o.WhsID '
IF @Sqlg<>'' SET @gStr = 'INNER JOIN Goods g ON g.GoodsID=o.GoodsID '
/*权限使用公用方法*/
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @wStr += 'INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=o.WhsID '
SET @Sql = ';WITH BalanceData as (
	SELECT SUM(InBSQty)InBSQty,SUM(OutBSQty)OutBSQty,GoodsID,WhsID 
	FROM 
	( '+ @Sql + @Sqlw + @Sqlg + '
SELECT ISNULL(SUM(InBSQty),0)[InBSQty],ISNULL(SUM(OutBSQty),0)[OutBSQty] FROM BalanceData o '+@wStr+@gStr
IF @KtypeLimit = 0 SET @Sql = N' SELECT 0[InBSQty],0[OutBSQty] '

--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END

EXEC SP_EXECUTESQL @Sql,N'@BillStartDate DATETIME,@BillEndDate DATETIME,@WhsTypeID INT,@WhsID VARCHAR(100),@GoodsTypeID INT,@GoodsID INT
,@GoodsNoMatch INT,@GoodsNo VARCHAR(100),@GoodsNameMatch INT,@GoodsName VARCHAR(100),@SpecMatch INT,@Spec VARCHAR(100),@ModelMatch INT,@Model VARCHAR(100)
,@OperatorID INT,@AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100)',@BillStartDate,@BillEndDate,@WhsTypeID,@WhsID,@GoodsTypeID,@GoodsID
,@GoodsNoMatch,@GoodsNo,@GoodsNameMatch,@GoodsName,@SpecMatch,@Spec,@ModelMatch,@Model,@OperatorID,@AbbName,@Brand,@BarCode

END

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_SaleBackList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_SaleBackList]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2014-07-09
	描述：销售退货统计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SaleBackList]
(
	@PageNo INT=0,	
	@PageSize INT=0,	
	@DateType TINYINT=0,	/*日期类型 0-录单日期 1-制单日期 2-过账日期*/
	@BeginDate DATE,	/*开始日期*/
	@EndDate DATE,	/*结束日期*/
	@BTypeID VARCHAR(max)='',	/*往来单位*/
	@DeptID VARCHAR(max)='',	/*部门*/
	@ElyID VARCHAR(max)='',		/*经手人*/
	@CreatorID VARCHAR(MAX)='', /*制单人*/
	@WhsID VARCHAR(max)='',		/*仓库*/
	@GoodsNo VARCHAR(50)='',	/*商品编号*/
	@GoodsNoMatch BIT = 0,
	@GoodsName VARCHAR(100)='',		/*商品名称*/
	@GoodsNameMatch BIT = 0,
	@Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	@Summary VARCHAR(256)='',		/*摘要*/
	@SummaryMatch BIT = 0,
	@Description VARCHAR(100)='',		/*说明*/
	@DescriptionMatch BIT = 0,
	@Remark VARCHAR(100),	/*明细备注*/
	@RemarkMatch BIT = 0,
	@IsGift TINYINT = 0,		/*赠品状态*/
	@SumType TINYINT = 0,		/*汇总条件一:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员*/
	@SumLayer TINYINT = 0,		/*汇总层级一:1,2,3,4,5,汇总条件*/
	@OrderFirst VARCHAR(20) = '',		
	@AscFirst INT = 1, 
	@OrderAgain VARCHAR(20) = '',
	@AscAgain INT = 1,
	@OperatorID INT = 1, 
	@IsHistory BIT = 0,
	@IsContainDiscountTotal BIT = 0       -- 是否包含优惠金额
	
) 
AS

DECLARE @IndexSql NVARCHAR(MAX) = '', @DetailSql NVARCHAR(MAX) = '', @IndexTableSql NVARCHAR(MAX) = '',@DetailTableSql NVARCHAR(MAX) = ''
DECLARE @CreateTableSql NVARCHAR(MAX) = '', @SurceSql NVARCHAR(MAX) = '', @Sql NVARCHAR(MAX) = '', @Ret INT = 0
DECLARE @SumTable NVARCHAR(MAX) = '', @BDCol NVARCHAR(MAX)='', @ICol NVARCHAR(50)= '', @OrderCol NVARCHAR(200) = ''
DECLARE @Table NVARCHAR(MAX) = '', @RetTable NVARCHAR(MAX) = '', @HisTable NVARCHAR(MAX) = '', @RetHisTable NVARCHAR(MAX) = ''
DECLARE @TotalCol NVARCHAR(MAX) = '', @BaseCol NVARCHAR(50) = ''
DECLARE @DiscountCol NVARCHAR(MAX) = '',@DiscountColRet NVARCHAR(MAX) = '',@DiscountGroupCol NVARCHAR(MAX) = '',
		@DiscountBaseCol NVARCHAR(MAX) = '',@SurceCol NVARCHAR(MAX) = '',@SurceGroupCol NVARCHAR(MAX) = '',
		@DiscountSumCol NVARCHAR(MAX) = ''

EXEC @Ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
	SET @DetailTableSql = ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =I.WhsID'

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
	SET @IndexTableSql = ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID'

IF @DateType = 0 
	SET @IndexSql += ' WHERE I.BillDate BETWEEN @BeginDate AND @EndDate'
ELSE IF @DateType = 1 
	SET @IndexSql += ' WHERE I.CreateTime BETWEEN @BeginDate AND @EndDate'
ELSE IF @DateType = 2
	SET @IndexSql += ' WHERE I.PosTime BETWEEN @BeginDate AND @EndDate'


--按往来单位汇总，无任何往来单位权限/按仓库汇总，无任何仓库权限
IF (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0)
OR (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0)  
BEGIN
	SET @IndexSql = ' AND 1=2'
END

-- 是否包含优惠金额
IF @IsContainDiscountTotal = 1
BEGIN
	SET @DiscountCol += ',I.Privilege AS SaleDiscountTotal, 0 AS BackDiscountTotal'
	SET @DiscountColRet += ',0 AS SaleDiscountTotal, I.Privilege AS BackDiscountTotal'
	SET @DiscountGroupCol += ',I.Privilege'
	SET @DiscountBaseCol += ',SUM(SaleDiscountTotal) SaleDiscountTotal,SUM(BackDiscountTotal) BackDiscountTotal'
	SET @SurceCol += ',SaleDiscountTotal,(SUM(SaleTotal) - SaleDiscountTotal) SaleTotalByDiscount,
						BackDiscountTotal,(SUM(BackTotal) - BackDiscountTotal) BackTotalByDiscount'
	SET @SurceGroupCol += ',SaleDiscountTotal,BackDiscountTotal'
	SET @DiscountSumCol += ',SUM(SaleDiscountTotal)[SaleDiscountTotal],SUM(SaleTotalByDiscount)[SaleTotalByDiscount],
							SUM(BackDiscountTotal)[BackDiscountTotal],SUM(BackTotalByDiscount)[BackTotalByDiscount]'
END

IF @BTypeID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     SET @IndexTableSql += ' INNER JOIN @BType B ON I.BTypeID=B.BTypeID '
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
 SET @IndexTableSql +=' INNER JOIN @DType D ON I.DeptID=D.DeptID '    
END

IF @ElyID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
 SET @IndexTableSql +=' INNER JOIN @EType E ON I.ElyID=E.ElyID '    
END

IF @CreatorID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @Creator Table(CreatorID INT)   
     INSERT  INTO @Creator SELECT typeid AS CreatorID  FROM dbo.UF_OT_Split_Int(@CreatorID,'','')   
     '  
 SET @IndexTableSql +=' INNER JOIN @Creator C ON I.Creator=C.CreatorID '    
END

IF @WhsID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @Whs Table(WhsID INT)   
     INSERT  INTO @Whs SELECT typeid AS WhsID  FROM dbo.UF_OT_Split_Int(@WhsID,'','')   
     '
     SET @IndexTableSql += ' INNER JOIN @Whs K ON I.WhsID=K.WhsID '
END

IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
BEGIN
	SET @DetailTableSql += ' INNER JOIN BD_Goods BG ON Detail.GoodsID = BG.GoodsID '
END	

--IF @BarCode <> ''
--BEGIN 
--	SET @DetailTableSql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = Detail.GoodsID and pri.UnitID = 1 '
--END

IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 1 
		SET @DetailSql += ' AND BG.GoodsNo = @GoodsNo'
	ELSE
		SET @DetailSql += ' AND BG.GoodsNo Like ''%''+@GoodsNo+''%'' ' 
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 1 
		SET @DetailSql += ' AND GoodsName = @GoodsName'
	ELSE
		SET @DetailSql += ' AND GoodsName Like ''%''+@GoodsName+''%'' ' 
END

--商品型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @DetailSql += N' AND BG.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @DetailSql += N' AND BG.Model = @Model ' 
END   
--商品简名    
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @DetailSql += N' AND BG.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @DetailSql += N' AND BG.GoodsAbbName = @GoodsAbbName ' 
END       
--商品品牌
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @DetailSql += N' AND BG.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @DetailSql += N' AND BG.Brand = @Brand ' 
END
--商品规格    
IF @Spec <> ''        
BEGIN 
   IF @SpecMatch = 0
	   SET @DetailSql += N' AND BG.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @DetailSql += N' AND BG.Spec = @Spec '  
END
--商品条码
IF @BarCode <> ''      
BEGIN 
   IF @BarCodeMatch = 0
	   SET @DetailSql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=Detail.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @DetailSql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=Detail.GoodsID)'
END


IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 1 
		SET @IndexSql += ' AND Summary = @Summary'
	ELSE
		SET @IndexSql += ' AND Summary Like ''%''+@Summary+''%'' ' 
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 1 
		SET @IndexSql += ' AND Description = @Description'
	ELSE
		SET @IndexSql += ' AND Description Like ''%''+@Description+''%'' ' 
END
IF @Remark <> ''
BEGIN
	IF @RemarkMatch = 1 
		SET @DetailSql += ' AND Detail.Remark = @Remark'
	ELSE
		SET @DetailSql += ' AND Detail.Remark Like ''%''+@Remark+''%'' ' 
END

IF @IsGift <> 0
BEGIN
	IF @IsGift = 1
		SET @DetailSql += ' AND Gift = 1'
	ELSE 
		SET @DetailSql += ' AND Gift = 0'
END

IF @IsContainDiscountTotal =1
BEGIN
	SET @TotalCol = ', SUM(SaleQty) SaleQty, SUM(SaleTotal) SaleTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal
					, CASE WHEN (SUM(SaleQty) = 0) OR (SUM(BackQty) = 0) THEN 0 ELSE CONVERT(FLOAT,SUM(BackQty)/SUM(SaleQty)*100) END AS BackRate
					, SUM(SaleQty) - SUM(BackQty) AS OutStockQty, (SUM(SaleTotal) - SaleDiscountTotal) - (SUM(BackTotal) - BackDiscountTotal) AS OutStockTotal'
END
ELSE
BEGIN
	SET @TotalCol = ', SUM(SaleQty) SaleQty, SUM(SaleTotal) SaleTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal
					, CASE WHEN (SUM(SaleQty) = 0) OR (SUM(BackQty) = 0) THEN 0 ELSE CONVERT(FLOAT,SUM(BackQty)/SUM(SaleQty)*100) END AS BackRate
					, SUM(SaleQty) - SUM(BackQty) AS OutStockQty, SUM(SaleTotal) - SUM(BackTotal) AS OutStockTotal'
END

IF @SumType = 1 --按商品汇总
BEGIN
	SET @ICol = 'Detail.GoodsID'
	SET @BaseCol = 'GoodsID'
	IF @SumLayer = 6 
	BEGIN
		SELECT  @SumTable = '
				INNER JOIN BD_Goods BD ON PD.GoodsID = BD.GoodsID
				INNER JOIN BD_Goods_Price pri ON PD.GoodsID = pri.GoodsID and pri.UnitID = 1
				GROUP BY BD.GoodsID, BD.GoodsNo, BD.GoodsName, BD.Model, BD.GoodsAbbName, BD.Brand, BD.Spec, pri.BarCode',
				@BDCol = 'BD.GoodsID AS BaseID, BD.GoodsNo, BD.GoodsName, BD.Model, BD.GoodsAbbName, BD.Brand, BD.Spec, pri.BarCode '
	END ELSE
	BEGIN
		SET @CreateTableSql += '
			SELECT * INTO #BaseSummary FROM dbo.UF_BD_BaseSummary(''PTYPE'', @SumLayer) 
		'
		SELECT  @SumTable = ' 
				INNER JOIN BD_Goods BG ON PD.GoodsID = BG.GoodsID
				INNER JOIN BD_Goods_Price pri ON PD.GoodsID = pri.GoodsID  and pri.UnitID = 1
				INNER JOIN #BaseSummary BS ON BG.GoodsTypeID = BS.ParID
				INNER JOIN BD_Goods_Type BD ON BS.BaseID = BD.GoodsTypeID 
				GROUP BY BS.BaseID, BD.TypeCode, BD.TypeName', 
				@BDCol = 'BS.BaseID ,BD.TypeCode AS PCode, BD.TypeName AS PName '
	END
END ELSE
IF @SumType = 2 --按往来单位汇总
BEGIN
	SET @ICol = 'I.BTypeID'
	SET @BaseCol = 'BTypeID'
	IF @SumLayer = 6 
	BEGIN
		SELECT	
				@SumTable = '
				INNER JOIN BD_Btype BD ON PD.BTypeID = BD.BTypeID
				GROUP BY BD.BTypeID, BD.BTypeCode, BD.BTypeName', 
				@BDCol = 'BD.BTypeID AS BaseID, BD.BTypeCode, BD.BTypeName '
	END ELSE
	BEGIN
		SET @CreateTableSql += '
			SELECT * INTO #BaseSummary FROM dbo.UF_BD_BaseSummary(''BTYPE'', @SumLayer) 
		'
		SELECT	@SumTable = '
				INNER JOIN BD_Btype BG ON PD.BTypeID = BG.BTypeID
				INNER JOIN #BaseSummary BS ON BG.BtypeTypeID = BS.ParID
				INNER JOIN BD_BType_Type BD ON BS.BaseID = BD.BtypeTypeID
				GROUP BY BS.BaseID, BD.TypeCode, BD.TypeName', 
				@BDCol = 'BS.BaseID, BD.TypeCode AS BCode, BD.TypeName AS BName'
	END		
END ELSE
IF @SumType = 3 --按仓库汇总
BEGIN
	SET @ICol = 'I.WhsID'
	SET @BaseCol = 'WhsID'
	IF @SumLayer = 6
	BEGIN
		SELECT	@SumTable = '
				INNER JOIN BD_Whs BD ON PD.WhsID = BD.WhsID
				GROUP BY BD.WhsID, BD.WhsNO, BD.WhsName', 
				@BDCol = 'BD.WhsID AS BaseID, BD.WhsNO, BD.WhsName'
	END ELSE
	BEGIN
		SET @CreateTableSql += '
			SELECT * INTO #BaseSummary FROM dbo.UF_BD_BaseSummary(''KTYPE'', @SumLayer) 
		'
		SELECT	@SumTable = '
				INNER JOIN BD_Whs BG ON PD.WhsID = BG.WhsID
				INNER JOIN #BaseSummary BS ON BG.WhsTypeID = BS.ParID
				INNER JOIN BD_Whs_Type BD ON BS.BaseID = BD.WhsTypeID
				GROUP BY BS.BaseID, BD.TypeCode, BD.TypeName', 
				@BDCol = 'BS.BaseID, BD.TypeCode AS KCode, BD.TypeName AS KName'
	END
END ELSE
IF @SumType = 4 --按地区汇总
BEGIN
	SET @CreateTableSql += '
			SELECT * INTO #BaseSummary FROM dbo.UF_BD_BaseSummary(''AREA'', @SumLayer) 
		'
	SELECT	@ICol = 'I.BTypeID',
			@BaseCol = 'BTypeID', 
			@SumTable = '
				INNER JOIN BD_Btype BG ON PD.BTypeID = BG.BTypeID
				INNER JOIN #BaseSummary BS ON BG.AreaID = BS.ParID
				INNER JOIN (SELECT AreaID, AreaNO, AreaName FROM BD_Area 
							UNION ALL
							SELECT 0 AS AreaID, '''' AS AreaNO, ''其他'' AS AreaName
							)BD ON BS.BaseID = BD.AreaID
				GROUP BY BS.BaseID, BD.AreaNO, BD.AreaName', 
				@BDCol = 'BS.BaseID, BD.AreaNO , BD.AreaName '
END
IF @SumType = 5 --按部门汇总
BEGIN
	SET	@ICol = 'I.DeptID'
	SET @BaseCol = 'DeptID'
	IF @SumLayer = 5
	BEGIN
		SELECT	@SumTable = '
				INNER JOIN BD_Dept BD ON PD.DeptID = BD.DeptID
				GROUP BY BD.DeptID, BD.DeptCode, BD.DeptName', 
				@BDCol = 'BD.DeptID, BD.DeptCode, BD.DeptName'
	END ELSE
	BEGIN
		SET @CreateTableSql += '
			SELECT * INTO #BaseSummary FROM dbo.UF_BD_BaseSummary(''DTYPE'', @SumLayer) 
		'
		SELECT  @SumTable = '
				INNER JOIN #BaseSummary BS ON BS.ParID= PD.DeptID
				INNER JOIN BD_Dept BD ON BS.BaseID = BD.DeptID	
				GROUP BY BS.BaseID, BD.DeptCode, BD.DeptName', 
				@BDCol = 'BS.BaseID,BD.DeptCode, BD.DeptName'
	END
END ELSE
IF @SumType = 6 --按经手人汇总
BEGIN
	SELECT	@ICol = 'I.ElyID',
			@BaseCol = 'ElyID',
			@SumTable = '
			INNER JOIN BD_Employee BD ON PD.ElyID = BD.ElyID
			GROUP BY BD.ElyID, BD.ElyCode, BD.ElyName', 
			@BDCol = 'BD.ElyID AS BaseID, BD.ElyCode, BD.ElyName'
END

IF @SumType = 7 --按制单人汇总
BEGIN
	SELECT @ICol = 'I.Creator',
		   @BaseCol = 'Creator',
		   @SumTable = '
		   INNER JOIN BD_Employee BD ON PD.Creator = BD.ElyID
		   GROUP BY BD.ElyID, BD.ElyCode, BD.ElyName',
		   @BDCol = ' BD.ElyID AS BaseID, BD.ElyCode AS OperatorCode, BD.ElyName AS OperatorName'
END

SET @IndexSql += ' AND Red = 0 AND IsDraft = 0'

SET @Table = '
	  SELECT '+ @ICol + @DiscountCol +', ISNULL(SUM(Detail.BSQty), 0) SaleQty, ISNULL(SUM(Detail.DiscTotal), 0) SaleTotal, 0 AS BackQty, 0 AS BackTotal 
	  FROM PD_SellBill I INNER JOIN PD_SellDetail Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol

	SET @RetTable = '
	  UNION ALL
	  SELECT '+ @ICol + @DiscountColRet +', 0 AS SaleQty, 0 AS SaleTotal, ISNULL(SUM(BSQty), 0) BackQty, ISNULL(SUM(Detail.DiscTotal), 0) BackTotal 
	  FROM PD_SellRetBill I INNER JOIN PD_SellRetDetail Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol

IF @IsHistory = 1
BEGIN
	SET @HisTable = '
	  UNION ALL
	  SELECT '+ @ICol + @DiscountCol +', ISNULL(SUM(Detail.BSQty), 0) SaleQty, ISNULL(SUM(Detail.DiscTotal), 0) SaleTotal, 0 AS BackQty, 0 AS BackTotal 
	  FROM PD_SellBill_His I INNER JOIN PD_SellDetail_His Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol 
	  
	SET @RetHisTable = '
	  UNION ALL
	  SELECT '+ @ICol + @DiscountColRet +', 0 AS SaleQty, 0 AS SaleTotal, ISNULL(SUM(BSQty), 0) BackQty, ISNULL(SUM(Detail.DiscTotal), 0) BackTotal 
	  FROM PD_SellRetBill_His I INNER JOIN PD_SellRetDetail_His Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql +' 
	  GROUP BY '+ @ICol + @DiscountGroupCol
END

IF @OrderFirst <> ''
BEGIN
	IF @AscFirst = 2 SET @OrderCol = @OrderFirst+' DESC' ELSE SET @OrderCol = @OrderFirst +' ASC'
END
IF @OrderAgain <> ''
BEGIN
	IF @OrderCol <> '' SET @OrderCol +=', '
	IF @AscAgain = 2 SET @OrderCol += @OrderAgain+' DESC' ELSE SET @OrderCol += @OrderAgain +' ASC'
END

SET @SurceSql +='
	SELECT	'+ @BDCol + @TotalCol + @SurceCol +'
	FROM 
	(	SELECT '+ @BaseCol + @DiscountBaseCol +', SUM(SaleQty) SaleQty, SUM(SaleTotal) SaleTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal
		FROM ( 
				'+@Table + @RetTable + @HisTable + @RetHisTable+'
			) I GROUP BY '+ @BaseCol +'
	) PD 
	'+ @SumTable + @SurceGroupCol

SET @Sql = @CreateTableSql + '
	;WITH PagingData AS 
	(
		'+ @SurceSql +'
	)

   SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+ @OrderCol +') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	
	'

PRINT(@sql)
EXEC sp_executesql @sql,
N'@PageNo INT, @PageSize INT,@BeginDate DATE,@EndDate DATE,@BTypeID VARCHAR(MAX),@DeptID VARCHAR(MAX),@ElyID VARCHAR(MAX),@CreatorID VARCHAR(MAX),@WhsID VARCHAR(MAX),@GoodsNo VARCHAR(50),@GoodsName VARCHAR(100),@Summary VARCHAR(256),@Description VARCHAR(100), @Remark VARCHAR(100), @SumLayer INT, @OperatorID INT
,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',
@PageNo, @PageSize,@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID, @CreatorID, @WhsID,@GoodsNo,@GoodsName,@Summary,@Description, @Remark, @SumLayer, @OperatorID
,@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch 

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_SaleBackListSum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_SaleBackListSum]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：雷洋
	日期：2015-10-25
	描述：销售退货统计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SaleBackListSum]
(
	@PageNo INT=0,	
	@PageSize INT=0,	
	@DateType TINYINT=0,	/*日期类型 0-录单日期 1-制单日期 2-过账日期*/
	@BeginDate DATE,	/*开始日期*/
	@EndDate DATE,	/*结束日期*/
	@BTypeID VARCHAR(max)='',	/*往来单位*/
	@DeptID VARCHAR(max)='',	/*部门*/
	@ElyID VARCHAR(max)='',		/*经手人*/
	@CreatorID VARCHAR(MAX)='', /*制单人*/
	@WhsID VARCHAR(max)='',		/*仓库*/
	@GoodsNo VARCHAR(50)='',	/*商品编号*/
	@GoodsNoMatch BIT = 0,
	@GoodsName VARCHAR(100)='',		/*商品名称*/
	@GoodsNameMatch BIT = 0,
	@Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	@Summary VARCHAR(256)='',		/*摘要*/
	@SummaryMatch BIT = 0,
	@Description VARCHAR(100)='',		/*说明*/
	@DescriptionMatch BIT = 0,
	@Remark VARCHAR(100),	/*明细备注*/
	@RemarkMatch BIT = 0,
	@IsGift TINYINT = 0,		/*赠品状态*/	
	@OperatorID INT = 1, 
	@IsHistory BIT = 0,
	@IsContainDiscountTotal BIT = 0       -- 是否包含优惠金额
	
) 
AS

DECLARE @IndexSql NVARCHAR(MAX) = '', @DetailSql NVARCHAR(MAX) = '', @IndexTableSql NVARCHAR(MAX) = '',@DetailTableSql NVARCHAR(MAX) = ''
DECLARE @CreateTableSql NVARCHAR(MAX) = '', @SurceSql NVARCHAR(MAX) = '', @Sql NVARCHAR(MAX) = '', @Ret INT = 0 
DECLARE @Table NVARCHAR(MAX) = '', @RetTable NVARCHAR(MAX) = '', @HisTable NVARCHAR(MAX) = '', @RetHisTable NVARCHAR(MAX) = ''
DECLARE @TotalCol NVARCHAR(MAX) = ''
DECLARE @DiscountCol NVARCHAR(MAX) = '',@DiscountColRet NVARCHAR(MAX) = '',@DiscountBaseCol NVARCHAR(MAX) = '',
		@SurceCol NVARCHAR(MAX) = ''

EXEC @Ret= UP_OT_CheckHistoryTime  @BillStartDate=@BeginDate,@IsHistory=@IsHistory
IF @Ret<>0
	RETURN

IF dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 1
	SET @DetailTableSql = ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =I.WhsID'

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
	SET @IndexTableSql = ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID'

IF @DateType = 0 
	SET @IndexSql += ' WHERE I.BillDate BETWEEN @BeginDate AND @EndDate'
ELSE IF @DateType = 1 
	SET @IndexSql += ' WHERE I.CreateTime BETWEEN @BeginDate AND @EndDate'
ELSE IF @DateType = 2
	SET @IndexSql += ' WHERE I.PosTime BETWEEN @BeginDate AND @EndDate'


--按往来单位汇总，无任何往来单位权限/按仓库汇总，无任何仓库权限
IF (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0)
OR (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0)  
BEGIN
	SET @IndexSql = ' AND 1=2'
END

-- 是否包含优惠金额
IF @IsContainDiscountTotal = 1
BEGIN
	SET @DiscountCol += ',SUM(I.Privilege) AS SaleDiscountTotal, 0 AS BackDiscountTotal'
	SET @DiscountColRet += ',0 AS SaleDiscountTotal, SUM(I.Privilege) AS BackDiscountTotal'
	SET @DiscountBaseCol += ',SUM(SaleDiscountTotal) SaleDiscountTotal,SUM(BackDiscountTotal) BackDiscountTotal'
	SET @SurceCol += ',SUM(SaleDiscountTotal)SaleDiscountTotal,(SUM(SaleTotal) - SUM(SaleDiscountTotal)) SaleTotalByDiscount,
						SUM(BackDiscountTotal)BackDiscountTotal,(SUM(BackTotal) - SUM(BackDiscountTotal)) BackTotalByDiscount'
END

IF @BTypeID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     SET @IndexTableSql += ' INNER JOIN @BType B ON I.BTypeID=B.BTypeID '
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
 SET @IndexTableSql +=' INNER JOIN @DType D ON I.DeptID=D.DeptID '    
END

IF @ElyID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
 SET @IndexTableSql +=' INNER JOIN @EType E ON I.ElyID=E.ElyID '    
END

IF @CreatorID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @Creator Table(CreatorID INT)   
     INSERT  INTO @Creator SELECT typeid AS CreatorID  FROM dbo.UF_OT_Split_Int(@CreatorID,'','')   
     '  
 SET @IndexTableSql +=' INNER JOIN @Creator C ON I.Creator=C.CreatorID '    
END

IF @WhsID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @Whs Table(WhsID INT)   
     INSERT  INTO @Whs SELECT typeid AS WhsID  FROM dbo.UF_OT_Split_Int(@WhsID,'','')   
     '
     SET @IndexTableSql += ' INNER JOIN @Whs K ON I.WhsID=K.WhsID '
END

IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
BEGIN
	SET @DetailTableSql += ' INNER JOIN BD_Goods BG ON Detail.GoodsID = BG.GoodsID '
END	

--IF @BarCode <> ''
--BEGIN 
--	SET @DetailTableSql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = Detail.GoodsID and pri.UnitID = 1 '
--END

IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 1 
		SET @DetailSql += ' AND GoodsNo = @GoodsNo'
	ELSE
		SET @DetailSql += ' AND GoodsNo Like ''%''+@GoodsNo+''%'' ' 
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 1 
		SET @DetailSql += ' AND GoodsName = @GoodsName'
	ELSE
		SET @DetailSql += ' AND GoodsName Like ''%''+@GoodsName+''%'' ' 
END

--商品型号
IF @Model <> ''      
BEGIN 
   IF @ModelMatch = 0
	   SET @DetailSql += N' AND BG.Model LIKE ''%'' + @Model +''%'''
   ELSE IF @ModelMatch = 1
	   SET @DetailSql += N' AND BG.Model = @Model ' 
END   
--商品简名    
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @DetailSql += N' AND BG.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @DetailSql += N' AND BG.GoodsAbbName = @GoodsAbbName ' 
END       
--商品品牌
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @DetailSql += N' AND BG.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @DetailSql += N' AND BG.Brand = @Brand ' 
END
--商品规格    
IF @Spec <> ''        
BEGIN 
   IF @SpecMatch = 0
	   SET @DetailSql += N' AND BG.Spec LIKE ''%'' + @Spec +''%'''
   ELSE IF @SpecMatch = 1
	   SET @DetailSql += N' AND BG.Spec = @Spec '  
END
--商品条码
IF @BarCode <> ''      
BEGIN 
   IF @BarCodeMatch = 0
	   SET @DetailSql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=Detail.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @DetailSql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=Detail.GoodsID)'
END


IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 1 
		SET @IndexSql += ' AND Summary = @Summary'
	ELSE
		SET @IndexSql += ' AND Summary Like ''%''+@Summary+''%'' ' 
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 1 
		SET @IndexSql += ' AND Description = @Description'
	ELSE
		SET @IndexSql += ' AND Description Like ''%''+@Description+''%'' ' 
END
IF @Remark <> ''
BEGIN
	IF @RemarkMatch = 1 
		SET @DetailSql += ' AND Detail.Remark = @Remark'
	ELSE
		SET @DetailSql += ' AND Detail.Remark Like ''%''+@Remark+''%'' ' 
END

IF @IsGift <> 0
BEGIN
	IF @IsGift = 1
		SET @DetailSql += ' AND Gift = 1'
	ELSE 
		SET @DetailSql += ' AND Gift = 0'
END

SET @TotalCol = ' SUM(SaleQty) SaleQty, SUM(SaleTotal) SaleTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal				
				, SUM(SaleQty) - SUM(BackQty) AS OutStockQty, SUM(SaleTotal) - SUM(BackTotal) AS OutStockTotal'


SET @IndexSql += ' AND Red = 0 AND IsDraft = 0'

SET @Table = '
	  SELECT  ISNULL(SUM(Detail.BSQty), 0) SaleQty, ISNULL(SUM(Detail.DiscTotal), 0) SaleTotal, 0 AS BackQty, 0 AS BackTotal 
	  '+ @DiscountCol +'
	  FROM PD_SellBill I INNER JOIN PD_SellDetail Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql

	SET @RetTable = '
	  UNION ALL
	  SELECT  0 AS SaleQty, 0 AS SaleTotal, ISNULL(SUM(BSQty), 0) BackQty, ISNULL(SUM(Detail.DiscTotal), 0) BackTotal 
	  '+ @DiscountColRet +'
	  FROM PD_SellRetBill I INNER JOIN PD_SellRetDetail Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql

IF @IsHistory = 1
BEGIN
	SET @HisTable = '
	  UNION ALL
	  SELECT ISNULL(SUM(Detail.BSQty), 0) SaleQty, ISNULL(SUM(Detail.DiscTotal), 0) SaleTotal, 0 AS BackQty, 0 AS BackTotal 
	  '+ @DiscountCol +'
	  FROM PD_SellBill_His I INNER JOIN PD_SellDetail_His Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql 
	  
	SET @RetHisTable = '
	  UNION ALL
	  SELECT 0 AS SaleQty, 0 AS SaleTotal, ISNULL(SUM(BSQty), 0) BackQty, ISNULL(SUM(Detail.DiscTotal), 0) BackTotal 
	  '+ @DiscountColRet +'
	  FROM PD_SellRetBill_His I INNER JOIN PD_SellRetDetail_His Detail ON I.BillNo = Detail.BillNo '
	  + @IndexTableSql + @DetailTableSql + @IndexSql + @DetailSql 
END

SET @SurceSql +='
	SELECT	' + @TotalCol + @SurceCol +'
	FROM 
	(	SELECT SUM(SaleQty) SaleQty, SUM(SaleTotal) SaleTotal, SUM(BackQty) BackQty, SUM(BackTotal) BackTotal
		'+ @DiscountBaseCol +'
		FROM ( 
				'+@Table + @RetTable + @HisTable + @RetHisTable+'
			) I
	) PD 
	'

SET @Sql = @CreateTableSql + '
	;WITH PagingData AS 
	(
		'+ @SurceSql +'
	)

   SELECT * from PagingData
	'

--PRINT(@sql)
EXEC sp_executesql @sql,
N'@PageNo INT, @PageSize INT,@BeginDate DATE,@EndDate DATE,@BTypeID VARCHAR(MAX),@DeptID VARCHAR(MAX),@ElyID VARCHAR(MAX),@CreatorID VARCHAR(MAX),@WhsID VARCHAR(MAX),@GoodsNo VARCHAR(50),@GoodsName VARCHAR(100),@Summary VARCHAR(256),@Description VARCHAR(100), @Remark VARCHAR(100),  @OperatorID INT
,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',
@PageNo, @PageSize,@BeginDate,@EndDate,@BTypeID,@DeptID,@ElyID, @CreatorID, @WhsID,@GoodsNo,@GoodsName,@Summary,@Description, @Remark, @OperatorID
,@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch 

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：查询销售明细
	××××××××××××××××××
	修改：sunzhiyuan
	日期：2015-3-31
	修改描述：62行：取消归档数据判断
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SaleDetailsSum]
(
	--@DateType INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@SaleBill Int = 1,
	@SaleBackBill Int = 1,
	@BTypeID VARCHAR(max)='',
	@DeptID VARCHAR(max)='',
	@ElyID VARCHAR(max)='',
	@WhsID VARCHAR(max)='',
	@CreatorID VARCHAR(max)='',
	@BillCode VARCHAR(100)='',
	@BillCodeMatch INT=0,
	@FullName VARCHAR(100)='',
	@UserCodeMatch INT=0,
	@UserCode VARCHAR(100)='',
	@FullNameMatch INT=0,
	@Model VARCHAR(50) = '',               --型号
	@ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '',        --简名
	@GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',               --品牌
	@BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',                --规格
	@SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',             --条码
	@BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	@Ppt1 VARCHAR(100)='',
	@Ppt1Match INT=0,
	@Ppt2 VARCHAR(100)='',
	@Ppt2Match INT=0,
	@Summary VARCHAR(256)='',
	@SummaryMatch INT=0,
	@Description VARCHAR(100)='',
	@DescriptionMatch INT=0,
	@Remark VARCHAR(100)='',
	@RemarkMatch INT=0,
	@GiftFlag INT=0,
	@IsRedFlag Int = 0,
	@OperatorID INT,
	@ClassID1 Int = 0,
	@ClassType1 Int = 0,
	@ClaseFlag1 Int = 0, 
	@ClassID2 Int = 0,
	@ClassType2 Int = 0,
	@ClaseFlag2 Int = 0,
	@isHistory INT=0,				--是否包含历史数据
	@ClickFlag Int =0,
	@GoodsDataFile1 varchar(100) ='', --商品自定义字段1
	@GoodsDataFile2 varchar(100) ='', --商品自定义字段2
	@GoodsDataFile3 varchar(100) ='', --商品自定义字段3
	@GoodsDataFile4 varchar(100) ='', --商品自定义字段4
	@GoodsDataFile5 varchar(100) ='', --商品自定义字段5
	@GoodsCFlag1 int = 0, --商品自定义字段1选中标识
	@GoodsCFlag2 int = 0, --商品自定义字段2选中标识
	@GoodsCFlag3 int = 0, --商品自定义字段3选中标识
	@GoodsCFlag4 int = 0, --商品自定义字段4选中标识
	@GoodsCFlag5 int = 0, --商品自定义字段5选中标识
	@BtypeDataFile1 varchar(100) ='', --往来单位自定义字段1
	@BtypeDataFile2 varchar(100) ='', --往来单位自定义字段2
	@BtypeDataFile3 varchar(100) ='', --往来单位自定义字段3
	@BtypeDataFile4 varchar(100) ='', --往来单位自定义字段4
	@BtypeDataFile5 varchar(100) ='',  --往来单位自定义字段5	
	@BtypeCFlag1 int = 0, --往来单位自定义字段1选中标识
	@BtypeCFlag2 int = 0, --往来单位自定义字段2选中标识
	@BtypeCFlag3 int = 0, --往来单位自定义字段3选中标识
	@BtypeCFlag4 int = 0, --往来单位自定义字段4选中标识
	@BtypeCFlag5 int = 0 --往来单位自定义字段5选中标识
)

AS
SET NOCOUNT ON

--DECLARE @re int 
--execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
--if( @re=1 )return @re;

DECLARE @sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',@SqlMatch varchar(max)='',@SqlWhs nvarchar(max),
		@SqlDept nvarchar(max),@SqlEly nvarchar(max),@SqlPost nvarchar(max),@SqlUnit nvarchar(2000),
		@SqlUnit1 nvarchar(1000),@SqlUnit2 nvarchar(1000),@SqlUnit3 nvarchar(1000),@SqlBtype nvarchar(max),
		@SqlCreator nvarchar(max),@SqlIn nvarchar(Max),@SqlOut nVarchar(max),@OrderName nvarchar(100),
		@OrderColumn varchar(max)='',@OrderTable varchar(max)='',@GoodsTable varchar(max)='',@GoodsMath varchar(max)='', 
		@SqlGoods Nvarchar(1000),@SqlPpt1 nvarchar(1000),@SqlPpt2 nvarchar(1000), @LimitKtypeSql NVARCHAR(MAX) = '', @LimitBtypeSql NVARCHAR(MAX) = '',@RedStr varchar(100)='',@Red varchar(100)='',
		@SqlClass1 varchar(500)='',@SqlClass2 varchar(500)='',@ExcSql Nvarchar(Max)='',@DecParam NVARCHAR(max),@param NVARCHAR(max),@BtypeLimit INT=0,@KtypeLimit INT=0 
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF @KtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
End
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) insert into @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID1,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON bill.DeptID=D.TypeID '
END	
IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) insert into @EType Select typeid from dbo.UF_OT_Split_Int(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON bill.ElyID=E.TypeID ' 
END	
IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) insert into @CreateEType Select typeid from dbo.UF_OT_Split_Int(@CreatorID,'','') '
	SET @SqlTable+=' INNER JOIN @CreateEType CE ON bill.Creator=CE.TypeID ' 
END	
IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
	SET @SqlTable+=' INNER JOIN @KType W ON bill.WhsID=W.TypeID ' 
END	
if(@Summary <> '')
	Set @SqlMatch += ' And Summary ' + case @SummaryMatch when 0 then ' Like ''%''+@Summary+''%''' Else ' =@Summary ' End
if(@Description <> '')
	Set @SqlMatch += ' And Description ' + case @DescriptionMatch when 0 then ' Like ''%''+@Description+''%''' Else ' =@Description ' END
if(@Remark <> '')
	Set @SqlMatch += ' And Remark ' + case @RemarkMatch when 0 then ' Like ''%''+@Remark+''%''' Else ' =@Remark ' END
if(@BillCode <> '')
	Set @SqlMatch += ' And BillCode ' + case @BillCodeMatch when 0 then ' Like ''%''+@BillCode+''%''' Else ' =@BillCode ' END	
if(@FullName <> '' or @UserCode <> '' or @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> '')
Begin
	if(@FullName <> '')
		Set @GoodsMath += ' And G.GoodsName ' + case @FullNameMatch when 0 then ' Like ''%''+@FullName+''%''' Else ' =@FullName ' END
	if(@UserCode <> '')
		Set @GoodsMath += ' And G.GoodsNo ' + case @UserCodeMatch when 0 then ' Like ''%''+@UserCode+''%''' Else ' =@UserCode ' END
	--商品型号
	IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @GoodsMath += N' AND G.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @GoodsMath += N' AND G.Model = @Model ' 
	END   
	--商品简名    
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @GoodsMath += N' AND G.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @GoodsMath += N' AND G.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @GoodsMath += N' AND G.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @GoodsMath += N' AND G.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
	   IF @SpecMatch = 0
		   SET @GoodsMath += N' AND G.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @GoodsMath += N' AND G.Spec = @Spec '  
	END
	
	Select @GoodsTable += ' And exists(select 1 from BD_GOODS G Where detail.GoodsID = G.GoodsID '+@GoodsMath+')'
End

--商品条码
	IF @BarCode <> ''      
	BEGIN 
		SET @SqlTable += N' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID AND pri.UnitID = 1 '
	   IF @BarCodeMatch = 0
		   SET @SqlMatch += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	   ELSE IF @BarCodeMatch = 1
		   SET @SqlMatch += N' AND pri.BarCode = @BarCode ' 
	END 

if(@Ppt1 <> '' or (@ClickFlag = 1 and  @Ppt1Match = 1))
BEGIN
	if(@Ppt1 <> '')
	Begin
		Set @GoodsMath = ' And GP1.Value ' + case @Ppt1Match when 0 then ' Like ''%''+@Ppt1+''%''' Else ' =@Ppt1 ' END
		Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt1 GP1 Where detail.Ppt1ID = GP1.Ppt1ID '+@GoodsMath+')'
	End
	Else
		Select @GoodsTable += ' And Ppt1ID = 0 ' 
END
if(@Ppt2 <> '' or (@ClickFlag = 1 and  @Ppt2Match = 1))
BEGIN
	if(@Ppt2 <> '')
	Begin
		Set @GoodsMath = ' And GP2.Value ' + case @Ppt2Match when 0 then ' Like ''%''+@Ppt2+''%''' Else ' =@Ppt2 ' END	
		Select @GoodsTable += ' And exists(select 1 from BD_Goods_Ppt2 GP2 Where detail.Ppt2ID = GP2.Ppt2ID '+@GoodsMath+')'
	End
	Else
		Select @GoodsTable += ' And Ppt2ID = 0 ' 
END

--自定义字段汇总查询明细
IF(@GoodsDataFile1 <> '' OR (@ClickFlag = 1 And @GoodsCFlag1 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG1 ON detail.GoodsID = BG1.BaseID '
	Set @SqlMatch += ' And BG1.CustVal1 = @GoodsDataFile1 '
END
IF(@GoodsDataFile2 <> '' OR (@ClickFlag = 1 And @GoodsCFlag2 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG2 ON detail.GoodsID = BG2.BaseID '
	Set @SqlMatch += ' And BG2.CustVal2 = @GoodsDataFile2 '
END
IF(@GoodsDataFile3 <> '' OR (@ClickFlag = 1 And @GoodsCFlag3 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG3 ON detail.GoodsID = BG3.BaseID '
	Set @SqlMatch += ' And BG3.CustVal3 = @GoodsDataFile3 '
END
IF(@GoodsDataFile4 <> '' OR (@ClickFlag = 1 And @GoodsCFlag4 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG4 ON detail.GoodsID = BG4.BaseID '
	Set @SqlMatch += ' And BG4.CustVal4 = @GoodsDataFile4 '
END
IF(@GoodsDataFile5 <> '' OR (@ClickFlag = 1 And @GoodsCFlag5 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Goods_CustomVal BG5 ON detail.GoodsID = BG5.BaseID '
	Set @SqlMatch += ' And BG5.CustVal5 = @GoodsDataFile5 '
END
IF(@BtypeDataFile1 <> '' OR (@ClickFlag = 1 And @BtypeCFlag1 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB1 ON bill.BtypeID = BB1.BaseID '
	Set @SqlMatch += ' And BB1.CustVal1 = @BtypeDataFile1 '
END
IF(@BtypeDataFile2 <> '' OR (@ClickFlag = 1 And @BtypeCFlag2 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB2 ON bill.BtypeID = BB2.BaseID '
	Set @SqlMatch += ' And BB2.CustVal2 = @BtypeDataFile2 '
END
IF(@BtypeDataFile3 <> '' OR (@ClickFlag = 1 And @BtypeCFlag3 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB3 ON bill.BtypeID = BB3.BaseID '
	Set @SqlMatch += ' And BB3.CustVal3 = @BtypeDataFile3 '
END
IF(@BtypeDataFile4 <> '' OR (@ClickFlag = 1 And @BtypeCFlag4 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB4 ON bill.BtypeID = BB4.BaseID '
	Set @SqlMatch += ' And BB4.CustVal4 = @BtypeDataFile4 '
END
IF(@BtypeDataFile5 <> '' OR (@ClickFlag = 1 And @BtypeCFlag5 = 1))
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype_CustomVal BB5 ON bill.BtypeID = BB5.BaseID '
	Set @SqlMatch += ' And BB5.CustVal5 = @BtypeDataFile5 '
END

IF @ClassID1 <> 0
Begin
	SET @SqlClass1 +=' DECLARE @CTb1  as Table(typeid int) INSERT INTO @CTb1(typeid) '
	Set @SqlCreateTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag1 when 0 then '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass1 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass1 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType1 when 1 then case @ClaseFlag1 when 0 then ' And detail.GoodsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on detail.GoodsID = C1.TypeID' end 
											when 2 then case @ClaseFlag1 when 0 then ' And bill.BtypeID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.BtypeID = C1.TypeID' end
											when 3 then case @ClaseFlag1 when 0 then ' And bill.WhsID = @ClassID1 ' else ' Inner Join @CTb1 C1 on Bill.WhsID = C1.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb1 C1 on BB.AreaID = C1.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb1 C1 on EE.DeptId = C1.TypeID'
											when 6 then ' And bill.ElyID = @ClassID1 '  	
											When 7 then ' And bill.Creator = @ClassID1' end 	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType1 = 4 and @ClassID1 = 0 
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END

IF @ClassID2 <> 0
Begin
	SET @SqlClass2 +=' DECLARE @CTb2  as Table(typeid int) INSERT INTO @CTb2(typeid) '
	Set @SqlCreateTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') end 
											when 2 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetBtypeID_Str(@BTypeID) end
											when 3 then case @ClaseFlag2 when 0 then '' else @SqlClass2 + dbo.UF_BD_GetWhsID_Str(@WhsID) end
											when 4 then @SqlClass2 + dbo.UF_BD_GetAreaID_Str('') 
											when 5 then @SqlClass2 + dbo.UF_BD_GetDeptID_Str() 
											else '' end
    Set @SqlTable += Case @ClassType2 when 1 then case @ClaseFlag2 when 0 then ' And detail.GoodsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on detail.GoodsID = C2.TypeID' end 
											when 2 then case @ClaseFlag2 when 0 then ' And bill.BtypeID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.BtypeID = C2.TypeID' end
											when 3 then case @ClaseFlag2 when 0 then ' And bill.WhsID = @ClassID2 ' else ' Inner Join @CTb2 C2 on Bill.WhsID = C2.TypeID' end
											when 4 then ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID Inner Join @CTb2 C2 on BB.AreaID = C2.TypeID'
											when 5 then ' Inner Join BD_Employee EE ON Bill.ElyID = EE.ElyID Inner Join @CTb2 C2 on EE.DeptId = C2.TypeID'
											when 6 then ' And bill.ElyID = @ClassID2 '  
											When 7 then ' And bill.Creator = @ClassID2' end 	
End
--特殊处理采购销售汇总报表按地区汇总，其他地区数据
if @ClassType2 = 4 and @ClassID2 = 0
BEGIN
	Set @SqlTable += ' Inner Join BD_Btype BB ON Bill.BtypeID = BB.BTypeID and bb.AreaID = 0 '
END
Set @Red = ' And Red = 0 '


select  @SqlIn = ' select 
		sum(detail.BSQty) as Qty,sum(detail.Total) as Total,sum(detail.DiscTotal) as DiscTotal,sum(detail.GoodsCostTotal) as GoodsCostTotal,
		(isnull(sum(detail.DiscTotal),0)-isnull(sum(detail.GoodsCostTotal),0)) as Profit
		 from PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where detail.BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
		+@SqlMatch + @GoodsTable
select @SqlOut = ' select 
		sum(detail.BSQty)*-1 as Qty,sum(detail.Total)*-1 as Total,sum(detail.DiscTotal)*-1 as  DiscTotal,sum(detail.GoodsCostTotal)*-1 as GoodsCostTotal, 
		(isnull(sum(detail.DiscTotal),0)-isnull(sum(detail.GoodsCostTotal),0))*-1 as Profit
		 from PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		where detail.BillDate BETWEEN @BeginDate AND @EndDate And  IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
		+@SqlMatch + @GoodsTable
		
IF @isHistory=1
Begin
	select  @SqlIn += ' 
			UNION ALL
			select 
		sum(detail.BSQty) as Qty,sum(detail.Total) as Total,sum(detail.DiscTotal) as DiscTotal,sum(detail.GoodsCostTotal) as GoodsCostTotal,
			(isnull(sum(detail.DiscTotal),0)-isnull(sum(detail.GoodsCostTotal),0)) as Profit
			 from PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
			where detail.BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
			+@SqlMatch + @GoodsTable
	select @SqlOut += ' 
			UNION ALL
			select 
			sum(detail.BSQty)*-1 as Qty,sum(detail.Total)*-1 as Total,sum(detail.DiscTotal)*-1 as  DiscTotal,sum(detail.GoodsCostTotal)*-1 as GoodsCostTotal, 
			(isnull(sum(detail.DiscTotal),0)-isnull(sum(detail.GoodsCostTotal),0))*-1 as Profit
			 from PD_SellRetBill_his bill INNER JOIN PD_SellRetDetail_his detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
			where detail.BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 ' + @Red + case @GiftFlag when 1 then ' And Gift=1 ' when 2 then ' And Gift=0 ' Else '' End 
			+@SqlMatch + @GoodsTable
End
	
if (@SaleBill = 1)  
begin  
 if(@SaleBackBill = 1)  
  Select @Sql += @SqlIn+ ' UNION ALL ' ;  
 else  
  Select @Sql += @SqlIn ;  
end  
if (@SaleBackBill = 1)  
 Select @Sql += @SqlOut;  
SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
)'
select @Sql += ' select SUM(Qty) as Qty,SUM(total) as Total,SUM(DiscTotal) as DiscTotal,SUM(GoodsCostTotal) as GoodsCostTotal,SUM(Profit) as Profit
	 from  Bill '

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END  

--Set @EndDate = CASE WHEN @DateType=0 THEN @EndDate ELSE DATEADD(day,1,@EndDate) END

Select @DecParam = N'@BeginDate VARCHAR(50),@EndDate VARCHAR(50),@BuyBillIn Int ,@BuyBillOut Int,@BTypeID VARCHAR(MAX),@DeptID1 VARCHAR(50),@ElyID VARCHAR(MAX),@CreatorID VARCHAR(MAX),@WhsID VARCHAR(MAX),@BillCode VARCHAR(100),@FullName VARCHAR(100),@UserCode VARCHAR(100),@Ppt1 VARCHAR(100),@Ppt2 VARCHAR(100),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@OperatorID INT
					,@Model VARCHAR(50), @GoodsAbbName VARCHAR(50), @Brand VARCHAR(50), @Spec VARCHAR(50),  @BarCode VARCHAR(100)
					, @GoodsDataFile1 Varchar(100),@GoodsDataFile2 varchar(100),@GoodsDataFile3 varchar(100),@GoodsDataFile4 varchar(100),@GoodsDataFile5 varchar(100)
					, @BtypeDataFile1 Varchar(100),@BtypeDataFile2 varchar(100),@BtypeDataFile3 varchar(100),@BtypeDataFile4 varchar(100),@BtypeDataFile5 varchar(100)'

Select @param =  ''''+Cast(@BeginDate as varchar(10))+''''+N','+''''+Cast(@EndDate as varchar(10))+''''+N','+''''+Cast(@SaleBill as varchar(2))+''''+N','
				+''''+Cast(@SaleBackBill as varchar(2))+''''+N','+''''+@BTypeID+''''+N','+''''+@DeptID+''''+N','+''''+@ElyID+''''+N','+''''+@CreatorID+''''+N','+''''+@WhsID+''''+N','+''''+@BillCode+''''+N','
				+''''+@FullName+''''+N','+''''+@UserCode+''''+N','+''''+@Ppt1+''''+N','+''''+@Ppt2+''''+N','+''''+@Summary+''''+N','+''''+@Description+''''+N','+''''+@Remark+''''+N','
				+''''+Cast(@OperatorID  as varchar(50))+''''+N','
				+''''+@Model+''''+N','+''''+@GoodsAbbName+''''+N','+''''+@Brand+''''+N','+''''+@Spec+''''+N','+''''+@BarCode+''''
				+N','+''''+@GoodsDataFile1+''''+N','+''''+@GoodsDataFile2+''''+N','+''''+@GoodsDataFile3+''''+N','+''''+@GoodsDataFile4+''''+N','+''''+@GoodsDataFile5+''''
				+N','+''''+@BtypeDataFile1+''''+N','+''''+@BtypeDataFile2+''''+N','+''''+@BtypeDataFile3+''''+N','+''''+@BtypeDataFile4+''''+N','+''''+@BtypeDataFile5+''''
				
if @ClassID1 <> 0
Begin
	Select @DecParam += ',@ClassID1 Int '
	Select @param += N',' + Cast(@ClassID1  as varchar(50))
	if(@ClassType1 = 1 and @ClaseFlag1 = 1)
	begin
		Select @DecParam += ',@GoodsTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 2 and @ClaseFlag1 = 1)
	begin
		Select @DecParam += ',@BtypeTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 3 and @ClaseFlag1 = 1)
	begin
		Select @DecParam += ',@WhsTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 4)
	begin
		Select @DecParam += ',@AreaTypeID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
	if(@ClassType1 = 5)
	begin
		Select @DecParam += ',@DeptID Int '
		Select @param += N',' + Cast(@ClassID1  as varchar(50))		
	ENd
END
if @ClassID2 <> 0
Begin
	Select @DecParam += ',@ClassID2 Int '
	Select @param += N',' + Cast(@ClassID2  as varchar(50))
	if(@ClassType2 = 1 and @ClaseFlag2 = 1)
	begin
		Select @DecParam += ',@GoodsTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 2 and @ClaseFlag2 = 1)
	begin
		Select @DecParam += ',@BtypeTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 3 and @ClaseFlag2 = 1)
	begin
		Select @DecParam += ',@WhsTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 4)
	begin
		Select @DecParam += ',@AreaTypeID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	if(@ClassType2 = 5)
	begin
		Select @DecParam += ',@DeptID Int '
		Select @param += N',' + Cast(@ClassID2  as varchar(50))		
	ENd
	
END
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
Select @ExcSql = N'EXEC sp_executesql @Sql,@DecParam,'+@param 

EXEC sp_executesql @ExcSql,N'@Sql NVARCHAR(max),@DecParam NVARCHAR(max)',@Sql,@DecParam
--EXEC SP_EXECUTESQL @Sql,N'@DateType Int,@BeginDate VARCHAR(50),@EndDate VARCHAR(50),@SaleBill Int ,	@SaleBackBill Int,@BTypeID VARCHAR(50),@DeptID VARCHAR(50),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@BillCode VARCHAR(100),@FullName VARCHAR(100),@UserCode VARCHAR(100),@Ppt1 VARCHAR(100),@Ppt2 VARCHAR(100),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@OperatorID INT'
--					,@DateType,@BeginDate,@EndDate,@SaleBill,@SaleBackBill,@BTypeID,@DeptID,@ElyID,@WhsID,@BillCode,@FullName,@UserCode,@Ppt1,@Ppt2,@Summary,@Description,@Remark,@OperatorID

GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2015-2-10
	描述：查询销售开票明细
-------------------------------------------*/
CREATE PROCEDURE UP_PD_SaleInvoiceStatisticalSum
(	
	@BeginDate DATE,
	@EndDate DATE,
	@BillType Int=0,  --单据类型
	@BTypeID VARCHAR(max)='',
	@IsManual INT=0,  --是否勾选手工开票单独列示
	@IsRedFlag INT=0,				--是否包含红冲单据数据
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID Int=0
)

AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;


DECLARE @Sql nvarchar(MAX)='',@SqlCreateTable VARCHAR(max)='',@SqlTable VARCHAR(max)='',
		 @LimitBtypeSql NVARCHAR(MAX) = '',@OutStr varchar(max)='',@outRetStr varchar(max)=''
		,@outSql varchar(max)='',@BtypeLimit INT=0,@RedStr varchar(100)=''
		,@InvoiceSql varchar(max)='',@InvoiceModeSql varchar(max)='',@InvoiceOutModeSql varchar(Max)=''
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1
Begin
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) insert into @LimitBType Select BtypeID from dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
End
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) insert into @BType Select typeid from dbo.UF_OT_Split_Int(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END   
if @IsRedFlag = 0
	select @RedStr = ' And Red=0 '
SET @RedStr += ' AND IsInvoice = 1 ' --只查询是否开票为是的单据
---------------计算单据金额列信息----------------
Select @OutStr +=' select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
Select @outRetStr +=' select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellRetBill Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
select @InvoiceSql += ' select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_SellInvoiceBill bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0 group by BTypeID'
if @IsHistory = 1
begin
	Select @OutStr +='
		Union All
		 select BTypeID,sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	Select @outRetStr +=' 
		Union All
		select BTypeID,-sum('+ case when @IsRedFlag = 1 then ' case when bill.red = 2 then total * -1 else Total End' else ' Total' end + ') as Total,sum(InvoiceTotal) as InvoiceTotal from PD_SellRetBill_His Bill '+@SqlTable +@LimitBtypeSql+ ' where BillDate BETWEEN @BeginDate AND @EndDate And IsDraft = 0 '+@RedStr+' Group by BTypeID' 
	select @InvoiceSql += '
		Union All
	 select BTypeID,0 as Total,0 as BillTotal1,SUM(InvoiceTotal) as UserTotal1 from MF_SellInvoiceBill_His bill '+@SqlTable+@LimitBtypeSql+' where BillDate BETWEEN @BeginDate AND @EndDate And InvoiceMode = 3 And IsDraft = 0  group by BTypeID'
end
if @BillType = 0
	Select @Sql += @OutStr + ' Union All ' + @outRetStr
else if @BillType =1
	Select @Sql += @OutStr 
else
	Select @Sql += @outRetStr 
-----------不同的显示方式计算未结金额和超额金额-----------
if @IsManual = 1 
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal2,SUM(UserTotal1) as UserTotal2,sum(Total) - sum(BillTotal1) as NoInvoiceTotal '
	Select @InvoiceOutModeSql +=' Total,BillTotal2,UserTotal2,NoInvoiceTotal'
End
else
Begin
	select @InvoiceModeSql +=' ,sum(BillTotal1) as BillTotal1,SUM(UserTotal1) as UserTotal1,
					sum(Total) - sum(BillTotal1) - SUM(UserTotal1) as NoInvoiceTotal,sum(BillTotal1) + SUM(UserTotal1)- sum(Total) as OutInvoiceTotal '
	Select @InvoiceOutModeSql +=' Total,BillTotal1,UserTotal1,
								case when total >= 0 then (case when NoInvoiceTotal<=0 then 0 else NoInvoiceTotal end) else (case when NoInvoiceTotal > 0 then 0 else NoInvoiceTotal end) end as NoInvoiceTotal
								,case When total >= 0 then (Case When OutInvoiceTotal <=0 then 0 else OutInvoiceTotal end) Else (Case When OutInvoiceTotal >= 0 then 0 else OutInvoiceTotal end) End as OutInvoiceTotal'
End
	
SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
),BillTotal as(
	Select BTypeID,sum(Total) as Total,sum(InvoiceTotal) as BillTotal1,0 as UserTotal1 from Bill Group By BTypeID
),InvoiceTotal as(
' +@InvoiceSql+ '
),AllData AS
 (
	select BTypeID,Total,BillTotal1,UserTotal1 from BillTotal
	Union All
	select BTypeID,Total,BillTotal1,UserTotal1 from InvoiceTotal
 ),PagingData AS(
	Select sum(Total) as Total '+@InvoiceModeSql+' 
	from AllData Ad 
 )
'

select @sql +=' select '+@InvoiceOutModeSql+'
	 from PagingData data '
IF @BtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Btype WHERE 1 <> 1'
DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END  
exec sp_executesql @Sql,N'@BeginDate Date,@EndDate Date,@OperatorID Int,@BTypeID VarChar(MAX)'
			,@BeginDate,@EndDate,@OperatorID,@BTypeID

GO



/****** Object:  StoredProcedure [UP_PD_QuerySaleOrderDetail]    Script Date: 07/01/2014 15:11:36 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('[UP_PD_SaleOrderDetailSum]') AND TYPE IN ('P', 'PC'))
	DROP PROCEDURE [UP_PD_SaleOrderDetailSum]
GO

/****** Object:  StoredProcedure [UP_PD_SaleOrderDetailSum]    Script Date: 10/23/2015 11:08:56 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-30
	描述：销售订单明细查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SaleOrderDetailSum]
(
     @PageNo INT = 0,						--页码
     @PageSize INT = 0,						--页大小
	 @BillDateType INT = 1,					--日期类型 1=录单日期,2=制单日期
	 @BillStartDate DATETIME,				--开始日期
	 @BillEndDate DATETIME,					--结束日期
     @BillCodeMatch INT = 0,				--单据编号匹配方式:0=包含,1=等于
     @BillCode VARCHAR(100) = '',			--单据编号
	 @BTypeID VARCHAR(1000) = '',			--往来单位
	 @DeptID VARCHAR(1000) = '',			--部门
	 @ElyID VARCHAR(1000) = '',				--经手人
	 @WhsID VARCHAR(1000) = '',				--仓库
	 @GoodsNoMatch INT=0,					--商品编号配置模式:0=包含,1=等于
	 @GoodsNo VARCHAR(50) = '',				--商品编号
	 @GoodsNameMatch INT=0,					--商品名称配置模式:0=包含,1=等于
	 @GoodsName VARCHAR(100) = '',			--商品名称
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	 @Ppt1Match INT=0,						--属性1配置模式:0=包含,1=等于
	 @Ppt1 VARCHAR(10) = '',				--属性1
	 @Ppt2Match INT=0,						--属性2配置模式:0=包含,1=等于
	 @Ppt2 VARCHAR(10) = '',				--属性2
	 @SummaryMatch INT=0,					--摘要配置模式:0=包含,1=等于
	 @Summary VARCHAR(256) = '',			--摘要
	 @DescriptionMatch INT=0,				--说明配置模式:0=包含,1=等于
	 @Description VARCHAR(100) = '',		--说明
	 @RemarkMatch INT=0,					--明细备注配置模式:0=包含,1=等于
	 @Remark VARCHAR(100) = '',				--明细备注
	 @GiftStt INT = 1,						--赠品状态 9=全部,1=是,0=否
	 @Stt_1 BIT = 1,						--订单状态 未调用
	 @Stt_2 BIT = 1,						--订单状态 部分调用
	 @Stt_3 BIT = 1,						--订单状态 已完成
	 @StopTag INT = 1,						--中止状态 9=全部,1=已中止,0=未中止
	 @IsHistory INT=0,						--是否包含历史数据
	 @OperatorID INT = 0,					--操作员ID
-----------------------以下参数在由销售订单汇总查看明细时用到----------------------------
	 @GoodsTypeID_mx INT = 0,					--商品分类ID
	 @GoodsID_mx INT = 0,						--商品ID
	 @BtypeTypeID_mx INT = 0,					--往来单位分类ID
	 @BTypeID_mx INT = 0,						--往来单位ID
	 @WhsTypeID_mx INT = 0,						--仓库分类ID
	 @WhsID_mx INT = 0,							--仓库ID
	 @AreaID_mx INT = 0,						--地区ID
	 @DeptID_mx INT = 0,						--部门ID
	 @ElyID_mx INT = 0							--职员ID
------------------------------------------------------------------------------------------
   ) 
AS
SET NOCOUNT ON
BEGIN

	DECLARE @Re INT 
	EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
	IF( @Re=1 )RETURN @Re;
	
	DECLARE @HeadSql NVARCHAR(2000)='',
			@HeadSql_His NVARCHAR(2000)='',
			@Sql NVARCHAR(MAX)='',@SqlParam VARCHAR(1000)='',@DataSql VARCHAR(2000)='',
			@BtypeLimit INT=0,@KtypeLimit INT=0
    DECLARE @TVP_Com AS [TVP_Type] 
    SET @HeadSql = 'SELECT detail.BSQty, detail.ComQty, detail.ComTotal, detail.TaxTotal
					       , detail.StopTag '
						 
			SET @Sql += 'INNER JOIN BD_Goods goods ON detail.GoodsID = goods.GoodsID 
						 LEFT JOIN BD_Employee creator ON creator.ElyID = ord.Creator 
						 INNER JOIN BD_Btype btype ON btype.BTypeID = ord.BTypeID '
	
    IF @BillDateType = 1
       SET @SqlParam = 'WHERE detail.BillDate BETWEEN @BillStartDate AND @BillEndDate  And ord.IsDraft = 0 '
    ELSE
       SET @SqlParam = 'WHERE ord.CreateTime BETWEEN @BillStartDate AND @BillEndDate  And ord.IsDraft = 0 '
       
    IF @BTypeID <> '' AND @BTypeID_mx = 0	--往来单位
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = ord.BTypeID '
	   
    IF @DeptID <> '' AND @DeptID_mx = 0		--部门
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Com _dept ON _dept.ChildTypeID = ord.DeptID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
		INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	END
	   
    IF @ElyID <> '' AND @ElyID_mx = 0		--经手人
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = ord.ElyID '
	   
    IF @WhsID <> '' AND @WhsID_mx = 0		--仓库
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = ord.WhsID '
	/*权限使用公用方法*/
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
	IF( @BtypeLimit=1 ) --部份权限
		SET @Sql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=ord.BTypeID '
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF( @KtypeLimit=1 ) --部份权限
		SET @Sql += 'INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=ord.WhsID '
	/*权限使用非公用方法*/
	/*
	IF @OperatorID <> 1 
	BEGIN
		IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Btype_Jur j WHERE j.RoleID = r.RoleID )) 
		BEGIN
			SET @Sql +='
			INNER JOIN (SELECT BTypeID FROM SS_Btype_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rBtype ON rBtype.BTypeID=ord.BTypeID '
		END
		IF NOT EXISTS (SELECT 1 FROM SS_Oper_Role r WHERE r.OperID = @OperatorID AND NOT EXISTS (SELECT 1 FROM SS_Whs_Jur j WHERE j.RoleID = r.RoleID )) 
		BEGIN
			SET @Sql +='
			INNER JOIN (SELECT WhsID FROM SS_Whs_Jur swj INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID) rWhs ON rWhs.WhsID=ord.WhsID '
		END
	END
	*/

	-----------------------以下参数在由销售订单汇总查看明细时用到----------------------------
    IF @GoodsTypeID_mx <> 0		--商品分类
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Com _goodsType ON _goodsType.ChildTypeID = goods.GoodsTypeID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM  BD_Goods_Type gt
		INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
	    WHERE gt.GoodsTypeID = @GoodsTypeID_mx AND cgt.SonNum = 0
	END
    IF @GoodsID_mx <> 0			--商品
		SET @SqlParam += 'AND detail.GoodsID=@GoodsID_mx '
    IF @BtypeTypeID_mx <> 0		--往来单位分类
	BEGIN
		SET @Sql +=' INNER JOIN @TVP_Com _btypeType ON _btypeType.ChildTypeID = btype.BtypeTypeID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT bt.BtypeTypeID, cbt.BtypeTypeID FROM BD_Btype_Type bt       
		INNER JOIN BD_Btype_Type cbt ON cbt.[Path] Like bt.[Path] + '%'
		WHERE bt.BtypeTypeID = @BtypeTypeID_mx AND cbt.SonNum = 0
	END
    IF @BTypeID_mx <> 0			--往来单位
		SET @SqlParam += 'AND ord.BTypeID=@BTypeID_mx '
    IF @WhsTypeID_mx <> 0		--仓库分类
	BEGIN
		SET @Sql +=' INNER JOIN @TVP_Com _whsType ON _whsType.ChildTypeID = ord.WhsID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT cwt.WhsTypeID, w.WhsID FROM BD_Whs w
		INNER JOIN BD_Whs_Type cwt ON w.WhsTypeID = cwt.WhsTypeID         
		INNER JOIN BD_Whs_Type wt ON cwt.[Path] Like wt.[Path] + '%'
		WHERE wt.WhsTypeID = @WhsTypeID_mx AND cwt.SonNum = 0
	END
    IF @WhsID_mx <> 0			--仓库
		SET @SqlParam += 'AND ord.WhsID=@WhsID_mx '
	IF @AreaID_mx <> 0			--地区
	BEGIN
		SET @Sql +=' INNER JOIN @TVP_Com _area ON _area.ChildTypeID = btype.AreaID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT a.AreaID, ca.AreaID FROM BD_Area a
		INNER JOIN BD_Area ca ON ca.[Path] Like a.[Path] + '%'
		WHERE a.AreaID = @AreaID_mx AND ca.SonNum = 0
	END
    IF @DeptID_mx <> 0			--部门
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Com _dept ON _dept.ChildTypeID = ord.DeptID '
		INSERT INTO @TVP_Com([TypeID],[ChildTypeID]) 
		SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
		INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		WHERE d.DeptID=@DeptID_mx AND cd.SonNum = 0
	END
    IF @ElyID_mx <> 0			--职员
		SET @SqlParam += 'AND ord.ElyID=@ElyID_mx '
	------------------------------------------------------------------------------------------
	
	IF @BillCode <> ''   --单据编号
	BEGIN 
		IF @BillCodeMatch = 0
			SET @SqlParam += 'AND ord.BillCode LIKE ''%''+@BillCode+''%'' '
		IF @BillCodeMatch = 1
			SET @SqlParam += 'AND ord.BillCode=@BillCode ' 
	END
	
	IF @GoodsTypeID_mx = 0 AND @GoodsID_mx = 0   --有商品分类和商品ID，条件就不用重复筛选了。
	BEGIN
		IF @GoodsNo <> ''		--商品编号 
		BEGIN
			IF @GoodsNoMatch=0 SET @SqlParam += 'AND goods.GoodsNo LIKE ''%''+@GoodsNo+''%'' '
			IF @GoodsNoMatch=1 SET @SqlParam += 'AND goods.GoodsNo=@GoodsNo '
		END
		IF @GoodsName <> ''		--商品名称 
		BEGIN
			IF @GoodsNameMatch=0 SET @SqlParam += 'AND goods.GoodsName LIKE ''%''+@GoodsName+''%'' '
			IF @GoodsNameMatch=1 SET @SqlParam += 'AND goods.GoodsName=@GoodsName '
		END
		
		IF @Model <> ''      --商品型号
		BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
		END       
		IF @GoodsAbbName <> ''    --商品简名
		BEGIN 
		   IF @GoodsAbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
		   ELSE IF @GoodsAbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
		END       
		IF @Brand <> ''      --商品品牌
		BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
		END
		--商品规格    
		IF @Spec <> ''        
		BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
		END
		--商品条码
		IF @BarCode <> ''      
		BEGIN 
		   SET @Sql += ' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID AND pri.UnitID = 1 '
		   
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=detail.GoodsID) '
		   ELSE IF @BarCodeMatch = 1 
	           SET @SqlParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=detail.GoodsID)'
		END
		
		IF @Ppt1 <> ''			--属性一 
		BEGIN 
			SET @Sql += ' INNER JOIN BD_Goods_Ppt1 ppt1 ON detail.Ppt1ID = ppt1.Ppt1ID  '
			IF @Ppt1Match=0 SET @SqlParam += 'AND ppt1.Value LIKE ''%''+@Ppt1+''%'' '
			IF @Ppt1Match=1 SET @SqlParam += 'AND ppt1.Value=@Ppt1 ' 
		END 
		   
		IF @Ppt2 <> ''			--属性二
		BEGIN 
			SET @Sql += ' INNER JOIN BD_Goods_Ppt2 ppt2 ON detail.Ppt2ID = ppt2.Ppt2ID  '
			IF @Ppt2Match=0 SET @SqlParam += 'AND ppt2.Value LIKE ''%''+@Ppt2+''%'' '
			IF @Ppt2Match=1 SET @SqlParam += 'AND ppt2.Value=@Ppt2 ' 
		END 
	       							
		IF @Summary <> ''		--摘要
		BEGIN
			IF @SummaryMatch=0 SET @SqlParam += 'AND ord.Summary LIKE ''%''+@Summary+''%'' '
			IF @SummaryMatch=1 SET @SqlParam += 'AND ord.Summary=@Summary '
		END
		   
		IF @Description <> ''	--说明
		BEGIN
			IF @DescriptionMatch=0 SET @SqlParam += 'AND ord.[Description] LIKE ''%''+@Description+''%'' '
			IF @DescriptionMatch=1 SET @SqlParam += 'AND ord.[Description]=@Description '
		END
	       							
		IF @Remark <> ''		--明细备注
		BEGIN
			IF @RemarkMatch=0 SET @SqlParam += 'AND detail.Remark LIKE ''%''+@Remark+''%'' '
			IF @RemarkMatch=1 SET @SqlParam += 'AND detail.Remark=@Remark '
		END
	END

    IF @GiftStt <> 9			--赠品 
       SET @SqlParam += 'AND detail.Gift = @GiftStt '       
	
	IF @Stt_1 <> 1 OR @Stt_2 <> 1 OR @Stt_3 <> 1   --订单状态 未调用 部分调用 已完成
	BEGIN
		IF @Stt_1 = 1 AND @Stt_2 = 1 AND @Stt_3 = 1
			SET @SqlParam += ''
		ELSE
		BEGIN
			IF @Stt_1 = 1 AND @Stt_2 = 1 AND @Stt_3 <> 1	--勾选：未调用和部分调用
				SET @SqlParam += 'AND NOT (detail.ComQty >= detail.BSQty OR detail.StopTag = 1) '
			IF @Stt_1 = 1 AND @Stt_2 <> 1 AND @Stt_3 = 1	--勾选：未调用和已完成
				SET @SqlParam += 'AND NOT (detail.ComQty > 0 AND detail.ComQty < detail.BSQty AND detail.StopTag <> 1) '
			IF @Stt_1 <> 1 AND @Stt_2 = 1 AND @Stt_3 = 1	--勾选：部分调用和已完成
				SET @SqlParam += 'AND NOT (detail.ComQty = 0 AND detail.StopTag <> 1) '
			IF @Stt_1 = 1 AND @Stt_2 <> 1 AND @Stt_3 <> 1	--勾选：未调用
				SET @SqlParam += 'AND (detail.ComQty = 0 AND detail.StopTag <> 1) '
			IF @Stt_1 <> 1 AND @Stt_2 = 1 AND @Stt_3 <> 1	--勾选：部分调用
				SET @SqlParam += 'AND (detail.ComQty > 0 AND detail.ComQty < detail.BSQty AND detail.StopTag <> 1) '
			IF @Stt_1 <> 1 AND @Stt_2 <> 1 AND @Stt_3 = 1	--勾选：已完成
				SET @SqlParam += 'AND (detail.ComQty >= detail.BSQty OR detail.StopTag = 1) '
		END
	END
	
	IF @StopTag <> 9 
		SET @SqlParam += 'AND detail.StopTag = @StopTag '
       
					 
	IF @IsHistory=0
		SET @Sql = ';With PagingData AS ( ' + @HeadSql + 'FROM PD_SellOrdDetail detail INNER JOIN PD_SellOrdBill ord ON detail.BillNo = ord.BillNo ' + @Sql + @SqlParam + ')' 
	ELSE
		SET @Sql = ';With PagingData AS ( ' + @HeadSql 
					+ 'FROM PD_SellOrdDetail detail INNER JOIN PD_SellOrdBill ord ON detail.BillNo = ord.BillNo '
					+ @Sql 
					+ @SqlParam 
					+ 'UNION ALL '
					+ @HeadSql 
					+ 'FROM PD_SellOrdDetail_His detail INNER JOIN PD_SellOrdBill_His ord ON detail.BillNo = ord.BillNo '
					+ @Sql 
					+ @SqlParam +')'
    Set @Sql += ',fulldata as(
						 select BSQty,ComQty,ComTotal,TaxTotal
						 ,case when StopTag = 0 then 0 else BSQty-ComQty end as StopQty
						 ,case when StopTag = 0 then 0 else TaxTotal-ComTotal end as StopTotal
						 ,case when StopTag = 0 then case when BSQty-ComQty >0 then BSQty-ComQty  else 0 end else 0 end as NotComQty
						 ,case when StopTag = 0 then case when TaxTotal-ComTotal > 0 then TaxTotal-ComTotal else 0 end else 0 end as NotComTotal
						 ,case when ComQty-BSQty >0 then ComQty-BSQty else 0 end as OverQty
						 ,case when ComTotal-TaxTotal >0 then ComTotal-TaxTotal else 0 end as OverTotal
						  from PagingData )
						  select SUM (BSQty) as BSQty,SUM (TaxTotal) as TaxTotal
								,SUM (ComQty) as ComQty,SUM (ComTotal) as ComTotal 
								,SUM (StopQty) as StopQty ,SUM (StopTotal) as StopTotal 
								,SUM (NotComQty) as NotComQty ,SUM (NotComTotal) as NotComTotal 
								,SUM (OverQty) as OverQty ,SUM (OverTotal) as OverTotal 
								 from fulldata '					
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
DECLARE @curPos INT = 1 , @count INT = 1
WHILE (@curPos < len(@Sql))
BEGIN
	PRINT substring(@Sql, @curPos, @curPos + 3999)
	SET @curPos += 3999 + 1
	SET @count += 1
END 
	EXEC sp_executesql @Sql,N'@PageNo INT,@PageSize INT,@BillStartDate DATETIME,@BillEndDate DATETIME,@BillCode VARCHAR(100)
	,@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsNo VARCHAR(50),
	@GoodsName VARCHAR(100), @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT,
	@Ppt1 VARCHAR(10),@Ppt2 VARCHAR(10),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@GiftStt INT
	,@StopTag INT,@OperatorID INT,@GoodsTypeID_mx INT, @GoodsID_mx INT, @BtypeTypeID_mx INT, @BTypeID_mx INT, @WhsTypeID_mx INT, @WhsID_mx INT, @AreaID_mx INT, @DeptID_mx INT, @ElyID_mx INT,@TVP_Com TVP_Type READONLY',
	@PageNo,@PageSize,@BillStartDate,@BillEndDate,@BillCode,@BTypeID,@DeptID,@ElyID,@WhsID, @GoodsNo,@GoodsName,
	@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch,
	@Ppt1,@Ppt2,@Summary,@Description,@Remark,@GiftStt,@StopTag,@OperatorID,@GoodsTypeID_mx, @GoodsID_mx, @BtypeTypeID_mx, @BTypeID_mx, @WhsTypeID_mx, @WhsID_mx, @AreaID_mx, @DeptID_mx, @ElyID_mx, @TVP_Com
							 	 
END
GO




/****** Object:  StoredProcedure [UP_PD_QuerySaleSummaryList]    Script Date: 07/31/2014 10:38:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_SaleOrderSummarySum]') AND TYPE IN (N'P', N'PC'))
DROP PROCEDURE UP_PD_SaleOrderSummarySum
GO

/****** Object:  StoredProcedure [UP_PD_SaleOrderSummarySum]    Script Date: 23/10/2015 10:38:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-07-30
	描述：销售订单汇总查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SaleOrderSummarySum]
(
     @PageNo INT = 0,						--页码
     @PageSize INT = 0,						--页大小
	 @BillDateType INT = 1,					--日期类型 1=录单日期,2=制单日期
	 @BillStartDate DATETIME,				--开始日期
	 @BillEndDate DATETIME,					--结束日期
	 @BTypeID VARCHAR(1000) = '',           --往来单位
	 @DeptID VARCHAR(1000) = '',            --部门
	 @ElyID VARCHAR(1000) = '',				--经手人
	 @WhsID VARCHAR(1000) = '',				--仓库
	 @GoodsNoMatch INT = 0,					--商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',				--商品编号
	 @GoodsNameMatch INT = 0,				--商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',			--商品名称
	 ---------------update sunzhiyuan 20150902--------------------
	 @Model VARCHAR(50) = '',               --型号
	 @ModelMatch INT = 0,                   --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',        --简名
	 @GoodsAbbNameMatch INT = 0,            --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',               --品牌
	 @BrandMatch INT = 0,                   --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',                --规格
	 @SpecMatch INT = 0,                    --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',             --条码
	 @BarCodeMatch INT = 0,                 --条码匹配方式 0:包含 1:等于
	 ---------------update sunzhiyuan 20150902--------------------
	 @SummaryMatch INT = 0,					--摘要匹配方式
	 @Summary VARCHAR(256) = '',			--摘要
	 @DescriptionMatch INT = 0,				--说明匹配方式
	 @Description VARCHAR(100) = '',		--说明
	 @RemarkMatch INT = 0,					--明细备注匹配方式
	 @Remark VARCHAR(100) = '',				--明细备注
	 @GiftStt INT = 1,						--赠品状态 9=全部,1=是,0=否
	 @SumParam INT = 0,						--汇总条件
	 @SumLevel INT = 0,						--汇总等级
	 @OrderStr VARCHAR(50) = '',			--排序字符串
	 @IsHistory INT=0,						--是否包含历史数据
	 @OperatorID INT = 0					--操作员ID
) 
AS
SET NOCOUNT ON
BEGIN

	DECLARE @re INT 
	EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
	IF( @re=1 )RETURN @re;

	DECLARE @ComHeadSql NVARCHAR(2000), 
			@HeadSql NVARCHAR(2000)='', 
			@HeadSql_His NVARCHAR(2000)='', 
	        @Sql_Ct NVARCHAR(MAX), 
	        @Sql_His NVARCHAR(MAX), 
	        @Sql NVARCHAR(MAX) = '', 
	        @SqlGroup NVARCHAR(1000) = '',
	        @SqlGroup_His NVARCHAR(1000) = '',
		    @SqlParam NVARCHAR(1000) = '',
	        @DataSql NVARCHAR(2000) = '', 
	        @BaseSql NVARCHAR(2000) = '',
	        @BtypeLimit INT = 0, 
	        @KtypeLimit INT = 0
    DECLARE @TVP_Dept AS [TVP_Type]   
    
    SET @ComHeadSql = ';WITH PagingData AS (
					SELECT SUM(detail.BSQty) AS Qty,SUM(detail.TaxTotal) AS Total
					,SUM(detail.ComQty) AS ComQty,SUM(detail.ComTotal) AS ComTotal
                    ,SUM(CASE WHEN detail.StopTag = 1 AND detail.BSQty - detail.ComQty > 0 THEN detail.BSQty - detail.ComQty ELSE 0 END) AS StopQty
                    ,SUM(CASE WHEN detail.StopTag = 1 AND detail.TaxTotal - detail.ComTotal > 0 THEN detail.TaxTotal - detail.ComTotal ELSE 0 END) AS StopTotal '
                    
    SET @Sql_Ct = 'FROM PD_SellOrdBill ord 
                INNER JOIN PD_SellOrdDetail detail ON detail.BillNo = ord.BillNo '
    SET @Sql_His = 'FROM PD_SellOrdBill_His ord 
                INNER JOIN PD_SellOrdDetail_His detail ON detail.BillNo = ord.BillNo '
	/*权限使用公用方法*/
	--往来单位权限
	SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
	IF @BtypeLimit = 1  --部份权限
		SET @Sql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=ord.BTypeID '
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF @KtypeLimit = 1  --部份权限
		SET @Sql += ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=ord.WhsID '
	
    IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
	   SET @Sql += 'INNER JOIN BD_Goods goods ON goods.GoodsID = detail.GoodsID '
	
	-- 条码
	IF @BarCode <> ''
	BEGIN 
		SET @Sql += ' INNER JOIN dbo.BD_Goods_Price pri ON pri.GoodsID = detail.GoodsID AND pri.UnitID = 1 '
	END   
	   
    IF @BillDateType = 1
       SET @SqlParam = 'WHERE detail.BillDate BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
    ELSE
       SET @SqlParam = 'WHERE ord.CreateTime BETWEEN @BillStartDate AND @BillEndDate And ord.IsDraft = 0 '
       
    IF @BTypeID <> ''     --往来单位
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _Btype ON _Btype.typeid = ord.BTypeID '
	   
    IF @DeptID <> ''     --部门
	BEGIN
		SET @Sql +='INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = ord.DeptID '
		INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
		SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
		INNER JOIN BD_Dept cd ON cd.[Path] LIKE d.[Path] + '%'
		WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	END
	   
    IF @ElyID <> ''     --经手人
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Emp ON _Emp.typeid = ord.ElyID '
	   
    IF @WhsID <> ''     --仓库
	   SET @Sql += 'INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = ord.WhsID '
	     							
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += 'AND goods.GoodsNo LIKE ''%''+@GoodsNo+''%'' '
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += 'AND goods.GoodsNo=@GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	BEGIN 
	   IF @GoodsNameMatch = 0
		   SET @SqlParam += 'AND goods.GoodsName LIKE ''%''+@GoodsName+''%'' '
	   ELSE IF @GoodsNameMatch = 1
		   SET @SqlParam += 'AND goods.GoodsName=@GoodsName ' 
	END
    --商品型号
    IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @Sql += N' AND goods.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @Sql += N' AND goods.Model = @Model ' 
	END       
	--商品简名
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @Sql += N' AND goods.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @Sql += N' AND goods.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @Sql += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @Sql += N' AND goods.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
	   IF @SpecMatch = 0
		   SET @Sql += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @Sql += N' AND goods.Spec = @Spec '  
	END
	--商品条码
	IF @BarCode <> ''      
	BEGIN 
	IF @BarCodeMatch = 0
	   SET @Sql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=detail.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @Sql += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=detail.GoodsID)'
	END
	
	--IF @BarCode <> ''      
	--BEGIN 
	--   IF @BarCodeMatch = 0
	--	   SET @Sql += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
	--   ELSE IF @BarCodeMatch = 1
	--	   SET @Sql += N' AND pri.BarCode = @BarCode ' 
	--END
       							
	IF @Summary <> ''   --摘要 
	   BEGIN 
		   IF @SummaryMatch = 0
			   SET @SqlParam += 'AND ord.Summary LIKE ''%''+@Summary+''%'' '
		   ELSE IF @SummaryMatch = 1
			   SET @SqlParam += 'AND ord.Summary=@Summary ' 
	   END
	   
	IF @Description <> ''  --说明
	   BEGIN 
		   IF @DescriptionMatch = 0
			   SET @SqlParam += 'AND ord.[Description] LIKE ''%''+@Description+''%'' '
		   ELSE IF @DescriptionMatch = 1
			   SET @SqlParam += 'AND ord.[Description]=@Description ' 
	   END
       							
	IF @Remark <> ''   --明细备注
	   BEGIN 
		   IF @RemarkMatch = 0 
			   SET @SqlParam += 'AND detail.Remark LIKE ''%''+@Remark+''%'' '
		   ELSE IF @RemarkMatch = 1
			   SET @SqlParam += 'AND detail.Remark=@Remark ' 
	   END
	   
    IF @GiftStt <> 9 --赠品 
       SET @SqlParam += 'AND detail.Gift = @GiftStt '
	   
	IF @SumParam = 1 --汇总层级：商品分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
	          SET @HeadSql += ',parGoodsType.BaseID AS GoodsTypeID '
	          SET @HeadSql_His += ',o.GoodsTypeID '
	          SET @Sql += '
				INNER JOIN BD_Goods _bg ON _bg.GoodsID = detail.GoodsID 
				INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @SumLevel) parGoodsType ON parGoodsType.ParID = _bg.GoodsTypeID '
			  SET @SqlGroup += ',parGoodsType.BaseID '
			  SET @SqlGroup_His += ',o.GoodsTypeID '
	        END
	     ELSE IF @SumLevel = 6  --商品
            BEGIN
			  SET @HeadSql += ', detail.GoodsID '
			  SET @HeadSql_His += ', o.GoodsID '
			  SET @SqlGroup += ', detail.GoodsID '
			  SET @SqlGroup_His += ', o.GoodsID '
	        END
	   END
	   
	IF @SumParam = 2 --汇总层级：往来单位分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
	          SET @HeadSql += ',parBtypeType.BaseID AS BtypeTypeID '
	          SET @HeadSql_His += ',o.BtypeTypeID '
	          SET @Sql += '
				INNER JOIN BD_Btype _bt ON _bt.BTypeID = ord.BTypeID 
				INNER JOIN dbo.UF_BD_BaseSummary(''BTYPE'', @SumLevel) parBtypeType ON parBtypeType.ParID = _bt.BtypeTypeID '
			  SET @SqlGroup += ',parBtypeType.BaseID '
			  SET @SqlGroup_His += ',o.BtypeTypeID '
	        END
	     ELSE IF @SumLevel = 6  --往来单位
            BEGIN
			  SET @HeadSql += ',ord.BTypeID '
			  SET @HeadSql_His += ',o.BTypeID '
			  SET @SqlGroup += ',ord.BTypeID '
			  SET @SqlGroup_His += ',o.BTypeID '
	        END
	   END
	   
	IF @SumParam = 3 --汇总层级：仓库分类
	   BEGIN
         IF @SumLevel <> 6 AND @SumLevel <> 0  --1-5
            BEGIN
				SET @HeadSql += ',parWhsType.BaseID AS WhsTypeID '
				SET @HeadSql_His += ',o.WhsTypeID '
				SET @Sql += '
				INNER JOIN BD_Whs _bw ON _bw.WhsID = ord.WhsID 
				INNER JOIN dbo.UF_BD_BaseSummary(''KTYPE'', @SumLevel) parWhsType ON parWhsType.ParID = _bw.WhsTypeID '
				SET @SqlGroup += ',parWhsType.BaseID '
				SET @SqlGroup_His += ',o.WhsTypeID '
	        END
	     ELSE IF @SumLevel = 6  --仓库
            BEGIN
			  SET @HeadSql += ',ord.WhsID '
			  SET @HeadSql_His += ',o.WhsID '
			  SET @SqlGroup += ',ord.WhsID '
			  SET @SqlGroup_His += ',o.WhsID '
	        END
	   END
	   
	IF @SumParam = 4 --汇总层级：地区
	   BEGIN
	      IF @SumLevel<>5 
		     BEGIN
		        SET @HeadSql += ',parArea.BaseID AS AreaID '
		        SET @HeadSql_His += ',o.AreaID '
                SET @Sql += '
				INNER JOIN BD_Btype _bbt ON _bbt.BTypeID = ord.BTypeID 
				INNER JOIN dbo.UF_BD_BaseSummary(''AREA'', @SumLevel) parArea ON parArea.ParID = _bbt.AreaID '
		        SET @SqlGroup += ',parArea.BaseID '
		        SET @SqlGroup_His += ',o.AreaID '
		     END
		     ELSE
		     BEGIN
		        SET @HeadSql += ',bType.AreaID '
		        SET @HeadSql_His += ',o.AreaID '
                SET @Sql += 'INNER JOIN BD_BType bType ON bType.BTypeID=ord.BTypeID  '
		        SET @SqlGroup += ',bType.AreaID '
		        SET @SqlGroup_His += ',o.AreaID '
		     END
	   END
	   
	IF @SumParam = 5 --汇总层级：部门
	   BEGIN
	      IF @SumLevel<>5 
		     BEGIN
		        SET @HeadSql += ',parDept.BaseID AS DeptID '
		        SET @HeadSql_His += ',o.DeptID '
                SET @Sql += '
                INNER JOIN BD_Dept _bd ON _bd.DeptID = ord.DeptID 
				INNER JOIN dbo.UF_BD_BaseSummary(''DTYPE'', @SumLevel) parDept ON parDept.ParID = _bd.DeptID '
		        SET @SqlGroup += ',parDept.BaseID '
		        SET @SqlGroup_His += ',o.DeptID '
		     END
		     ELSE
		     BEGIN
		        SET @HeadSql += ',ord.DeptID '
		        SET @HeadSql_His += ',o.DeptID '
		        SET @SqlGroup += ',ord.DeptID '
		        SET @SqlGroup_His += ',o.DeptID '
		     END
	   END
	   
	IF @SumParam = 6 --汇总层级：职员
	   BEGIN
          SET @HeadSql += ',ord.ElyID '
          SET @HeadSql_His += ',o.ElyID '
		  SET @SqlGroup += ',ord.ElyID '
		  SET @SqlGroup_His += ',o.ElyID '
	   END
	
	IF @IsHistory=0
		SET @Sql = @ComHeadSql + @HeadSql + @Sql_Ct + @Sql + @SqlParam + ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1)  + ' )'
	ELSE
		SET @Sql = ';WITH PagingData AS (
					SELECT SUM(o.BSQty) AS Qty,SUM(o.TaxTotal) AS Total
					,SUM(o.ComQty) AS ComQty,SUM(o.ComTotal) AS ComTotal
                    ,SUM(CASE WHEN o.StopTag = 1 AND o.BSQty - o.ComQty > 0 THEN o.BSQty - o.ComQty ELSE 0 END) AS StopQty
                    ,SUM(CASE WHEN o.StopTag = 1 AND o.TaxTotal - o.ComTotal > 0 THEN o.TaxTotal - o.ComTotal ELSE 0 END) AS StopTotal ' + @HeadSql_His 
                    + 'FROM ( 
                    SELECT detail.BSQty,detail.TaxTotal,detail.ComQty,detail.ComTotal,detail.StopTag ' + @HeadSql + @Sql_Ct + @Sql + @SqlParam 
					+ 'UNION ALL '
					+ 'SELECT detail.BSQty,detail.TaxTotal,detail.ComQty,detail.ComTotal,detail.StopTag ' + @HeadSql + @Sql_His + @Sql + @SqlParam 
					+ ') o GROUP BY ' + SUBSTRING(@SqlGroup_His, 2, LEN(@SqlGroup_His) - 1)  + ' )'
    SET @Sql += ',MainData AS (
          select Qty,Total,
				 ComQty,ComTotal,
				 StopQty,StopTotal, 
				 case when Qty - ComQty-StopQty > 0 then Qty - ComQty-StopQty else 0 end as NotComQty ,
				 case when Total - ComTotal-StopTotal > 0 then Total - ComTotal-StopTotal else 0 end as NotComTotal ,
				 case when Qty - ComQty-StopQty < 0 then (Qty - ComQty-StopQty)*-1 else 0 end as OverQty ,
				 case when Total - ComTotal-StopTotal < 0 then (Total - ComTotal-StopTotal)*-1 else 0 end as OverTotal 
				 from PagingData 
          ),FullData as(
			select SUM(Qty) as Qty,SUM(Total) as Total,
				 SUM(ComQty) as ComQty,SUM(ComTotal) as ComTotal,
				 SUM(StopQty) as StopQty,SUM(StopTotal) as StopTotal, 
				 SUM(NotComQty) as NotComQty,SUM(NotComTotal) as NotComTotal ,
				 SUM(OverQty) as OverQty,SUM(OverTotal) as OverTotal 
				 from MainData
          )
          select * from FullData  ' 
    
    
    SET @Sql='SET NOCOUNT ON;'
             + @Sql 
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
PRINT @Sql
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillDateType INT, @BillStartDate DATETIME, 
							   @BillEndDate DATETIME, @BTypeID VARCHAR(1000), @DeptID VARCHAR(1000), 
							   @ElyID VARCHAR(1000), @WhsID VARCHAR(1000), @GoodsNo VARCHAR(50),
							   @GoodsName VARCHAR(100), @Summary VARCHAR(256), @Description VARCHAR(100), 
							   @Remark VARCHAR(100), @GiftStt INT, @SumLevel INT, @OperatorID INT, @TVP_Dept TVP_Type READONLY
							   , @Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT', 
	                         @PageNo, @PageSize, @BillDateType, @BillStartDate, @BillEndDate, @BTypeID, @DeptID, @ElyID, 
	                         @WhsID, @GoodsNo, @GoodsName, @Summary, @Description, @Remark, @GiftStt, @SumLevel, @OperatorID, @TVP_Dept     
	                         , @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
END
GO




/****** Object:  StoredProcedure [UP_PD_SaleSummaryListSum]    Script Date: 06/23/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_SaleSummaryListSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_SaleSummaryListSum]
GO

/****** Object:  StoredProcedure [UP_PD_SaleSummaryListSum]    Script Date: 10/26/2015 15:42:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：雷洋
	日期：2015-10-25
	描述：销售汇总统计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SaleSummaryListSum]
(			   
	@pageNo INT=1,					--页码
	@pageSize INT=10,				--分页数
	@BillDateType INT=1,			--单据日期类型:1=录单日期,2=制单日期,3=过账日期  对应BillDate,CreateTime,PosTime
	@BillStartDate DATETIME,		--单据开始日期
	@BillEndDate DATETIME,			--单据结束日期
	@SaleBillOut INT=1,				--销售出库单勾选状态
	@SaleBillIn INT=1,				--销售退货单勾选状态
	@BTypeID VARCHAR(1000) = '',	--往来单位
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@CreatorID VARCHAR(1000)='',    --制单人
	@WhsID VARCHAR(1000) = '',		--仓库
	@GoodsID VARCHAR(1000) = '',	--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(20) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(50) = '',	--商品名称
	---------------update sunzhiyuan 20150906--------------------
	@Model VARCHAR(50) = '',        --型号
	@ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	@GoodsAbbName VARCHAR(50) = '', --简名
	@GoodsAbbNameMatch INT = 0,     --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',        --品牌
	@BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	@Spec VARCHAR(50) = '',         --规格
	@SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	---------------update sunzhiyuan 20150906--------------------
	@SummaryMatch INT=0,			--摘要配置模式:0=包含,1=等于
	@Summary VARCHAR(256) = '',		--摘要
	@DescriptionMatch INT=0,		--说明配置模式:0=包含,1=等于
	@Description VARCHAR(100) = '', --说明
	@RemarkMatch INT=0,				--明细备注配置模式:0=包含,1=等于
	@Remark VARCHAR(100) = '',		--明细备注
	@Goods INT=0,					--商品汇总项：商品
	@Ppt1 INT=0,					--商品汇总项：属性一
	@Ppt2 INT=0,					--商品汇总项：属性二
	@GiftState INT=9,				--赠品状态：9=全部,1=是,0=否
	@Privilege INT=0,				--包含优惠信息：0=不包含，1=包含
	@CollectType1 INT=0,			--汇总条件一:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer1 INT=0,					--汇总层级一:0:空 1-5:XX分类层级 6:XX
	@CollectType2 INT=0,			--汇总条件二:1=商品分类,2=往来单位分类,3=仓库分类,4=地区,5=部门,6=职员
	@Layer2 INT=0,					--汇总层级二:0:空 1-5:XX分类层级 6:XX
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)
AS
SET NOCOUNT ON
BEGIN
	-- 当日期类型为业务日期的场合，做归档日期的范围判断
	IF @BillDateType = 1
	BEGIN
		DECLARE @Re INT 
		EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
		IF( @Re=1 )RETURN @Re;
	END

DECLARE @Sql NVARCHAR(MAX)='',@SqlDTStr VARCHAR(20)=''
	,@SumData NVARCHAR(MAX),@VbSumHead VARCHAR(50)='',@SumHead NVARCHAR(MAX),@SumHeadFH NVARCHAR(MAX),@SumJoin NVARCHAR(MAX)='',@SumParam NVARCHAR(MAX),@VbSumG VARCHAR(300)=''
	,@Sql_PPB NVARCHAR(MAX),@Sql_PPB_His NVARCHAR(MAX),@Sql_PRB NVARCHAR(MAX),@Sql_PRB_His NVARCHAR(MAX)
	,@VbBDHead VARCHAR(500)='',@BDHead VARCHAR(200),@VbSumBDHead VARCHAR(200)='',@VbBDJoin VARCHAR(400)='',@CFBDJoin NVARCHAR(MAX)=''
	,@Profit VARCHAR(100),@PrivilegeStrP varchar(200)='',@PrivilegeStrL varchar(100)=''
	,@BtypeLimit INT=0,@KtypeLimit INT=0 
--INNER JOIN BEGIN
IF @BTypeID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _BType ON _BType.typeid = p.BTypeID '
IF @DeptID <> ''
BEGIN
	SET @SumJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=p.DeptID '
END
IF @ElyID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = p.ElyID '
IF @CreatorID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@CreatorID, '','') _PEly ON _PEly.typeid = p.Creator '
IF @WhsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = p.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SumJoin += '
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=p.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SumJoin += '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=p.WhsID '
IF @GoodsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID '
IF @GoodsNo <> '' OR @GoodsName <> '' OR @Model <> '' OR @GoodsAbbName <> '' OR @Brand <> '' OR @Spec <> ''
	SET @SumJoin +='
	INNER JOIN BD_Goods g ON g.GoodsID=dtl.GoodsID '
IF @BarCode <> ''
BEGIN 
	SET @SumJoin += ' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID and pri.UnitID = 1 '
END 
--INNER JOIN END

--条件BEGIN
IF @BillDateType=1
	SET @SqlDTStr='dtl.BillDate'
IF @BillDateType=2
	SET @SqlDTStr='p.CreateTime'	
IF @BillDateType=3
	SET @SqlDTStr='p.PosTime'	
SET @SumParam = '
	WHERE '+@SqlDTStr+' BETWEEN @BillStartDate AND @BillEndDate AND p.IsDraft=0 AND p.Red=0 '
IF @GiftState<>9 
	SET @SumParam += 'AND Gift=@GiftState '

IF @Summary <> ''
BEGIN
	IF @SummaryMatch=0 SET @SumParam += 'AND p.Summary LIKE ''%''+@Summary+''%'' '  
	IF @SummaryMatch=1 SET @SumParam += 'AND p.Summary=@Summary '  
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch=0 SET @SumParam += 'AND p.[Description] LIKE ''%''+@Description+''%'' '  
	IF @DescriptionMatch=1 SET @SumParam += 'AND p.[Description]=@Description '  
END
IF @Remark <> ''
BEGIN
	IF @RemarkMatch=0 SET @SumParam += 'AND dtl.Remark LIKE ''%''+@Remark+''%'' '   
	IF @RemarkMatch=1 SET @SumParam += 'AND dtl.Remark=@Remark '  
END
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0 SET @SumParam += 'AND g.GoodsNo LIKE ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch=1 SET @SumParam += 'AND g.GoodsNo=@GoodsNo '  
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0 SET @SumParam += 'AND g.GoodsName LIKE ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch=1 SET @SumParam += 'AND g.GoodsName=@GoodsName '  
END
--商品型号	
IF @Model <> ''      
   BEGIN 
	   IF @ModelMatch = 0
		   SET @SumParam += N' AND g.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @SumParam += N' AND g.Model = @Model ' 
   END  
--商品简名     
IF @GoodsAbbName <> ''    
BEGIN 
   IF @GoodsAbbNameMatch = 0
	   SET @SumParam += N' AND g.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
   ELSE IF @GoodsAbbNameMatch = 1
	   SET @SumParam += N' AND g.GoodsAbbName = @GoodsAbbName ' 
END     
--商品品牌  
IF @Brand <> ''      
BEGIN 
   IF @BrandMatch = 0
	   SET @SumParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
   ELSE IF @BrandMatch = 1
	   SET @SumParam += N' AND g.Brand = @Brand ' 
END  
--商品规格  
IF @Spec <> ''        
   BEGIN 
	   IF @SpecMatch = 0
		   SET @SumParam += N' AND g.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @SumParam += N' AND g.Spec = @Spec '  
   END
--商品条码
IF @BarCode <> ''      
BEGIN 
	IF @BarCodeMatch = 0
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=dtl.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=dtl.GoodsID)'
END
--条件END

if(@Privilege = 1)
	SET @VbSumG += ' group by p.BillNo '

SET @SumData=';WITH SumData AS('

SET @SumHead='SUM(dtl.BSQty)[BSQtyST]
	,SUM(dtl.TaxTotal)[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)[GiftQtyST] '
SET @SumHeadFH='SUM(dtl.BSQty)*-1[BSQtyST]
	,SUM(dtl.TaxTotal)*-1[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)*-1[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)*-1[GiftQtyST] '
IF(@Privilege = 1)
BEGIN
	Set @SumHead += ' ,Sum(distinct p.Privilege) as [Privilege] '
	Set @SumHeadFH += ' ,Sum(distinct p.Privilege)*-1 as [Privilege] ' 
END	
IF NOT (@SaleBillOut<>0 AND @SaleBillIn<>0)
	SET @SumHeadFH = @SumHead
SET @Sql_PPB='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill p 
	INNER JOIN PD_SellDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PPB_His='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill_His p 
	INNER JOIN PD_SellDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam + @VbSumG
SET @Sql_PRB='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill p 
	INNER JOIN PD_SellRetDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam+ @VbSumG
SET @Sql_PRB_His='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill_His p 
	INNER JOIN PD_SellRetDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam+ @VbSumG

IF @IsHistory = 0
BEGIN
	IF @SaleBillOut<>0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL '+@Sql_PRB+')'
	END
	IF @SaleBillOut<>0 AND @SaleBillIn=0
	BEGIN
		SET @SumData+=@Sql_PPB+')'
	END
	IF @SaleBillOut=0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PRB+')'
	END
END
ELSE
BEGIN
	IF @SaleBillOut<>0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL '+@Sql_PRB+'
	UNION ALL'+@Sql_PPB_His+'
	UNION ALL '+@Sql_PRB_His+')'
	END
	IF @SaleBillOut<>0 AND @SaleBillIn=0
	BEGIN
		SET @SumData+=@Sql_PPB+'
	UNION ALL'+@Sql_PPB_His+')'
	END
	IF @SaleBillOut=0 AND @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PRB+'
	UNION ALL'+@Sql_PRB_His+')'
	END
END


SET	@Profit ='
	,SaleTotal-CostTotal [Profit] '
IF(@Privilege = 1)
BEGIN
	Set @PrivilegeStrP = ' ,[SaleTotalST] - [Privilege]-[CostTotalST] [Profit],Privilege as Privilege, [SaleTotalST] - [Privilege] as SalePrivilege  '
	Set @PrivilegeStrL = ' ,Sum(Privilege) as Privilege,Sum(SalePrivilege) as SalePrivilege '
END
Else
Begin
	Set @PrivilegeStrP = ',[SaleTotalST]-[CostTotalST] [Profit] '
End


SET @Sql += 'SET NOCOUNT ON;
' + @SumData + '
, PageData as (select [BSQtyST] as BSQTY,SaleTotalST as SaleToTal,CostTotalST as CostTotal,GiftQtyST as GiftQty '+@PrivilegeStrP+' from SumData )
   select Sum(BSQTY) as BSQty,Sum(SaleToTal) as SaleTotal ,Sum(CostTotal) as CostTotal,Sum(Profit) as Profit, SUM(GiftQty) as GiftQty '+@PrivilegeStrL+'  from PageData
 '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
print @Sql
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END 

EXEC SP_EXECUTESQL @Sql,N'@pageNo INT,@pageSize INT,@BillDateType INT,@BillStartDate DATETIME,@BillEndDate DATETIME
,@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@CreatorID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000)
,@GoodsNo VARCHAR(20),@GoodsName VARCHAR(50),@Summary VARCHAR(256),@Description VARCHAR(100),@Remark VARCHAR(100),@GiftState INT
,@CollectType1 INT,@Layer1 INT,@CollectType2 INT,@Layer2 INT,@OperatorID INT
,@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT'
,@pageNo,@pageSize,@BillDateType,@BillStartDate,@BillEndDate
,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@GoodsID,@GoodsNo,@GoodsName,@Summary,@Description,@Remark,@GiftState
,@CollectType1,@Layer1,@CollectType2,@Layer2,@OperatorID
, @Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
END


GO






if exists (select * from sysobjects where id = object_id(N'[UP_PD_SellLoadBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_PD_SellLoadBill]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		雷洋
-- Create date:  2014/6/17
-- Description:	 销售单
-- update sunzhiyuan 多账户查询
-- update sunzhiyuan 增加AuditStatus字段检索（审核状态）
-- =============================================
CREATE PROCEDURE [UP_PD_SellLoadBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @IsAccounts INT = 0
	IF EXISTS(SELECT 1 FROM PD_MulAccounts WHERE BillTypeID = 201 AND BillNo = @BillNo)
		SELECT @IsAccounts = 1
		
	if exists( select 1 from PD_SellBill where BillNo = @BillNo)
	begin
		select BillNo,
			   BillDate,
			   BillCode,
			   Bill.BTypeID,
			   Bill.DeptID,
			   Bill.ElyID,
			   bill.WhsID,
			   LogistBtypeID,
			   LogistBillNo,
			   Freight,
			   FreightTotal,
			   FreightFinanceID,
			   CASE FreightType WHEN 1 THEN 1 WHEN 0 THEN 0 END AS FreightType,
			   BillQty,
			   BTDTotal,
			   bill.PaidTotal,
			   Total,
			   Privilege,
			   Total - Privilege AS AfterPrivilege,
			   PayRecTotal,
			   CASE @IsAccounts WHEN 0 THEN bill.FinanceID ELSE -100 end as FinanceID,
			   --bill.FinanceID,
			   Creator,
			   PosElyID,
			   Summary,
			   Description,
			   IsDraft,
			   Red,
			   b.BTypeName,
			   b.PaidCircle,
			   d.DeptName,
			   e.ElyName,
			   ep.ElyName as PosName,
			   w.WhsName,
			   bl.BTypeName as LogistBtypeName,
			   ec.ElyName as CreatorName,
			   f.FinanceName as FreightFinanceName,
			   CASE @IsAccounts WHEN 0 THEN ff.FinanceName ELSE '【多账户】' end as FinanceName,
			   --ff.FinanceName,
			   bill.IsOS,@IsAccounts as IsAccounts,
			   bill.AuditStatus,
			   bill.IsInvoice,
			   bill.IsDeduction,
			   bill.DeductionCent,
			   bill.ExchangeCent,
			   bill.VipCardID,
			   Vt.IsAllPay,
			   ' '+Vt.TypeName + ' 会员卡号：'+v.VipCardNO+' 会员名称：'+V.VipName+' 持卡人：' + CardHolder+' 积分余额：' + CONVERT(VARCHAR,v.CentBalance)+' 储值余额：' + CONVERT(VARCHAR,CONVERT(FLOAT,v.MoneyBalance)) AS VipCardInfo,
			   bill.BeforeARTotal,
			   ISNULL(bill.BeforeARTotal,0)+(ISNULL(bill.total,0)-ISNULL(bill.Privilege,0)-ISNULL(bill.PayRecTotal,0)) AS CurARTotal
			from PD_SellBill bill 
		 LEFT JOIN BD_Btype b ON bill.BtypeID=b.BTypeID
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN  BD_Whs w ON bill.WhsID=w.WhsID
		 LEFT JOIN  BD_Btype bl on bill.LogistBTypeID = bl.BTypeID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 LEFT JOIN BD_Finance f ON bill.FreightFinanceID=f.FinanceID
		 LEFT JOIN BD_Finance Ff ON bill.FinanceID=ff.FinanceID
		 LEFT JOIN VS_VipCard V ON bill.VipCardID = v.VipCardID
		 LEFT JOIN VS_VipCardType Vt ON v.VipCardTypeID = Vt.VipCardTypeID
		 where BillNo = @BillNo
	     
		 SELECT		detail.[DID]
				  ,detail.[BillNo]
				  ,detail.OrdDID
				  ,detail.BarCode
				  ,detail.GoodsID
				  ,detail.Ppt1ID
				  ,detail.Ppt2ID
				  ,detail.WhsID
				  ,detail.WhsPtID
				  ,detail.UnitID
				  ,detail.Convfactor
				  ,detail.Price
				  ,detail.DiscPrice
				  ,detail.TaxPrice
				  ,detail.Qty
				  ,detail.BSQty
				  ,detail.Total
				  ,detail.DiscTotal
				  ,detail.TaxTotal
				  ,detail.Discount
				  ,detail.TaxRate
				  ,detail.Tax
				  ,detail.CostPrice
				  ,detail.CostPrice as GoodsCostPrice
				  ,detail.GoodsCostTotal
				  ,Cast(detail.Gift as bit) Gift
				  ,detail.Remark
				  ,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.InPutPrice,g.DateType,g.CostMethod
				  ,g.GoodsNo
				  ,g.GoodsName
				  ,g.Model
				  ,g.Spec
				  ,gp1.Value as Ppt1Name
				  ,gp2.Value as Ppt2Name
				  ,wp.WhsPtName
				  ,gp.Unit
				  ,gpr1.Convfactor as Convfactor1
				  ,ISNULL(gpr2.Convfactor,1) as Convfactor2
				  ,ISNULL(gpr3.Convfactor,1) as Convfactor3
				  ,gpr1.BarCode[BarCode1],gpr2.BarCode[BarCode2],gpr3.BarCode[BarCode3]
				  ,gpr1.Unit as Unit1
				  ,gpr2.Unit as Unit2
				  ,gpr3.Unit as Unit3
				,op.BillCode
				,detail.PriceID	
				,detail.VerifyQty
				,detail.IsSelectBatch	
				,CASE WHEN detail.Qty=detail.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
			g.IsSerial	,
			detail.goodsno AS BtypeGoodsNo,
			g.Brand,
			g.KG			
		 FROM PD_SellDetail detail
			  LEFT JOIN BD_Goods g ON detail.GoodsID=g.GoodsID	
			  LEFT JOIN BD_Whs_Position wp ON detail.WhsPtID = wp.WhsPtID
			  LEFT JOIN 
			(
				SELECT BillCode,DID 
				FROM PD_SellOrdDetail D
				INNER JOIN PD_SellOrdBill b ON d.BillNo = b.BillNo
				UNION ALL
				SELECT BillCode,DID 
				FROM PD_SellOrdDetail_His D
				INNER JOIN PD_SellOrdBill_His b ON d.BillNo = b.BillNo
			) op ON op.DID= detail.OrdDID
			  LEFT JOIN BD_Goods_Ppt1 gp1 ON detail.Ppt1ID = gp1.Ppt1ID
			  LEFT JOIN BD_Goods_Ppt2 gp2 ON detail.Ppt2ID = gp2.Ppt2ID
			  LEFT JOIN BD_Goods_Price gp ON detail.UnitID = gp.UnitID and detail.GoodsID = gp.GoodsID
			  LEFT JOIN BD_Goods_Price gpr1 ON g.GoodsID = gpr1.GoodsID and gpr1.UnitID = 1
			  LEFT JOIN BD_Goods_Price gpr2 ON g.GoodsID = gpr2.GoodsID and gpr2.UnitID = 2
			  LEFT JOIN BD_Goods_Price gpr3 ON g.GoodsID = gpr3.GoodsID and gpr3.UnitID = 3
		  WHERE detail.BillNo = @BillNo
		  ORDER BY detail.DID;  --查询明细  
		  
		  -- 查询多账户信息
		  SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 201 and BillNo = @BillNo  
		  
		  -- 查询单据明细SN
	select Serial,BillDID,ps.Remark from PD_SellSerial ps Inner Join PD_SellDetail pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
    END
    ELSE
    BEGIN
    		select BillNo,
			   BillDate,
			   BillCode,
			   Bill.BTypeID,
			   Bill.DeptID,
			   Bill.ElyID,
			   bill.WhsID,
			   LogistBtypeID,
			   LogistBillNo,
			   Freight,
			   FreightTotal,
			   FreightFinanceID,
			   CASE FreightType WHEN 1 THEN 1 WHEN 0 THEN 0 END AS FreightType,
			   BillQty,
			   BTDTotal,
			   bill.PaidTotal,
			   Total,
			   Privilege,
			   Total - Privilege AS AfterPrivilege,
			   PayRecTotal,
			   CASE @IsAccounts WHEN 0 THEN bill.FinanceID ELSE -100 end as FinanceID,
			   --bill.FinanceID,
			   Creator,
			   PosElyID,
			   Summary,
			   Description,
			   IsDraft,
			   Red,
			   b.BTypeName,
			   d.DeptName,
			   e.ElyName,
			   ep.ElyName as PosName,
			   w.WhsName,
			   bl.BTypeName as LogistBtypeName,
			   ec.ElyName as CreatorName,
			   f.FinanceName as FreightFinanceName,
			   CASE @IsAccounts WHEN 0 THEN ff.FinanceName ELSE '【多账户】' end as FinanceName,
			   bill.IsOS,@IsAccounts as IsAccounts,
			   bill.IsInvoice,
			   bill.IsDeduction,
			   bill.DeductionCent,
			   bill.ExchangeCent,
			   bill.VipCardID,
			   '会员卡类型：'+ Vt.TypeName + ' 会员卡号：'+v.VipCardNO+' 会员名称：'+V.VipName+' 持卡人：' + CardHolder + ' 会员卡状态' AS VipCardInfo,
			    bill.BeforeARTotal,
			    ISNULL(bill.BeforeARTotal,0)+(ISNULL(bill.total,0)-ISNULL(bill.Privilege,0)-ISNULL(bill.PayRecTotal,0)) AS CurARTotal
			from PD_SellBill_His bill
		 LEFT JOIN BD_Btype b ON bill.BtypeID=b.BTypeID
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN  BD_Whs w ON bill.WhsID=w.WhsID
		 LEFT JOIN  BD_Btype bl on bill.LogistBTypeID = bl.BTypeID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 LEFT JOIN BD_Finance f ON bill.FreightFinanceID=f.FinanceID
		 LEFT JOIN BD_Finance Ff ON bill.FinanceID=ff.FinanceID
		 LEFT JOIN VS_VipCard V ON bill.VipCardID = v.VipCardID
		 LEFT JOIN VS_VipCardType Vt ON v.VipCardTypeID = Vt.VipCardTypeID
		 where BillNo = @BillNo
	     
		 SELECT		detail.[DID]
				  ,detail.[BillNo]
				  ,detail.OrdDID
				  ,detail.BarCode
				  ,detail.GoodsID
				  ,detail.Ppt1ID
				  ,detail.Ppt2ID
				  ,detail.WhsID
				  ,detail.WhsPtID
				  ,detail.UnitID
				  ,detail.Convfactor
				  ,detail.Price
				  ,detail.DiscPrice
				  ,detail.TaxPrice
				  ,detail.Qty
				  ,detail.BSQty
				  ,detail.Total
				  ,detail.DiscTotal
				  ,detail.TaxTotal
				  ,detail.Discount
				  ,detail.TaxRate
				  ,detail.Tax
				  ,Cast(detail.Gift as bit) Gift
				  ,detail.Remark
				  ,detail.CostPrice
				  ,detail.CostPrice as GoodsCostPrice
				  ,detail.GoodsCostTotal
				  ,detail.BatchNumber,detail.ProductDate,detail.EndDate,detail.InPutPrice,g.DateType,g.CostMethod
				  ,g.GoodsNo
				  ,g.GoodsName
				  ,g.Model
				  ,g.Spec
				  ,gp1.Value as Ppt1Name
				  ,gp2.Value as Ppt2Name
				  ,wp.WhsPtName
				  ,gp.Unit
				  ,gpr1.Convfactor as Convfactor1
				  ,ISNULL(gpr2.Convfactor,1) as Convfactor2
				  ,ISNULL(gpr3.Convfactor,1) as Convfactor3
				  ,gpr1.BarCode[BarCode1],gpr2.BarCode[BarCode2],gpr3.BarCode[BarCode3]
				  ,gpr1.Unit as Unit1
				  ,gpr2.Unit as Unit2
				  ,gpr3.Unit as Unit3
				,op.BillCode		
				,detail.PriceID		
				,detail.VerifyQty	
				,CASE WHEN detail.Qty=detail.VerifyQty THEN '√' ELSE '×' END AS VerifyStatus,
				g.IsSerial	,
				detail.goodsno AS BtypeGoodsNo,
				g.Brand,
				g.KG
		 FROM PD_SellDetail_His detail
			  LEFT JOIN BD_Goods g ON detail.GoodsID=g.GoodsID	
			  LEFT JOIN BD_Whs_Position wp ON detail.WhsPtID = wp.WhsPtID
			  LEFT JOIN 
			(
				SELECT BillCode,DID 
				FROM PD_SellOrdDetail D
				INNER JOIN PD_SellOrdBill b ON d.BillNo = b.BillNo
				UNION ALL
				SELECT BillCode,DID 
				FROM PD_SellOrdDetail_His D
				INNER JOIN PD_SellOrdBill_His b ON d.BillNo = b.BillNo
			) op ON op.DID= detail.OrdDID
			  LEFT JOIN BD_Goods_Ppt1 gp1 ON detail.Ppt1ID = gp1.Ppt1ID
			  LEFT JOIN BD_Goods_Ppt2 gp2 ON detail.Ppt2ID = gp2.Ppt2ID
			  LEFT JOIN BD_Goods_Price gp ON detail.UnitID = gp.UnitID and detail.GoodsID = gp.GoodsID
			  LEFT JOIN BD_Goods_Price gpr1 ON g.GoodsID = gpr1.GoodsID and gpr1.UnitID = 1
			  LEFT JOIN BD_Goods_Price gpr2 ON g.GoodsID = gpr2.GoodsID and gpr2.UnitID = 2
			  LEFT JOIN BD_Goods_Price gpr3 ON g.GoodsID = gpr3.GoodsID and gpr3.UnitID = 3
		  WHERE detail.BillNo = @BillNo
		  ORDER BY detail.DID;  --查询明细  
		  
		  -- 查询多账户信息
		  SELECT FinanceID,Total FROM PD_MulAccounts WHERE BillTypeID = 201 and BillNo = @BillNo  
		  
		  -- 查询单据明细SN
		select Serial,BillDID,ps.Remark from PD_SellSerial_His ps Inner Join PD_SellDetail_His pd on ps.BillDID = pd.DID where pd.BillNo = @BillNo
	
    END                                             
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_SeriesNumStalkQuery]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_PD_SeriesNumStalkQuery
GO

SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：sunzhiyuan
	日期：2015-11-18
	描述：序列号跟踪查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SeriesNumStalkQuery]
(
	@PageNo INT = 1,					-- 页码
	@PageSize INT = 10,					-- 页大小
	@BillStartDate DATETIME,			-- 起始时间
	@BillEndDate DATETIME,				-- 截止时间
	@GoodsTypeID INT = 0,				-- 商品分类
	@WhsID VARCHAR(MAX) = '',			-- 仓库ID
	@BtypeID VARCHAR(MAX) = '',			-- 往来单位ID
	@DeptID  VARCHAR(MAX) = '',			-- 部门ID
	@ElyID VARCHAR(MAX) = '',			-- 经手人ID
	@WhsPtNameMatch INT = 0,			-- 货位名称配置模式:0=包含,1=等于
	@WhsPtName VARCHAR(100) = '',		-- 货位名称
	@GoodsNoMatch INT = 0,				-- 商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',			-- 商品编号
	@GoodsNameMatch INT = 0,			-- 商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',		-- 商品名称
	@SeriesNumMatch INT = 0,			-- 序列号配置模式:0=包含,1=等于
	@SeriesNum VARCHAR(100) = '',		-- 序列号
	@BillType INT = 1,					-- 单据类型
	@OperatorID INT = 0,				-- 操作员
	@IsHistory INT = 0					-- 是否包含归档数据
)
AS
BEGIN
SET NOCOUNT ON

DECLARE @SqlParam NVARCHAR(MAX) = '',@SqlParam2 NVARCHAR(MAX) = '',@Sql NVARCHAR(MAX) = '',@Sqlg NVARCHAR(MAX) = '',
		@BuyStr NVARCHAR(MAX) = '',@BuyRetStr NVARCHAR(MAX) = '',@SaleStr NVARCHAR(MAX) = '',@SaleRetStr NVARCHAR(MAX) = '',
		@InOutIn NVARCHAR(MAX) = '',@InOutOut NVARCHAR(MAX) = '',@LossSpillIn NVARCHAR(MAX) = '',@LossSpillOut NVARCHAR(MAX) = '',
		@AllotTIn NVARCHAR(MAX) = '',@AllotTOut NVARCHAR(MAX) = '',@AllotBIn NVARCHAR(MAX) = '',@AllotBOut NVARCHAR(MAX) = '',
		@AdjPriceIn NVARCHAR(MAX) = '',@AdjPriceOut NVARCHAR(MAX) = '',@AssemblyIn NVARCHAR(MAX) = '',@AssemblyOut NVARCHAR(MAX) = '',
		@KtypeLimit INT = 0,@BtypeLimit INT = 0,@Red varchar(100) = '',@InnerParam NVARCHAR(MAX) = '',@InnerParam2 NVARCHAR(MAX) = '',
		@LimitSql NVARCHAR(MAX) = '' ,@InspectTagStr NVARCHAR(MAX) = '',@IsOpening INT = 0,@OpeningStock NVARCHAR(MAX) = '',@InnerParam999 NVARCHAR(MAX) = '', @ExchangeOut NVARCHAR(MAX) = ''
DECLARE @TVP_Dept AS [TVP_Type]
-- 提示是否包含历史数据
DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@isHistory=@IsHistory
if( @re=1 )return @re;
----------------------查询条件begin---------------------
IF EXISTS(SELECT 1 FROM SS_SysCfg WHERE CfgName='AllotWithInspect' AND CfgValue = 1) --判断是否启用调拨验证
	SELECT @InspectTagStr = ' AND InspectTag = 1 '
	
SET @SqlParam2 += ' WHERE 1 = 1 '
-- 红冲单据，全部需要显示红冲 MODIFY BY WB 160311
IF @BillType = 4
	Set @Red = ' And Red <> 0 '
ELSE IF @BillType <> 1
	Set @Red = ' And Red = 0 '
-- 货位名称
IF @WhsPtName <> ''
BEGIN
	IF @WhsPtNameMatch = 0
		SET @SqlParam2 += 'AND WhsPtName Like ''%''+@WhsPtName+''%'' '  
	IF @WhsPtNameMatch = 1
		SET @SqlParam2 += 'AND WhsPtName = @WhsPtName '  
END
-- 商品编号
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch = 0
		SET @SqlParam2 += 'AND GoodsNo Like ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch = 1
		SET @SqlParam2 += 'AND GoodsNo = @GoodsNo '  
END
-- 商品名称
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch = 0
		SET @SqlParam2 += 'AND GoodsName Like ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch = 1
		SET @SqlParam2 += 'AND GoodsName = @GoodsName '  
END
-- 序列号
IF @SeriesNum <> ''
BEGIN
	IF @SeriesNumMatch = 0
		SET @SqlParam += 'AND Serial Like ''%''+@SeriesNum+''%'' '  
	IF @SeriesNumMatch = 1
		SET @SqlParam += 'AND Serial = @SeriesNum '  
END

-- 部门
IF @DeptID <> ''
BEGIN
	SET @InnerParam +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = Main.DeptID '
	INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
	SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
		INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	SET @InnerParam999 += ' INNER JOIN dbo.UF_OT_Split_Int(@DeptID, '','') _Dept ON _Dept.typeid = 0 '
END

-- 经手人
IF @ElyID <> ''
BEGIN
	SET @InnerParam += ' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = Main.ElyID '
	SET @InnerParam999 += ' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = 0 '
END

-- 仓库
IF @WhsID <> ''
BEGIN
	SET @InnerParam2 += ' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = PagingData.WhsID  '
END

-- 往来单位
IF @BtypeID <> ''
BEGIN
	SET @InnerParam2 += ' INNER JOIN dbo.UF_OT_Split_Int(@BtypeID, '','') _Btype ON _Btype.typeid = PagingData.BtypeID  '
END

-- 商品类型
IF @GoodsTypeID <> 0 AND @GoodsTypeID <> 1
BEGIN
	SET @Sqlg += '
		_GoodsType AS(
			SELECT gt2.GoodsTypeID[typeid] 
			FROM BD_Goods_Type gt 
			INNER JOIN BD_Goods_Type gt2 ON gt2.[Path] LIKE gt.[Path]+''%'' 
			WHERE gt.GoodsTypeID = @GoodsTypeID AND gt2.Stt = 1 
			GROUP BY gt2.GoodsTypeID
		)
		,Goods AS(
			SELECT * FROM BD_Goods g 
			INNER JOIN _GoodsType ON _GoodsType.typeid = g.GoodsTypeID ) '
	SET @InnerParam += ' INNER JOIN Goods Goods ON Goods.GoodsID = Detail.GoodsID  '
	SET @InnerParam999 += ' INNER JOIN Goods Goods ON Goods.GoodsID = Detail.GoodsID  '
END
ELSE
BEGIN
	SET @Sqlg += ' Goods AS(SELECT GoodsID FROM BD_Goods g  WHERE 1 = 1) '
END
----------------------查询条件end---------------------

-- 仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)
IF @KtypeLimit = 1  --部份权限
		SET @LimitSql += ' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = PagingData.WhsID '
-- 往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
		SET @LimitSql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID = PagingData.BTypeID '

-- 全部\红冲1\4 入库2 出库3 
IF OBJECT_ID('tempdb..#BillType','U') IS NOT NULL DROP TABLE #BillType
CREATE TABLE #BillType(billtype INT)
IF @BillType = 1 OR @BillType = 4		
	INSERT INTO #BillType SELECT BillTypeID FROM PD_BillType WHERE CanPost = 1 AND BillTypeID IN (101,102,201,202,301,302,303,304,305,306,309,310,600) --,102,201,202,301,302,303,304,305,306,309,310
ELSE IF @BillType = 2
	INSERT INTO #BillType SELECT BillTypeID FROM PD_BillType WHERE CanPost = 1 AND BillTypeID IN (101,202,301,302,303,306,309,310)
ELSE
	INSERT INTO #BillType SELECT BillTypeID FROM PD_BillType WHERE CanPost = 1 AND BillTypeID IN (102,201,301,302,304,305,309,310,600)

-- 是否查询期初数据
IF EXISTS(SELECT Convert(varchar(10),StartDate,120) as StartDate FROM Ss_MonthProc WHERE Period = 1 AND StartDate BETWEEN @BillStartDate AND @BillEndDate)
BEGIN
	SELECT @IsOpening = 999
	INSERT INTO #BillType (billtype) VALUES (@IsOpening)
END

SET @BuyStr += ' ''采购入库单'' AS BillName,Main.PosTime, Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,Main.BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @SaleRetStr += ' ''销售退货单'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,Main.BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @InOutIn += ' ''其他入库单'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,Main.BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @LossSpillIn += ' ''报溢单'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AllotTIn += ' ''同价调拨单(入库)'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.InWhsPtID AS WhsPtID, Detail.InWhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AllotBIn += ' ''变价调拨单(入库)'' AS BillName,Main.PosTime, Main.BillNo,Main.Red,Main.BillCode,Detail.InWhsPtID AS WhsPtID, Detail.InWhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AdjPriceIn += ' ''调价单(入库)'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AssemblyIn += ' ''生产拆装单(入库)'' AS BillName,Main.PosTime, Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark]'

SET @BuyRetStr += ' ''采购退货单'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,Main.BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @SaleStr += ' ''销售出库单'' AS BillName,Main.PosTime, Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,Main.BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @InOutOut += ' ''其他出库单'' AS BillName,Main.PosTime, Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,Main.BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @ExchangeOut = REPLACE(@InOutOut, '其他出库单','积分兑换单')

SET @LossSpillOut += ' ''报损单'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AllotTOut += ' ''同价调拨单(出库)'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.OutWhsPtID AS WhsPtID, Detail.OutWhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AllotBOut += ' ''变价调拨单(出库)'' AS BillName,Main.PosTime, Main.BillNo,Main.Red,Main.BillCode,Detail.OutWhsPtID AS WhsPtID, Detail.OutWhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AdjPriceOut += ' ''调价单(出库)'' AS BillName,Main.PosTime, Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark] '

SET @AssemblyOut += ' ''生产拆装单(出库)'' AS BillName, Main.PosTime,Main.BillNo,Main.Red,Main.BillCode,Detail.WhsPtID , Detail.WhsID AS WhsID,0 AS BTypeID,Main.DeptID,Main.ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],Serial.CostPrice[SeriesNumCost],Serial.Remark[SeriesNumRemark]'

SET @OpeningStock += ' ''期初数据'' AS BillName,'''' AS PosTime, '''' AS BillNo,0 AS Red,'''' AS BillCode,Detail.WhsPtID , Main.WhsID,0 AS BTypeID,0 AS DeptID,0 AS ElyID,Detail.GoodsID,Detail.Ppt1ID,Detail.Ppt2ID,Serial.Serial[SeriesNum],0 AS SeriesNumCost,Serial.Remark[SeriesNumRemark] '

SELECT @sql += '
	UNION ALL 
	SELECT ' + CAST(BillTypeID AS VARCHAR) + ' AS BillTypeID, '
	+ CASE  WHEN BillTypeID = 101 THEN @buyStr
			WHEN BillTypeID = 102 THEN @buyRetStr
			WHEN BillTypeID = 201 THEN @SaleStr
			WHEN BillTypeID = 202 THEN @saleRetStr
			ELSE '' END	
	+ ' FROM  ' + BillDetail + ' Detail INNER JOIN ' + BillTable + ' Main ON Main.BillNo = Detail.BillNo '
	+ ' INNER JOIN ' + BillSerial + ' Serial ON Detail.DID = Serial.BillDID '
	+ @InnerParam
	+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @SqlParam + @Red 
FROM PD_BillType b
INNER JOIN #BillType T ON b.billtypeid = T.billtype OR T.billtype = 0 
WHERE CanPost = 1 AND billtype NOT IN (301,302,303,304,305,306,309,310,600,@IsOpening)
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 303) -- 其他入库单
BEGIN
	SELECT @Sql += '
		UNION ALL 
			SELECT 303 AS BillTypeID, ' + @InOutIn + ' 
			FROM  PD_InOutWhsDetail Detail INNER JOIN PD_InOutWhsBill Main ON Main.BillNo = Detail.BillNo '
			+ ' INNER JOIN PD_InOutWhsSerial Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
			+ @InnerParam
			+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 303 ' + @SqlParam + @Red	
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 304) -- 其他出库单
BEGIN
	SELECT @Sql += '
		UNION ALL 
			SELECT 304 AS BillTypeID, ' + @InOutOut + ' 
			FROM  PD_InOutWhsDetail Detail INNER JOIN PD_InOutWhsBill Main ON Main.BillNo = Detail.BillNo '
			+ ' INNER JOIN PD_InOutWhsSerial Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
			+ @InnerParam
			+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 304 ' + @SqlParam + @Red	
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 600) -- 积分兑换单
BEGIN
	SELECT @Sql += '
		UNION ALL 
			SELECT 600 AS BillTypeID, ' + @ExchangeOut + ' 
			FROM  PD_InOutWhsDetail Detail INNER JOIN PD_InOutWhsBill Main ON Main.BillNo = Detail.BillNo '
			+ ' INNER JOIN PD_InOutWhsSerial Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
			+ @InnerParam
			+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 600 ' + @SqlParam + @Red	
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 306) -- 报损单
BEGIN
	SELECT @Sql += '
		UNION ALL 
			SELECT 306 AS BillTypeID, ' + @LossSpillIn + ' 
			FROM  PD_LossSpillDetail Detail INNER JOIN PD_LossSpillBill Main ON Main.BillNo = Detail.BillNo '
			+ ' INNER JOIN PD_LossSpillSerial Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
			+ @InnerParam
			+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 306 ' + @SqlParam + @Red	
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 305) -- 报溢单
BEGIN
	SELECT @Sql += '
		UNION ALL 
			SELECT 305 AS BillTypeID, ' + @LossSpillOut + ' 
			FROM  PD_LossSpillDetail Detail INNER JOIN PD_LossSpillBill Main ON Main.BillNo = Detail.BillNo '
			+ ' INNER JOIN PD_LossSpillSerial Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
			+ @InnerParam
			+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 305 ' + @SqlParam + @Red	
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 301) -- 同价调拨单
BEGIN
	IF @BillType <> 3
		SELECT @Sql += '
			UNION ALL 
				SELECT 301 AS BillTypeID, ' + @AllotTIn + ' 
				FROM  PD_AllotDetail Detail INNER JOIN PD_AllotBill Main ON Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AllotSerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @InspectTagStr + ' AND Main.BillTypeID = 301 ' + @SqlParam + @Red
	IF @BillType <> 2
		SELECT @Sql += '
			UNION ALL 
				SELECT 301 AS BillTypeID, ' + @AllotTOut + ' 
				FROM  PD_AllotDetail Detail INNER JOIN PD_AllotBill Main ON Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AllotSerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 301 ' + @SqlParam + @Red	
END	
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 302) -- 调价单
BEGIN
	IF @BillType <> 3
		SELECT @Sql += '
			UNION ALL 
				SELECT 302 AS BillTypeID, ' + @AdjPriceIn + ' 
				FROM  PD_AdjPriceDetail Detail  Inner Join PD_AdjPriceBill Main On Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AdjPriceSerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @SqlParam + @Red		
	IF @BillType <> 2
		SELECT @Sql += '
			UNION ALL 
				SELECT 302 AS BillTypeID, ' + @AdjPriceOut + ' 
				FROM  PD_AdjPriceDetail Detail  Inner Join PD_AdjPriceBill Main On Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AdjPriceSerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @SqlParam + @Red
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 309) -- 变价调拨单
BEGIN
	IF @BillType <> 3
		SELECT @Sql += '
			UNION ALL 
				SELECT 309 AS BillTypeID, ' + @AllotBIn + ' 
				FROM  PD_AllotDetail Detail  Inner Join PD_AllotBill Main On Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AllotSerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @InspectTagStr + ' AND Main.BillTypeID = 309 ' + @SqlParam + @Red		
	IF @BillType <> 2
		SELECT @Sql += '
			UNION ALL 
				SELECT 309 AS BillTypeID, ' + @AllotBOut + ' 
				FROM  PD_AllotDetail Detail  Inner Join PD_AllotBill Main On Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AllotSerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 309 ' + @SqlParam + @Red
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 310) -- 生产拆装单
BEGIN
	IF @BillType <> 3
		SELECT @Sql += '
			UNION ALL 
				SELECT 310 AS BillTypeID, ' + @AssemblyIn + ' 
				FROM  PD_AssemblyDetail Detail  Inner Join PD_AssemblyBill Main On Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AssemblySerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Detail.DetailType = 1 ' + @SqlParam + @Red		
	IF @BillType <> 2
		SELECT @Sql += '
			UNION ALL 
				SELECT 310 AS BillTypeID, ' + @AssemblyOut + ' 
				FROM  PD_AssemblyDetail Detail  Inner Join PD_AssemblyBill Main On Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_AssemblySerial Serial ON Detail.DID = Serial.BillDID '
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Detail.DetailType = 2 ' + @SqlParam + @Red
END
IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 999) AND @BillType = 1 -- 期初数据(全部才查询期初 MODIFY BY WB 160311)
BEGIN
	SELECT @Sql += '
		UNION ALL 
			SELECT 999 AS BillTypeID, ' + @OpeningStock + ' 
			FROM  BD_OpeningStock_Detail Detail  Inner Join BD_OpeningStock Main On Main.GoodsID = Detail.GoodsID '
			+ ' INNER JOIN BD_OpeningSerial Serial ON Detail.DetailID = Serial.StockDetailID '
			+ @InnerParam999
			+ ' WHERE 1 = 1 ' + @SqlParam
END
-- 历史数据
IF @IsHistory = 1
BEGIN
	SELECT @sql += '
		UNION ALL 
		SELECT ' + CAST(BillTypeID AS VARCHAR) + ' AS BillTypeID, '
		+ CASE  WHEN BillTypeID = 101 THEN @buyStr
				WHEN BillTypeID = 102 THEN @buyRetStr
				WHEN BillTypeID = 201 THEN @SaleStr
				WHEN BillTypeID = 202 THEN @saleRetStr
				ELSE '' END	
		+ ' FROM  ' + BillDetail + '_His Detail INNER JOIN ' + BillTable + '_His Main ON Main.BillNo = Detail.BillNo '
		+ ' INNER JOIN ' + BillSerial + '_His Serial ON Detail.DID = Serial.BillDID '
		+ @InnerParam
		+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @SqlParam + @Red 
	FROM PD_BillType b
	INNER JOIN #BillType T ON b.billtypeid = T.billtype OR T.billtype = 0 
	WHERE CanPost = 1 AND billtype NOT IN (301,302,303,304,305,306,309,310,600)
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 303) -- 其他入库单
	BEGIN
		SELECT @Sql += '
			UNION ALL 
				SELECT 303 AS BillTypeID, ' + @InOutIn + ' 
				FROM  PD_InOutWhsDetail_His Detail INNER JOIN PD_InOutWhsBill_His Main ON Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_InOutWhsSerial_His Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 303 ' + @SqlParam + @Red	
	END
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 304) -- 其他出库单
	BEGIN
		SELECT @Sql += '
			UNION ALL 
				SELECT 304 AS BillTypeID, ' + @InOutOut + ' 
				FROM  PD_InOutWhsDetail_His Detail INNER JOIN PD_InOutWhsBill_His Main ON Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_InOutWhsSerial_His Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 304 ' + @SqlParam + @Red	
	END
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 600) -- 积分兑换单
	BEGIN
		SELECT @Sql += '
			UNION ALL 
				SELECT 600 AS BillTypeID, ' + @ExchangeOut + ' 
				FROM  PD_InOutWhsDetail_His Detail INNER JOIN PD_InOutWhsBill_His Main ON Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_InOutWhsSerial_His Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 600 ' + @SqlParam + @Red	
	END
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 305) -- 报损单
	BEGIN
		SELECT @Sql += '
			UNION ALL 
				SELECT 305 AS BillTypeID, ' + @LossSpillOut + ' 
				FROM  PD_LossSpillDetail_His Detail INNER JOIN PD_LossSpillBill_His Main ON Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_LossSpillSerial_His Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 305 ' + @SqlParam + @Red	
	END
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 306) -- 报溢单
	BEGIN
		SELECT @Sql += '
			UNION ALL 
				SELECT 306 AS BillTypeID, ' + @LossSpillIn + ' 
				FROM  PD_LossSpillDetail_His Detail INNER JOIN PD_LossSpillBill_His Main ON Main.BillNo = Detail.BillNo '
				+ ' INNER JOIN PD_LossSpillSerial_His Serial ON Detail.DID = Serial.BillDID AND Serial.BillTypeID = Main.BillTypeID'
				+ @InnerParam
				+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 306 ' + @SqlParam + @Red	
	END
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 301) -- 同价调拨单
	BEGIN
		IF @BillType <> 3
			SELECT @Sql += '
				UNION ALL 
					SELECT 301 AS BillTypeID, ' + @AllotTIn + ' 
					FROM  PD_AllotDetail_His Detail INNER JOIN PD_AllotBill_His Main ON Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AllotSerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @InspectTagStr + ' AND Main.BillTypeID = 301 ' + @SqlParam + @Red
		IF @BillType <> 2
			SELECT @Sql += '
				UNION ALL 
					SELECT 301 AS BillTypeID, ' + @AllotTOut + ' 
					FROM  PD_AllotDetail_His Detail INNER JOIN PD_AllotBill_His Main ON Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AllotSerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Main.BillTypeID = 301 ' + @SqlParam + @Red	
	END	
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 302) -- 调价单
	BEGIN
		IF @BillType <> 3
			SELECT @Sql += '
				UNION ALL 
					SELECT 302 AS BillTypeID, ' + @AdjPriceIn + ' 
					FROM  PD_AdjPriceDetail_His Detail  Inner Join PD_AdjPriceBill_His Main On Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AdjPriceSerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @SqlParam + @Red		
		IF @BillType <> 2
			SELECT @Sql += '
				UNION ALL 
					SELECT 302 AS BillTypeID, ' + @AdjPriceOut + ' 
					FROM  PD_AdjPriceDetail_His Detail  Inner Join PD_AdjPriceBill_His Main On Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AdjPriceSerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 ' + @SqlParam + @Red
	END
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 309) -- 变价调拨单
	BEGIN
		IF @BillType <> 3
			SELECT @Sql += '
				UNION ALL 
					SELECT 309 AS BillTypeID, ' + @AllotBIn + ' 
					FROM  PD_AllotDetail_His Detail  Inner Join PD_AllotBill_His Main On Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AllotSerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 '+ @InspectTagStr +' AND Main.BillTypeID = 309 ' + @SqlParam + @Red		
		IF @BillType <> 2
			SELECT @Sql += '
				UNION ALL 
					SELECT 309 AS BillTypeID, ' + @AllotBOut + ' 
					FROM  PD_AllotDetail_His Detail  Inner Join PD_AllotBill_His Main On Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AllotSerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND  Main.BillTypeID = 309 ' + @SqlParam + @Red
	END
	IF EXISTS (SELECT 1 FROM #BillType WHERE billtype = 310) -- 生产拆装单
	BEGIN
		IF @BillType <> 3
			SELECT @Sql += '
				UNION ALL 
					SELECT 310 AS BillTypeID, ' + @AssemblyIn + ' 
					FROM  PD_AssemblyDetail_His Detail  Inner Join PD_AssemblyBill_His Main On Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AssemblySerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Detail.DetailType = 1 ' + @SqlParam + @Red		
		IF @BillType <> 2
			SELECT @Sql += '
				UNION ALL 
					SELECT 310 AS BillTypeID, ' + @AssemblyOut + ' 
					FROM  PD_AssemblyDetail_His Detail  Inner Join PD_AssemblyBill_His Main On Main.BillNo = Detail.BillNo '
					+ ' INNER JOIN PD_AssemblySerial_His Serial ON Detail.DID = Serial.BillDID '
					+ @InnerParam
					+ ' WHERE Main.BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft = 0 AND Detail.DetailType = 2 ' + @SqlParam + @Red
	END	
END


SELECT @sql= '
;WITH '+ @Sqlg +' ,PagingData AS
 ('
	+ STUFF(@sql,1,13,'')+
' )'

SET @Sql +=',CData AS (
	SELECT PagingData.*,WhsNO,WhsName,WhsPtNO,WhsPtName,BTypeCode,BTypeName,DeptCode,DeptName,ElyCode,ElyName,GoodsNo,GoodsName,Ppt1.Value[Spec1],Ppt2.Value[Spec2] ' 
SET @sql += ' FROM PagingData
	LEFT JOIN BD_Dept Dept ON PagingData.DeptID = Dept.DeptID                               
	LEFT JOIN BD_Employee Employee ON PagingData.ElyID = Employee.ElyID
	INNER JOIN BD_Whs Whs ON PagingData.WhsID = Whs.WhsID
	LEFT JOIN BD_Whs_Position Position ON PagingData.WhsPtID = Position.WhsPtID
	LEFT JOIN BD_Btype Btype ON PagingData.BTypeID = Btype.BTypeID                 
	INNER JOIN BD_Goods Goods ON PagingData.GoodsID = Goods.GoodsID
	LEFT JOIN BD_Goods_Ppt1 Ppt1 ON PagingData.Ppt1ID = Ppt1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 Ppt2 ON PagingData.Ppt2ID = Ppt2.Ppt2ID 
	' + @InnerParam2 + @LimitSql + @SqlParam2 + ' ) '
	
-- 分页
SET @sql += ' SELECT *  FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM CData) A
		CROSS JOIN
		(
			SELECT ROW_NUMBER() OVER( ORDER BY SeriesNum ,PosTime ) AS ROWID,* FROM CData 
		) B
		WHERE B.ROWID > (@PageNo - 1) * @PageSize AND B.ROWID <= @PageNo * @PageSize '

DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	 WHILE (@curPos < len(@sql))  
	 BEGIN  
		 PRINT substring(@sql, @curPos, @curPos + 3999)  
		 SET @curPos += 3999 + 1  
		 SET @count += 1  
	 END

-- 返回一个空记录，不让页面报错
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  
	RETURN 
END

-- 没有权限
IF @KtypeLimit = 0 OR @BtypeLimit = 0 
	SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'

EXEC sp_executesql @Sql,N'@PageNo Int, @PageSize Int, @BillStartDate DATETIME, @BillEndDate DATETIME, @GoodsTypeID INT, @WhsID VARCHAR(MAX), @BtypeID VARCHAR(MAX), @DeptID  VARCHAR(MAX),
						  @ElyID VARCHAR(MAX), @WhsPtNameMatch INT, @WhsPtName VARCHAR(100), @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),
						  @SeriesNumMatch INT, @SeriesNum VARCHAR(100), @BillType INT, @OperatorID INT, @IsHistory INT,@TVP_Dept TVP_Type READONLY',
						  @PageNo, @PageSize, @BillStartDate, @BillEndDate, @GoodsTypeID, @WhsID, @BtypeID, @DeptID,
						  @ElyID, @WhsPtNameMatch, @WhsPtName, @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName,
						  @SeriesNumMatch, @SeriesNum, @BillType, @OperatorID, @IsHistory,@TVP_Dept
			
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_SeriesNumStockQuery]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE UP_PD_SeriesNumStockQuery
GO

SET ANSI_NULLS ON
GO


SET QUOTED_IDENTIFIER ON
GO


/*------------------------------------------
    作者：sunzhiyuan
	日期：2015-5-27
	描述：序列号库存查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SeriesNumStockQuery]
(
	@PageNo INT = 1,					-- 页码
	@PageSize INT = 10,					-- 页大小
	@WhsID VARCHAR(MAX) = '',         	-- 仓库
	@WhsPtNameMatch INT = 0,			-- 货位名称配置模式:0=包含,1=等于
	@WhsPtName VARCHAR(100) = '',		-- 货位名称
	@GoodsTypeID INT = 0,				-- 商品分类
	@GoodsNoMatch INT = 0,				-- 商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(100) = '',			-- 商品编号
	@GoodsNameMatch INT = 0,			-- 商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(100) = '',		-- 商品名称
	@SeriesNumMatch INT = 0,			-- 序列号配置模式:0=包含,1=等于
	@SeriesNum VARCHAR(100) = '',		-- 序列号
	@SeriesNumNote VARCHAR(100),		-- 序列号备注
	@OperatorID INT = 0,				-- 操作员ID
	/*来自库存状况表的参数*/
	@GoodsID INT = 0,                   --商品ID
	@Spec VARCHAR(50) = '',             --规格
	@SpecMatch INT = 0,                 --规格匹配方式 0:包含 1:等于
	@SpecSum INT = 0,                   --规格
	@Model VARCHAR(50) = '',            --型号
	@ModelMatch INT = 0,                --型号匹配方式 0:包含 1:等于
	@ModelSum INT = 0,                  --型号
	@AbbName VARCHAR(50) = '',          --简名
	@AbbNameMatch INT = 0,              --简名匹配方式 0:包含 1:等于
	@Brand VARCHAR(50) = '',            --品牌
	@BrandMatch INT = 0,				--品牌匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',          --条码
	@BarCodeMatch INT = 0,              --条码匹配方式 0:包含 1:等于
	@BatchNo VARCHAR(50) = '',          --批号
	@BatchNoMatch INT = 0,              --批号匹配方式 0:包含 1:等于
	@ProductDateStart VARCHAR(25) = '', --生产日期范围起
	@ProductDateEnd VARCHAR(25) = '',   --生产日期范围始
	@EndDateStart VARCHAR(25) = '',     --到期日期范围起
	@EndDateEnd VARCHAR(25) = '',       --到期日期范围始
	@NearDateStart VARCHAR(25) = '',    --近效日期范围起
	@NearDateEnd VARCHAR(25) = ''       --近效日期范围始
)
AS
BEGIN
SET NOCOUNT ON
	DECLARE @HeadSql NVARCHAR(MAX),@Sql NVARCHAR(MAX),@SqlParam NVARCHAR(MAX) = N'',
			@SqlInner NVARCHAR(MAX) = N'',@PageDataName NVARCHAR(MAX) = N'PagingData',@KtypeLimit INT = 0,
			@Sqlg NVARCHAR(MAX) = N''
	        
	----------------------------------查询条件----------------------------------
	SET @SqlParam='WHERE 1=1 AND GS.Flag = 1 '
	
	-- 仓库
	IF @WhsID <> ''
	BEGIN
		SET @SqlInner += ' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = GS.WhsID  '
	END
	
	-- 货位
	IF @WhsPtName <> ''
	BEGIN
		-- 模糊查询
		IF @WhsPtNameMatch = 0
			SET @SqlParam += ' AND WHSPT.WhsPtName Like ''%'' + @WhsPtName + ''%'' '  
		-- 精确查询
		IF @WhsPtNameMatch = 1
			SET @SqlParam += ' AND WHSPT.WhsPtName = @WhsPtName '
	END
	
	-- 商品编号
	IF @GoodsNo <> ''
	BEGIN
		-- 模糊查询
		IF @GoodsNoMatch = 0
			SET @SqlParam += ' AND Goods.GoodsNo Like ''%''+@GoodsNo+''%'' '  
		-- 精确查询
		IF @GoodsNoMatch = 1
			SET @SqlParam += ' AND Goods.GoodsNo = @GoodsNo '  
	END
	
	-- 商品名称
	IF @GoodsName <> ''
	BEGIN
		-- 模糊查询
		IF @GoodsNameMatch = 0
			SET @SqlParam += ' AND Goods.GoodsName Like ''%''+@GoodsName+''%'' '  
		-- 精确查询
		IF @GoodsNameMatch = 1
			SET @SqlParam += ' AND Goods.GoodsName = @GoodsName '  
	END
	
	/*处理库存状况表的参数 start*/	
	-- 商品名称
	IF @GoodsID <> 0
	BEGIN
		SET @SqlParam += ' AND Goods.GoodsID = @GoodsID '
	END
	ELSE
	BEGIN
		IF @Spec <> '' OR @SpecSum = 1  --商品规格(汇总时可能为空但是精确匹配)
		BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND Goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND Goods.Spec = @Spec '  
		END 
		IF @Model <> '' OR @ModelSum = 1      --商品型号(汇总时可能为空但是精确匹配)
		BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND Goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND Goods.Model = @Model ' 
		END 
		IF @AbbName <> ''    --商品简名
		BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND Goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND Goods.GoodsAbbName = @AbbName ' 
		END       
		IF @Brand <> ''      --商品品牌
		BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND Goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND Goods.Brand = @Brand ' 
		END
		IF @BarCode <> ''      --商品条码
		BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = Goods.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND barcode.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
		END
	END
	
	/*处理库存状况表的参数 end*/
	
	-- 序列号
	IF @SeriesNum <> ''
	BEGIN
		-- 模糊查询
		IF @SeriesNumMatch = 0
			SET @SqlParam += ' AND GS.Serial Like ''%''+@SeriesNum+''%'' '  
		-- 精确查询
		IF @SeriesNumMatch = 1
			SET @SqlParam += ' AND GS.Serial = @SeriesNum '  
	END

	-- 序列号备注
	IF @SeriesNumNote <> ''
	BEGIN
		SET @SqlParam += ' AND GS.Remark Like ''%''+@SeriesNumNote+''%'' '
	END
	
	-- 批号
	IF @BatchNo <> ''
	BEGIN
		-- 模糊查询
		IF @BatchNoMatch = 0
			SET @SqlParam += ' AND GS.BatchNumber Like ''%''+@BatchNo+''%'' '  
		-- 精确查询
		IF @BatchNoMatch = 1
			SET @SqlParam += ' AND GS.BatchNumber = @BatchNo '  
	END
	
	--生产日期范围
	IF @ProductDateStart <> '' AND @ProductDateEnd <> '' 
		SET @SqlParam += ' AND GS.ProductDate <> '''' AND GS.ProductDate BETWEEN CONVERT(DATE, @ProductDateStart) AND CONVERT(DATE, @ProductDateEnd) '
	
	--到期日期范围
	IF @EndDateStart <> '' AND @EndDateEnd <> '' 
		SET @SqlParam += ' AND GS.EndDate <> '''' AND GS.EndDate BETWEEN CONVERT(DATE, @EndDateStart) AND CONVERT(DATE, @EndDateEnd) '
	
	--近效日期范围
	IF @NearDateStart <> '' AND @NearDateEnd <> '' 
		SET @SqlParam += ' AND GS.EndDate <> '''' AND DATEADD(dd,-Goods.NearbyDays,CONVERT(DATE, GS.EndDate)) BETWEEN CONVERT(DATE, @NearDateStart) AND CONVERT(DATE, @NearDateEnd) '

	-- 商品类型
	IF @GoodsTypeID <> 0 AND @GoodsTypeID <> 1
	BEGIN
		SET @Sqlg += '
			_GoodsType AS(
				SELECT gt2.GoodsTypeID[typeid] 
				FROM BD_Goods_Type gt 
				INNER JOIN BD_Goods_Type gt2 ON gt2.[Path] LIKE gt.[Path]+''%'' 
				WHERE gt.GoodsTypeID = @GoodsTypeID AND gt2.Stt = 1 
				GROUP BY gt2.GoodsTypeID
			)
			,Goods AS(
				SELECT * FROM BD_Goods g 
				INNER JOIN _GoodsType ON _GoodsType.typeid = g.GoodsTypeID ) '
	END
	ELSE
	BEGIN
		SET @Sqlg += ' Goods AS(SELECT * FROM BD_Goods g  WHERE 1 = 1) '
	END

	/*权限使用公用方法*/
	--仓库权限
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
	IF @KtypeLimit = 1 --部份权限
	   SET @SqlInner +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = WHS.WhsID '

	-- 仓库编号,仓库名称;
	-- 仓位编号,仓位名称;
	-- 商品编号,商品名称;
	-- 属性一,属性二;
	-- 序列号,序列号备注,入库时间
	SET @HeadSql = N';With ' + @Sqlg +' ,PagingData AS (
						SELECT WHS.WhsNO,WHS.WhsName,
								WHSPT.WhsPtNO,WHSPT.WhsPtName,
								Goods.GoodsNo,Goods.GoodsName,GP1.Value AS Spec1,
								GP2.Value AS Spec2,
								GS.Serial,GS.Remark,GS.InTime,GS.BatchNumber,
								GS.ProductDate, GS.EndDate, 
								CASE WHEN g.CostMethod = 1 THEN GoodsStock.Price 
								ELSE GS.CostPrice END AS CostPrice,
								(CASE WHEN GS.EndDate <> '''' THEN CONVERT(VARCHAR, DATEADD(dd,-Goods.NearbyDays,CONVERT(DATE, GS.EndDate)), 121)
								ELSE GS.EndDate END) AS NearDate
								FROM PD_GoodsSerial GS  
									INNER JOIN BD_Goods g ON GS.GoodsID = g.GoodsID
									INNER JOIN PD_GoodsStock GoodsStock ON GS.GoodsID = GoodsStock.GoodsID AND GS.WhsID=GoodsStock.WhsID  AND GoodsStock.Qty>0
									INNER jOIN BD_Whs WHS ON GS.WhsID = WHS.WhsID
									LEFT JOIN BD_Whs_Position WHSPT ON GS.WhsPtID = WHSPT.WhsPtID
									INNER JOIN Goods Goods ON GS.GoodsID = Goods.GoodsID
									LEFT JOIN BD_Goods_Ppt1 GP1 ON GS.Ppt1ID = GP1.Ppt1ID
									LEFT JOIN BD_Goods_Ppt2 GP2 ON GS.Ppt2ID = GP2.Ppt2ID
					'
					
	-- 组合SQL代码块
    SET @Sql = @HeadSql + @SqlInner + @SqlParam 
    
    
    -- 分页
    SET @Sql+=' ) SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A
				CROSS JOIN
				(SELECT	ROW_NUMBER() OVER( ORDER BY Serial ) AS ROWID,* FROM PagingData) B
				WHERE B.ROWID > (@PageNo - 1) * @PageSize AND B.ROWID <= @PageNo * @PageSize '
	
	-- 没有权限
	IF @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
	
	print @Sql
	
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @WhsID VARCHAR(100), @WhsPtNameMatch INT, @WhsPtName VARCHAR(100),
	                           @GoodsTypeID INT, @GoodsNoMatch INT, @GoodsNo VARCHAR(100), @GoodsNameMatch INT, @GoodsName VARCHAR(100),
	                           @SeriesNumMatch INT, @SeriesNum VARCHAR(100), @SeriesNumNote VARCHAR(100), @OperatorID INT, @GoodsID INT, 
	                           @Spec VARCHAR(50), @Model VARCHAR(50), @AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(20),
	                           @BatchNo VARCHAR(50), @ProductDateStart VARCHAR(25), @ProductDateEnd VARCHAR(25),
	                           @EndDateStart VARCHAR(25), @EndDateEnd VARCHAR(25), @NearDateStart VARCHAR(25), @NearDateEnd VARCHAR(25)', 
							 @PageNo, @PageSize, @WhsID, @WhsPtNameMatch, @WhsPtName,
							 @GoodsTypeID, @GoodsNoMatch, @GoodsNo, @GoodsNameMatch, @GoodsName,
	                         @SeriesNumMatch, @SeriesNum, @SeriesNumNote, @OperatorID,
	                         @GoodsID, @Spec, @Model, @AbbName, @Brand, @BarCode,
	                         @BatchNo, @ProductDateStart, @ProductDateEnd,
	                         @EndDateStart, @EndDateEnd, @NearDateStart, @NearDateEnd
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_SignBill]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_SignBill
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-06-05
	描述：签收单据
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_SignBill]
(
	@BillNo			INT=0,
	@BillTypeID		INT=0
) 
AS

IF @BillTypeID = 100
BEGIN
	IF NOT EXISTS(SELECT 1 FROM PD_PchOrdBill WHERE AuditStatus = 4 AND BillNo = @BillNo) RETURN -1 --审核未通过，无法签收
END ELSE
IF @BillTypeID = 101
BEGIN
	IF NOT EXISTS(SELECT 1 FROM PD_PchBill WHERE AuditStatus = 4 AND BillNo = @BillNo) RETURN -1 --审核未通过，无法签收
END

IF NOT EXISTS(SELECT 1 FROM dbo.PD_AuditingBill WHERE BillNo = @BillNo AND BillTypeID = @BillTypeID) RETURN -2 --无审核相关记录，无法签收

UPDATE dbo.PD_AuditingBill SET SignStatus = 1 WHERE BillNo = @BillNo AND BillTypeID = @BillTypeID

RETURN 0

GO





IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockCheck]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_StockCheck]
GO
/****** Object:  StoredProcedure [UP_PD_StockCheck]    Script Date: 05/27/2014 16:12:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/5/27
-- Description:	 库存盘点
-- =============================================
CREATE PROCEDURE [UP_PD_StockCheck](
     @PageNo INT = 0,
     @PageSize INT = 0,
	 @BillStartDate DATETIME, --录单日期查询开始时间
	 @BillEndDate  DATETIME,  --录单日期查询结束时间
	 @OperatorID INT = 0, --操作员ID
	 @WhsID VARCHAR(1000) = '',  --仓库
	 @DeptID VARCHAR(1000) = '',  --部门
	 @ElyID VARCHAR(1000) = '',  --经手人
	 @GoodsID VARCHAR(1000)= '',  --商品
	 @GoodsTypeID INT = 0,  --商品分类
	 @Stt INT = 2  --盘点状态 (2=全部,0=未处理,1=已处理) 
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @Sql NVARCHAR(MAX) = '', @SqlParam NVARCHAR(MAX), @SqlLSHis NVARCHAR(500) = '', @EndDate DATETIME,
	        @TVP_Dept AS [TVP_Type], @TVP_GoodsType AS [TVP_Type], @KtypeLimit INT = 0 
	          
	SELECT @EndDate = Max(EndDate) FROM SS_MonthProc where [State] = 1 
	
	IF @EndDate IS NOT NULL AND @EndDate > @BillStartDate
	   SET @SqlLSHis = ' UNION ALL (SELECT BillNo AS LSBillNo, BillCode AS LSBillCode, StockBillNo AS StockBillNo, BillTypeID from PD_LossSpillBill_His WHERE Red <> 2) ' 
	
    SET @Sql = ' ;WITH PagingData AS 
			  (SELECT a.BillNo, a.Stt, a.BillDate, a.BillCode, a.WhsID, a.DeptID, a.ElyID,
					  a.Summary FROM PD_StockBill a '	
					  
    SET @SqlParam = ' WHERE a.BillDate BETWEEN @BillStartDate AND @BillEndDate '
                         
    --仓库权限 
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	                   
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON a.WhsID = rWhs.WhsID '
        
    IF @WhsID <> ''
	   SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = a.WhsID '
       
    IF @DeptID <> ''
       BEGIN
	     SET @Sql +=' INNER JOIN @TVP_Dept _dept ON _dept.ChildTypeID = a.DeptID '
         INSERT INTO @TVP_Dept([TypeID],[ChildTypeID]) 
	     SELECT d.DeptID, cd.DeptID FROM BD_Dept d 
	         INNER JOIN BD_Dept cd ON cd.[Path] Like d.[Path] + '%'
		     WHERE EXISTS (SELECT 1 FROM dbo.UF_OT_Split_Int(@DeptID, ',') _Dept WHERE _Dept.typeid = d.DeptID)
	   END
              
    IF @ElyID <> ''
	   SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = a.ElyID ' 
         
    IF @GoodsID <> '' OR @GoodsTypeID <> 0
	   SET @Sql += ' INNER JOIN [PD_StockDetail] detail ON detail.BillNo = a.BillNo '
       
    IF @GoodsID <> ''
       SET @Sql +=' INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid = detail.GoodsID ' 
            
    IF @GoodsTypeID <> 0
       BEGIN
            --可以选非子节点的商品分类，需找出该分类下的所有子节点
			INSERT INTO @TVP_GoodsType([TypeID],[ChildTypeID]) 
			SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM BD_Goods_Type gt 
				 INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
				 WHERE 	gt.GoodsTypeID = @GoodsTypeID and cgt.SonNum = 0
			SET @Sql +=' INNER JOIN [BD_Goods] goods ON goods.GoodsID = detail.GoodsID
			             INNER JOIN @TVP_GoodsType goodsType ON goodsType.ChildTypeID = goods.GoodsTypeID '
       END 
                  
    IF @Stt <> 2
       SET @SqlParam +=' AND a.Stt = @Stt '		
	  
    SET @Sql= N'SET NOCOUNT ON;' + @Sql + @SqlParam + ' )' +
			 N', _DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName from BD_Whs)
			   , _DATA_Dept AS (SELECT DeptID AS DID, DeptCode, DeptName from BD_Dept)
			   , _DATA_Ely AS (SELECT ElyID AS EID, ElyCode, ElyName from BD_Employee)
			   , _DATA_LSBill AS (SELECT BillNo AS LSBillNo, BillCode AS LSBillCode, StockBillNo AS StockBillNo, BillTypeID from PD_LossSpillBill WHERE Red <> 2 ' + @SqlLSHis + ')
			   , DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
						  CROSS JOIN
						 (SELECT ROW_NUMBER() OVER(ORDER BY BillNo) AS ROWID,* FROM PagingData) B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
			   SELECT * FROM DATA LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID
								  LEFT JOIN _DATA_Dept ON Data.DeptID = _DATA_Dept.DID
								  LEFT JOIN _DATA_Ely ON Data.ElyID = _DATA_Ely.EID
								  LEFT JOIN _DATA_LSBill ON Data.BillNo = _DATA_LSBill.StockBillNo ORDER BY ROWID'
								  
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT * FROM PD_StockBill WHERE 1 <> 1'
		
    --print @sql

	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @BillStartDate DATETIME, @BillEndDate DATETIME, @OperatorID INT,
	                           @WhsID VARCHAR(1000), @DeptID VARCHAR(1000), @ElyID VARCHAR(1000), @GoodsID VARCHAR(1000),
	                           @GoodsTypeID INT, @Stt INT, @TVP_Dept TVP_Type READONLY, @TVP_GoodsType TVP_Type READONLY', 
	                           @PageNo, @PageSize, @BillStartDate, @BillEndDate, @OperatorID, @WhsID, @DeptID, @ElyID, @GoodsID,
	                           @GoodsTypeID, @Stt, @TVP_Dept, @TVP_GoodsType
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockLBWarn]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_StockLBWarn]
GO
/****** Object:  StoredProcedure [UP_PD_StockLBWarn]    Script Date: 03/18/2015 17:01:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/3/18
-- Description:	 库存下限报警
-- =============================================
CREATE PROCEDURE [UP_PD_StockLBWarn](
     @PageNo INT = 0,
     @PageSize INT = 0,
	 @WhsID INT = 0,  --仓库
	 @GoodsTypeID INT = 0,  --商品分类
     @GoodsNoMatch INT = 0,   --商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',            --商品编号
     @GoodsNameMatch INT = 0,   --商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @Model VARCHAR(50) = '',        --型号
	 @ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',      --简名
	 @AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',        --品牌
	 @BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',         --规格
	 @SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',      --条码
	 @BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	 @OperatorID INT = 0 --操作员ID
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @Sql NVARCHAR(MAX) = N' ;WITH ', @SqlParam NVARCHAR(MAX) = N' WHERE b.LowerBound - ISNULL(s.Qty,0) > 0 ', @StockTb NVARCHAR(20) = N' PD_GoodsStock ',
	        @TVP_GoodsType AS [TVP_Type], @KtypeLimit INT = 0, 
	        @BaseSql NVARCHAR(2000) = N' , _DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName FROM BD_Whs)
										 , _DATA_Pri AS (SELECT GoodsID AS GID, BarCode FROM dbo.BD_Goods_Price WHERE UnitID = 1) '
	
	IF @WhsID = 99999
		BEGIN
			SET @Sql += '  StockData AS 
					  (SELECT 99999 AS WhsID, s.GoodsID, SUM(s.Qty) AS Qty, SUM(s.Total) AS Total
							  FROM PD_GoodsStock s GROUP BY s.GoodsID ), '	
			SET @StockTb = ' StockData '
			SET @BaseSql = ' , _DATA_Whs AS (SELECT 99999 AS WID, ''ALL'' AS WhsNO, ''全部仓库'' AS WhsName) 
			                 , _DATA_Pri AS (SELECT GoodsID AS GID, BarCode FROM dbo.BD_Goods_Price WHERE UnitID = 1)'
		END
	SET @Sql += ' PagingData AS 
			     (SELECT b.WhsID, b.GoodsID, b.BoundID, b.LowerBound, ISNULL(s.Qty,0) AS StockQty, ISNULL(s.Total,0) AS Total, 
				  g.GoodsNo, g.GoodsName, g.Spec, g.Model, g.Place, g.Brand, b.LowerBound - ISNULL(s.Qty,0) AS LessQty,
				  g.GoodsAbbName
				  FROM PD_GoodsStock_Bound b
				  LEFT JOIN '+@StockTb+' s ON s.WhsID = b.WhsID AND s.GoodsID = b.GoodsID 
				  INNER JOIN BD_Goods g ON g.GoodsID = b.GoodsID '	
                         
    --仓库权限 
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	                   
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON b.WhsID = rWhs.WhsID '
        
    IF @WhsID <> 0
	   SET @SqlParam +=' AND b.WhsID = @WhsID '
            
    IF @GoodsTypeID <> 0
       BEGIN
            --可以选非子节点的商品分类，需找出该分类下的所有子节点
			INSERT INTO @TVP_GoodsType([TypeID],[ChildTypeID]) 
			SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM BD_Goods_Type gt 
				 INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
				 WHERE 	gt.GoodsTypeID = @GoodsTypeID and cgt.SonNum = 0
			SET @Sql +=' INNER JOIN @TVP_GoodsType goodsType ON goodsType.ChildTypeID = g.GoodsTypeID '
       END 
    
    IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND g.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND g.GoodsNo = @GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsName = @GoodsName ' 
	   END
		
	/*新增商品查询条件 start 150906*/
	IF @Model <> ''      --商品型号
	   BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND g.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND g.Model = @Model ' 
	   END       
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND g.Brand = @Brand ' 
	   END    
	IF @Spec <> ''       --商品规格 
	   BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND g.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND g.Spec = @Spec '  
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = g.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND pri.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/
	  
    SET @Sql= N'SET NOCOUNT ON;' + @Sql + @SqlParam + ' )' + @BaseSql +
			 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
						  CROSS JOIN
						 (SELECT ROW_NUMBER() OVER(ORDER BY WhsID) AS ROWID,* FROM PagingData) B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
			   SELECT * FROM DATA LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID 
			                      LEFT JOIN _DATA_Pri ON Data.GoodsID = _DATA_Pri.GID ORDER BY ROWID '
								  
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT 1 FROM PD_GoodsStock WHERE 1 <> 1'
		
    --print @sql

	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @WhsID VARCHAR(1000), @GoodsTypeID INT, @GoodsNo VARCHAR(50), 
	                           @GoodsName VARCHAR(100), @TVP_GoodsType TVP_Type READONLY, @Model VARCHAR(50), @AbbName VARCHAR(50), 
	                           @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100), @OperatorID INT', 
	                           @PageNo, @PageSize, @WhsID, @GoodsTypeID, @GoodsNo, @GoodsName, @TVP_GoodsType, @Model, @AbbName, 
	                           @Brand, @Spec, @BarCode, @OperatorID
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockLBWarnSum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_StockLBWarnSum]
GO
/****** Object:  StoredProcedure [UP_PD_StockLBWarnSum]    Script Date: 24/12/2015 17:01:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/12/24
-- Description:	 库存下限报警合计
-- =============================================
CREATE PROCEDURE [UP_PD_StockLBWarnSum](
	 @WhsID INT = 0,  --仓库
	 @GoodsTypeID INT = 0,  --商品分类
     @GoodsNoMatch INT = 0,   --商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',            --商品编号
     @GoodsNameMatch INT = 0,   --商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @Model VARCHAR(50) = '',        --型号
	 @ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',      --简名
	 @AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',        --品牌
	 @BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',         --规格
	 @SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',      --条码
	 @BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	 @OperatorID INT = 0 --操作员ID
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @Sql NVARCHAR(MAX) = N' ;WITH ', @SqlParam NVARCHAR(MAX) = N' WHERE b.LowerBound - ISNULL(s.Qty,0) > 0 ', @StockTb NVARCHAR(20) = N' PD_GoodsStock ',
	        @TVP_GoodsType AS [TVP_Type], @KtypeLimit INT = 0
	
	IF @WhsID = 99999
		BEGIN
			SET @Sql += '  StockData AS 
					  (SELECT 99999 AS WhsID, s.GoodsID, SUM(s.Qty) AS Qty, SUM(s.Total) AS Total
							  FROM PD_GoodsStock s GROUP BY s.GoodsID ), '	
			SET @StockTb = ' StockData '
		END
	SET @Sql += ' PagingData AS 
			     (SELECT b.WhsID, b.GoodsID, b.BoundID, b.LowerBound, ISNULL(s.Qty,0) AS StockQty, 
			     ISNULL(s.Total,0) AS Total, b.LowerBound - ISNULL(s.Qty,0) AS LessQty,
			      CASE WHEN ISNULL(s.Total,0) = 0 OR ISNULL(s.Qty,0) = 0 THEN -ISNULL(s.Total,0)
			      ELSE 
			      (CAST((CAST(s.Total AS DECIMAL(20,8))/CAST(s.Qty AS DECIMAL(20,8))) AS DECIMAL(20,8))*
			      CAST(b.LowerBound AS DECIMAL(20,8))-s.Total) END AS LessTotal
				  FROM PD_GoodsStock_Bound b
				  LEFT JOIN '+@StockTb+' s ON s.WhsID = b.WhsID AND s.GoodsID = b.GoodsID 
				  INNER JOIN BD_Goods g ON g.GoodsID = b.GoodsID '	
                         
    --仓库权限 
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	                   
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON b.WhsID = rWhs.WhsID '
        
    IF @WhsID <> 0
	   SET @SqlParam +=' AND b.WhsID = @WhsID '
            
    IF @GoodsTypeID <> 0
       BEGIN
            --可以选非子节点的商品分类，需找出该分类下的所有子节点
			INSERT INTO @TVP_GoodsType([TypeID],[ChildTypeID]) 
			SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM BD_Goods_Type gt 
				 INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
				 WHERE 	gt.GoodsTypeID = @GoodsTypeID and cgt.SonNum = 0
			SET @Sql +=' INNER JOIN @TVP_GoodsType goodsType ON goodsType.ChildTypeID = g.GoodsTypeID '
       END 
    
    IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND g.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND g.GoodsNo = @GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsName = @GoodsName ' 
	   END
		
	/*新增商品查询条件 start 150906*/
	IF @Model <> ''      --商品型号
	   BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND g.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND g.Model = @Model ' 
	   END       
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND g.Brand = @Brand ' 
	   END    
	IF @Spec <> ''       --商品规格 
	   BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND g.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND g.Spec = @Spec '  
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = g.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND pri.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/
	  
    SET @Sql= N'SET NOCOUNT ON;' + @Sql + @SqlParam + ' )' +
			 N' SELECT SUM(StockQty) AS StockQty, SUM(Total) AS Total,  
						         SUM(LessQty) AS LessQty, SUM(LessTotal) AS LessTotal  FROM PagingData '
								  
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT 1 FROM PD_GoodsStock WHERE 1 <> 1'
		
    --print @sql

	EXEC sp_executesql @Sql, N'@WhsID VARCHAR(1000), @GoodsTypeID INT, @GoodsNo VARCHAR(50), 
	                           @GoodsName VARCHAR(100), @TVP_GoodsType TVP_Type READONLY, @Model VARCHAR(50), @AbbName VARCHAR(50), 
	                           @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100), @OperatorID INT', 
	                           @WhsID, @GoodsTypeID, @GoodsNo, @GoodsName, @TVP_GoodsType, @Model, @AbbName, 
	                           @Brand, @Spec, @BarCode, @OperatorID
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockSummary]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_StockSummary
GO
/****** Object:  StoredProcedure [UP_PD_StockSummary]    Script Date: 07/08/2014 18:31:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/8
-- Description:	 库存状况表
-- =============================================
CREATE PROCEDURE [UP_PD_StockSummary](
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @WhsID VARCHAR(1000) = '',            --仓库
	 @GoodsNo VARCHAR(50) = '',            --商品编号
	 @GoodsNoMatch INT = 0,                --商品编号匹配方式 0:包含 1:等于
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @GoodsNameMatch INT = 0,              --商品名称匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',               --规格
	 @SpecMatch INT = 0,                   --规格匹配方式 0:包含 1:等于
	 @Model VARCHAR(50) = '',              --型号
	 @ModelMatch INT = 0,                  --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',            --简名
	 @AbbNameMatch INT = 0,                --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',              --品牌
	 @BrandMatch INT = 0,				   --品牌匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',            --条码
	 @BarCodeMatch INT = 0,                --条码匹配方式 0:包含 1:等于
	 @ShowStop BIT = 0,                    --显示停用商品
	 @StockStt INT = 1,                    --不显示0数量信息 1:库存不为0 2:有出入库记录 3:库存为负 4:全部商品
	 @SumParam1 INT = 1,                   --汇总条件一 0:空 1:仓库分类 (可以为空)
	 @SumLevel1 INT = 1,                   --汇总等级一 0:空 1-5:仓库分类层级 6:仓库 汇总条件一为1时必须选层级
	 @SumParam2 INT = 1,                   --汇总条件二 0:空 1:商品分类 2:规格 3:型号 (不能为空)
	 @SumLevel2 INT = 1,                   --汇总等级二 0:空 1-5:商品分类层级 6:商品 汇总条件二为1时必须选层级
	 @OperatorID INT = 0,                  --操作员ID
	 @OrderStr VARCHAR(50) = ''            --排序字符串        
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @HeadSql NVARCHAR(2000),
	        @Sql NVARCHAR(MAX), 
	        @SqlGroup NVARCHAR(1000) = N'', 
		    @SqlParam NVARCHAR(1000) = N'',
	        @Alias NVARCHAR(10) = N'stock', 
	        @DataSql NVARCHAR(2000) = N'', 
	        @BaseSql NVARCHAR(2000) = N'',
	        @PageDataName NVARCHAR(20) = N'PagingData', 
	        @KtypeLimit INT = 0 
    
    IF @StockStt = 1 OR @StockStt = 2 OR @StockStt = 3  --1:库存不为0  2:有出入库记录 3:库存为负
       BEGIN 
		   --固定字段数量、金额、成本
		   SET @HeadSql = N';With PagingData AS (SELECT SUM(stock.Qty) AS Qty, SUM(stock.Total) AS Total, 
										  (CASE WHEN SUM(stock.Qty) = 0 THEN 0
										   ELSE CAST(CAST(SUM(stock.Total) AS DECIMAL(20,8))
										   /CAST(SUM(stock.Qty) AS DECIMAL(20,8)) AS DECIMAL(20,8)) END) 
										   AS Price '
		   SET @Sql = N' FROM PD_GoodsStock stock INNER JOIN BD_Goods goods ON goods.GoodsID = stock.GoodsID '
       END
    ELSE     --4:全部商品
       BEGIN
		   --固定字段数量、金额、成本
		   SET @HeadSql = N';With PagingData AS (SELECT SUM(ISNULL(stock.Qty,0)) AS Qty, SUM(ISNULL(stock.Total,0)) AS Total, 
										  (CASE WHEN SUM(ISNULL(stock.Qty,0)) = 0 THEN 0
										   ELSE CAST(SUM(ISNULL(stock.Total,0))/SUM(ISNULL(stock.Qty,0)) AS DECIMAL(20,8)) END) 
										   AS Price ' 
	       IF @SumParam1 = 0 AND @WhsID = ''
	           SET @Sql = N' FROM BD_Goods goods LEFT JOIN PD_GoodsStock stock ON goods.GoodsID = stock.GoodsID '
	       ELSE
	           BEGIN
				   SET @Alias = N'whs'
				   SET @Sql = N' FROM BD_Whs whs CROSS JOIN BD_Goods goods 
							     LEFT JOIN PD_GoodsStock stock ON stock.WhsID = whs.WhsID 
							              AND stock.GoodsID = goods.GoodsID ' 
			   END  
	   END
                         
    --仓库权限                    
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	                   
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = '+ @Alias +'.WhsID '
	   
    IF @WhsID <> ''     --仓库
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = '+ @Alias +'.WhsID '
							
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND goods.GoodsNo = @GoodsNo '
	   END 
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsName = @GoodsName ' 
	   END 
	   
	IF @Spec <> ''       --商品规格 
	   BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
	   END 
	   
	IF @Model <> ''      --商品型号
	   BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
	   END 

	/*新增商品查询条件 start 150901*/
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
	       SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = goods.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND barcode.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/
	   
	IF @SumParam1 = 1    --汇总条件一:仓库分类
	   BEGIN
	     IF @StockStt = 1 OR @StockStt = 2 OR @StockStt = 3 --1:库存不为0  2:有出入库记录 3:库存为负(连接仓库信息)
	        SET @Sql += N' INNER JOIN BD_Whs whs on whs.WhsID = stock.WhsID '
         IF @SumLevel1 <> 6 AND @SumLevel1 <> 0 --汇总层级:仓库分类1-5
            BEGIN
	          SET @HeadSql += N', parWhsType.BaseID AS WhsTypeID '
			  SET @SqlGroup += N', parWhsType.BaseID '
			  SET @Sql += N' INNER JOIN dbo.UF_BD_BaseSummary(''KTYPE'', @SumLevel1) parWhsType ON parWhsType.ParID = whs.WhsTypeID '
	        END
	     ELSE IF @SumLevel1 = 6 --汇总层级:仓库
            BEGIN
			  SET @HeadSql += N', whs.WhsID '
			  SET @SqlGroup += N', whs.WhsID '
			  IF @SumParam2 <> 1 OR (@SumParam2 = 1 AND @SumLevel2 = 6)
			     SET @HeadSql += N', whs.WhsNO, whs.WhsName '
			     SET @SqlGroup += N', whs.WhsNO, whs.WhsName '
	        END
	   END
	   
	IF @SumParam2 = 1    --汇总条件二:商品分类
	   BEGIN
         IF @SumLevel2 <> 6 AND @SumLevel2 <> 0 --汇总层级:商品分类1-5
            BEGIN
	          SET @HeadSql += N', parGoodsType.BaseID AS GoodsTypeID'
			  SET @SqlGroup += N', parGoodsType.BaseID '
			  SET @Sql += N' INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @SumLevel2) parGoodsType ON parGoodsType.ParID = goods.GoodsTypeID '
	        END
	     ELSE IF @SumLevel2 = 6 --汇总层级:商品 (需辅助数量,关联基础表) 分页后出规格、型号字段
            BEGIN
	          SET @HeadSql += N', goods.GoodsID '
			  SET @SqlGroup += N', goods.GoodsID '		  
			  IF @SumParam1 = 0 OR (@SumParam1 = 1 AND @SumLevel1 = 6)
			     SET @HeadSql += N', goods.GoodsNo, goods.GoodsName, goods.Stt '
			     SET @SqlGroup += N', goods.GoodsNo, goods.GoodsName, goods.Stt '
			  SET @BaseSql += N', _DATA_Price1 AS (SELECT GoodsID AS GoodsID1, UnitID AS UnitID1, Unit AS Unit1, Convfactor AS Convfactor1, BarCode from BD_Goods_Price)
			                    , _DATA_Price2 AS (SELECT GoodsID AS GoodsID2, UnitID AS UnitID2, Unit AS Unit2, Convfactor AS Convfactor2 from BD_Goods_Price)
			                    , _DATA_Price3 AS (SELECT GoodsID AS GoodsID3, UnitID AS UnitID3, Unit AS Unit3, Convfactor AS Convfactor3 from BD_Goods_Price)
			                    , _DATA_Goods AS (SELECT GoodsID AS _GoodsID, Spec, Model, Brand, GoodsAbbName FROM BD_Goods)'  
			                   
			  SET @DataSql += N' LEFT JOIN _DATA_Price1 ON Data.GoodsID = _DATA_Price1.GoodsID1 AND _DATA_Price1.UnitID1 = 1
								 LEFT JOIN _DATA_Price2 ON Data.GoodsID = _DATA_Price2.GoodsID2 AND _DATA_Price2.UnitID2 = 2
								 LEFT JOIN _DATA_Price3 ON Data.GoodsID = _DATA_Price3.GoodsID3 AND _DATA_Price3.UnitID3 = 3
								 LEFT JOIN _DATA_Goods ON Data.GoodsID = _DATA_Goods._GoodsID '
	        END
	   END
	ELSE IF @SumParam2 = 2    --汇总条件二:规格
	   BEGIN
	     SET @HeadSql += N', goods.Spec ' 
	     SET @SqlGroup += N', goods.Spec ' 
	   END
	ELSE IF @SumParam2 = 3    --汇总条件二:模型
	   BEGIN
	     SET @HeadSql += N', goods.Model ' 
	     SET @SqlGroup += N', goods.Model ' 
	   END 	
  	   
	IF @ShowStop = 0        --不显示停用商品
	   SET @SqlParam += N' AND goods.Stt = 1 '
	   
	IF @StockStt = 1  --库存不为0
	BEGIN
		SET @SqlParam+=' and stock.Qty<>0'
	    SET @SqlGroup += N' HAVING SUM(stock.Qty) <> 0 '
	END
	ELSE IF @StockStt = 3 --库存为负
	   SET @SqlGroup += N' HAVING SUM(stock.Qty) < 0 '
	   
    IF @SqlParam <> ''  --查询条件
       SET @SqlParam = ' WHERE ' + SUBSTRING(@SqlParam, 5, LEN(@SqlParam) - 4)
    
	SET @Sql = @HeadSql + @Sql + @SqlParam + ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1)  + ' )'
	IF (@SumParam1 = 1 AND @SumLevel1 <> 6) OR (@SumParam2 = 1 AND @SumLevel2 <> 6)
	    BEGIN
		    SET @Sql += N', MainData AS (SELECT PagingData.* ' 
		    IF @SumParam1 = 1 AND @SumLevel1 <> 6
		        BEGIN
					SET @Sql += N',w.TypeCode AS WhsTypeCode, w.TypeName AS WhsTypeName' 
					IF @SumParam2 = 1 AND @SumLevel2 = 6
						SET @Sql += N',goods.GoodsNo, goods.GoodsName, goods.Stt ' 
				END
		    IF @SumParam2 = 1 AND @SumLevel2 <> 6
		        BEGIN
					SET @Sql += N',g.TypeCode AS GoodsTypeCode, g.TypeName AS GoodsTypeName'
					IF @SumParam1 = 1 AND @SumLevel1 = 6
						SET @Sql += N',whs.WhsNO, whs.WhsName'
				END
			SET @Sql += N' FROM PagingData '
		    IF @SumParam1 = 1 AND @SumLevel1 <> 6
		        BEGIN
					SET @Sql += N' INNER JOIN BD_Whs_Type w on w.WhsTypeID = PagingData.WhsTypeID '
					IF @SumParam2 = 1 AND @SumLevel2 = 6
						SET @Sql += N' INNER JOIN BD_Goods goods on goods.GoodsID = PagingData.GoodsID '
				END
		    IF @SumParam2 = 1 AND @SumLevel2 <> 6
		        BEGIN
					SET @Sql += N' INNER JOIN BD_Goods_Type g on g.GoodsTypeID = PagingData.GoodsTypeID '
					IF @SumParam1 = 1 AND @SumLevel1 = 6
						SET @Sql += N' INNER JOIN BD_Whs whs on whs.WhsID = PagingData.WhsID '
				END
		    SET @Sql += N')'
			SET @PageDataName = N' MainData '	       
	    END
    SET @Sql=N'SET NOCOUNT ON;'
             + @Sql + @BaseSql + 
			 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM ' + @PageDataName + ') A 
						 CROSS JOIN
						(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM ' + @PageDataName + ') B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				SELECT *, Qty AS BSQty FROM DATA ' + @DataSql + ' ORDER BY ROWID'
	
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT * FROM PD_GoodsStock WHERE 1 <> 1'				
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @WhsID VARCHAR(1000), @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100),
	                           @Spec VARCHAR(50), @Model VARCHAR(50), @SumLevel1 INT, @SumLevel2 INT, @OperatorID INT, 
	                           @AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100)', 
	                         @PageNo, @PageSize, @WhsID, @GoodsNo, @GoodsName, @Spec, 
							 @Model, @SumLevel1, @SumLevel2, @OperatorID, @AbbName, @Brand, @BarCode
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockSummarySum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_StockSummarySum
GO
/****** Object:  StoredProcedure [UP_PD_StockSummarySum]    Script Date: 07/28/2014 18:12:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/28
-- Description:	 库存状况表合计
-- =============================================
CREATE PROCEDURE [UP_PD_StockSummarySum](
	 @WhsID VARCHAR(1000) = '',            --仓库
	 @GoodsNo VARCHAR(50) = '',            --商品编号
	 @GoodsNoMatch INT = 0,                --商品编号匹配方式 0:包含 1:等于
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @GoodsNameMatch INT = 0,              --商品名称匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',               --规格
	 @SpecMatch INT = 0,                   --规格匹配方式 0:包含 1:等于
	 @Model VARCHAR(50) = '',              --型号
	 @ModelMatch INT = 0,                  --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',            --简名
	 @AbbNameMatch INT = 0,                --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',              --品牌
	 @BrandMatch INT = 0,                  --品牌匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',            --条码
	 @BarCodeMatch INT = 0,                --条码匹配方式 0:包含 1:等于
	 @ShowStop BIT = 0,                    --显示停用商品
	 @StockStt INT = 1,                    --不显示0数量信息 1:库存不为0 2:有出入库记录 3:库存为负
	 @SumParam1 INT = 1,                   --汇总条件一 0:空 1:仓库分类 (可以为空)
	 @SumLevel1 INT = 1,                   --汇总等级一 0:空 1-5:仓库分类层级 6:仓库 汇总条件一为1时必须选层级
	 @SumParam2 INT = 1,                   --汇总条件二 0:空 1:商品分类 2:规格 3:型号 (不能为空)
	 @SumLevel2 INT = 1,                   --汇总等级二 0:空 1-5:商品分类层级 6:商品 汇总条件二为1时必须选层级
	 @OperatorID INT = 0                   --操作员ID       
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX),  
			@HeadSql NVARCHAR(2000) = N'',
	        @SqlGroup NVARCHAR(1000) = N'',
		    @SqlParam NVARCHAR(1000) = N'', 
	        @KtypeLimit INT = 0 
	
	IF @StockStt = 3
	BEGIN
		 SET @HeadSql = N';With PagingData AS (SELECT SUM(stock.Qty) AS Qty, SUM(stock.Total) AS Total '
		 SET @Sql = N' FROM PD_GoodsStock stock '
	END
	ELSE
		SET @Sql = N' SELECT SUM(stock.Qty) AS Qty, SUM(stock.Total) AS Total FROM PD_GoodsStock stock '
	
	IF @GoodsNo <> '' OR @GoodsName <> '' OR @Spec <> '' OR @Model <> '' OR @AbbName <> '' OR @Brand <> '' OR @BarCode <> '' OR @ShowStop = 0 OR @StockStt = 3
		SET @Sql += N' INNER JOIN BD_Goods goods ON goods.GoodsID = stock.GoodsID '
                          
    --仓库权限                    
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	                   
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID = stock.WhsID '
	   
    IF @WhsID <> ''     --仓库
	   SET @Sql += N' INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = stock.WhsID '
							
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND goods.GoodsNo = @GoodsNo '
	   END 
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsName = @GoodsName ' 
	   END 
	   
	IF @Spec <> ''       --商品规格 
	   BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
	   END 
	   
	IF @Model <> ''      --商品型号
	   BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
	   END

	/*新增商品查询条件 start 150901*/
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
	       SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = goods.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND barcode.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/ 
	   
    IF @StockStt = 3 --库存为负
        BEGIN
            IF @SumParam1 = 1    --汇总条件一:仓库分类
                BEGIN
                    SET @Sql += N' INNER JOIN BD_Whs whs on whs.WhsID = stock.WhsID '
                    IF @SumLevel1 <> 6 AND @SumLevel1 <> 0 --汇总层级:仓库分类1-5
                        BEGIN
                            SET @HeadSql += N', parWhsType.BaseID AS WhsTypeID '
                            SET @SqlGroup += N', parWhsType.BaseID '
                            SET @Sql += N' INNER JOIN dbo.UF_BD_BaseSummary(''KTYPE'', @SumLevel1) parWhsType ON parWhsType.ParID = whs.WhsTypeID '
                        END
                    ELSE 
                        IF @SumLevel1 = 6 --汇总层级:仓库
                            BEGIN
                                SET @HeadSql += N', whs.WhsID '
                                SET @SqlGroup += N', whs.WhsID '
                            END
                END
		   
            IF @SumParam2 = 1    --汇总条件二:商品分类
                BEGIN
                    IF @SumLevel2 <> 6 AND @SumLevel2 <> 0 --汇总层级:商品分类1-5
                        BEGIN
                            SET @HeadSql += N', parGoodsType.BaseID AS GoodsTypeID'
                            SET @SqlGroup += N', parGoodsType.BaseID '
                            SET @Sql += N' INNER JOIN dbo.UF_BD_BaseSummary(''PTYPE'', @SumLevel2) parGoodsType ON parGoodsType.ParID = goods.GoodsTypeID '
                        END
                    ELSE 
                        IF @SumLevel2 = 6 --汇总层级:商品
                            BEGIN
                                SET @HeadSql += N', goods.GoodsID '
                                SET @SqlGroup += N', goods.GoodsID '
                            END
                END
            ELSE 
                IF @SumParam2 = 2    --汇总条件二:规格
                    BEGIN
                        SET @HeadSql += N', goods.Spec ' 
                        SET @SqlGroup += N', goods.Spec ' 
                    END
                ELSE 
                    IF @SumParam2 = 3    --汇总条件二:模型
                        BEGIN
                            SET @HeadSql += N', goods.Model ' 
                            SET @SqlGroup += N', goods.Model ' 
                        END
	   
            SET @SqlGroup += N' HAVING SUM(stock.Qty) < 0 '	
        END
	
	IF @ShowStop = 0        --不显示停用商品
	   SET @SqlParam += N' AND goods.Stt = 1 '
	IF @StockStt=1
		SET @SqlParam +=' AND stock.Qty<>0'
	   
    IF @SqlParam <> ''  --查询条件
       SET @SqlParam = ' WHERE ' + SUBSTRING(@SqlParam, 5, LEN(@SqlParam) - 4)
	
	SET @Sql += @SqlParam
	
	IF @StockStt = 3 --库存为负
		SET @Sql = @HeadSql + @Sql + ' GROUP BY ' + SUBSTRING(@SqlGroup, 2, LEN(@SqlGroup) - 1)  + ' )
		           SELECT SUM(Qty) AS Qty, SUM(Total) AS Total FROM PagingData '
	
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT 0, 0 FROM PD_GoodsStock WHERE 1 <> 1'
	
	EXEC sp_executesql @Sql, N'@WhsID VARCHAR(1000), @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100),
	                           @Spec VARCHAR(50), @Model VARCHAR(50), @OperatorID INT, 
	                           @AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100), 
	                           @SumLevel1 INT, @SumLevel2 INT', 
	                         @WhsID, @GoodsNo, @GoodsName, @Spec, @Model, @OperatorID, @AbbName, @Brand, @BarCode,
	                         @SumLevel1, @SumLevel2
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockUBWarn]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_StockUBWarn]
GO
/****** Object:  StoredProcedure [UP_PD_StockUBWarn]    Script Date: 03/18/2015 15:32:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/3/18
-- Description:	 库存上限报警
-- =============================================
CREATE PROCEDURE [UP_PD_StockUBWarn](
     @PageNo INT = 0,
     @PageSize INT = 0,
	 @WhsID INT = 0,  --仓库
	 @GoodsTypeID INT = 0,  --商品分类
     @GoodsNoMatch INT = 0,   --商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',            --商品编号
     @GoodsNameMatch INT = 0,   --商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @Model VARCHAR(50) = '',        --型号
	 @ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',      --简名
	 @AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',        --品牌
	 @BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',         --规格
	 @SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',      --条码
	 @BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	 @OperatorID INT = 0 --操作员ID
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @Sql NVARCHAR(MAX) = N' ;WITH ', @SqlParam NVARCHAR(MAX) = N' WHERE ISNULL(s.Qty,0) - b.UpperBound > 0 ', @StockTb NVARCHAR(20) = N' PD_GoodsStock ',
	        @TVP_GoodsType AS [TVP_Type], @KtypeLimit INT = 0, 
	        @BaseSql NVARCHAR(2000) = N' , _DATA_Whs AS (SELECT WhsID AS WID, WhsNO, WhsName FROM BD_Whs) 
										 , _DATA_Pri AS (SELECT GoodsID AS GID, BarCode FROM dbo.BD_Goods_Price WHERE UnitID = 1)'
	
	IF @WhsID = 99999
		BEGIN
			SET @Sql += '  StockData AS 
					  (SELECT 99999 AS WhsID, s.GoodsID, SUM(s.Qty) AS Qty, SUM(s.Total) AS Total
							  FROM PD_GoodsStock s GROUP BY s.GoodsID ), '	
			SET @StockTb = ' StockData '
			SET @BaseSql = ' , _DATA_Whs AS (SELECT 99999 AS WID, ''ALL'' AS WhsNO, ''全部仓库'' AS WhsName)
							 , _DATA_Pri AS (SELECT GoodsID AS GID, BarCode FROM dbo.BD_Goods_Price WHERE UnitID = 1) '
		END
	SET @Sql += ' PagingData AS 
			     (SELECT s.WhsID, s.GoodsID, b.BoundID, b.UpperBound, ISNULL(s.Qty,0) AS StockQty, ISNULL(s.Total,0) AS Total, 
				  g.GoodsNo, g.GoodsName, g.Spec, g.Model, g.Place, g.Brand, ISNULL(s.Qty,0) - b.UpperBound AS OverQty,
				  g.GoodsAbbName
				  FROM PD_GoodsStock_Bound b
				  INNER JOIN '+@StockTb+' s ON s.WhsID = b.WhsID AND s.GoodsID = b.GoodsID
				  INNER JOIN BD_Goods g ON g.GoodsID = b.GoodsID '	
                         
    --仓库权限 
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	                   
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON s.WhsID = rWhs.WhsID '
        
    IF @WhsID <> 0 
	   SET @SqlParam +=' AND b.WhsID = @WhsID '
            
    IF @GoodsTypeID <> 0
       BEGIN
            --可以选非子节点的商品分类，需找出该分类下的所有子节点
			INSERT INTO @TVP_GoodsType([TypeID],[ChildTypeID]) 
			SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM BD_Goods_Type gt 
				 INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
				 WHERE 	gt.GoodsTypeID = @GoodsTypeID and cgt.SonNum = 0
			SET @Sql +=' INNER JOIN @TVP_GoodsType goodsType ON goodsType.ChildTypeID = g.GoodsTypeID '
       END 
    
    IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND g.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND g.GoodsNo = @GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsName = @GoodsName ' 
	   END
		
	/*新增商品查询条件 start 150906*/
	IF @Model <> ''      --商品型号
	   BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND g.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND g.Model = @Model ' 
	   END       
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND g.Brand = @Brand ' 
	   END    
	IF @Spec <> ''       --商品规格 
	   BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND g.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND g.Spec = @Spec '  
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = g.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND pri.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/	
	  
    SET @Sql= N'SET NOCOUNT ON;' + @Sql + @SqlParam + ' )' + @BaseSql +
			 N', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A 
						  CROSS JOIN
						 (SELECT ROW_NUMBER() OVER(ORDER BY WhsID) AS ROWID,* FROM PagingData) B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
			   SELECT * FROM DATA LEFT JOIN _DATA_Whs ON Data.WhsID = _DATA_Whs.WID 
			                      LEFT JOIN _DATA_Pri ON Data.GoodsID = _DATA_Pri.GID ORDER BY ROWID'	
							  
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT 1 FROM PD_GoodsStock WHERE 1 <> 1'
		
    --print @sql

	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @WhsID VARCHAR(1000), @GoodsTypeID INT, @GoodsNo VARCHAR(50), 
	                           @GoodsName VARCHAR(100), @TVP_GoodsType TVP_Type READONLY, @Model VARCHAR(50), @AbbName VARCHAR(50), 
	                           @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100), @OperatorID INT', 
	                           @PageNo, @PageSize, @WhsID, @GoodsTypeID, @GoodsNo, @GoodsName, @TVP_GoodsType, @Model, @AbbName, 
	                           @Brand, @Spec, @BarCode, @OperatorID
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockUBWarnSum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_StockUBWarnSum]
GO
/****** Object:  StoredProcedure [UP_PD_StockUBWarnSum]    Script Date: 24/12/2015 15:32:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/12/24
-- Description:	 库存上限报警合计
-- =============================================
CREATE PROCEDURE [UP_PD_StockUBWarnSum](
	 @WhsID INT = 0,  --仓库
	 @GoodsTypeID INT = 0,  --商品分类
     @GoodsNoMatch INT = 0,   --商品编号匹配方式
	 @GoodsNo VARCHAR(50) = '',            --商品编号
     @GoodsNameMatch INT = 0,   --商品名称匹配方式
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @Model VARCHAR(50) = '',        --型号
	 @ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',      --简名
	 @AbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',        --品牌
	 @BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',         --规格
	 @SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',      --条码
	 @BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	 @OperatorID INT = 0 --操作员ID
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	
	DECLARE @Sql NVARCHAR(MAX) = N' ;WITH ', @SqlParam NVARCHAR(MAX) = N' WHERE ISNULL(s.Qty,0) - b.UpperBound > 0 ', @StockTb NVARCHAR(20) = N' PD_GoodsStock ',
	        @TVP_GoodsType AS [TVP_Type], @KtypeLimit INT = 0
	
	IF @WhsID = 99999
		BEGIN
			SET @Sql += '  StockData AS 
					  (SELECT 99999 AS WhsID, s.GoodsID, SUM(s.Qty) AS Qty, SUM(s.Total) AS Total
							  FROM PD_GoodsStock s GROUP BY s.GoodsID ), '	
			SET @StockTb = ' StockData '
		END
	SET @Sql += ' PagingData AS 
			     (SELECT s.WhsID, s.GoodsID, b.BoundID, b.UpperBound, ISNULL(s.Qty,0) AS StockQty, 
			      ISNULL(s.Total,0) AS Total, ISNULL(s.Qty,0) - b.UpperBound AS OverQty,
			      CASE WHEN ISNULL(s.Total,0) = 0 OR ISNULL(s.Qty,0) = 0 THEN ISNULL(s.Total,0)
			      ELSE 
			      (s.Total-
			      CAST((CAST(s.Total AS DECIMAL(20,8))/CAST(s.Qty AS DECIMAL(20,8))) AS DECIMAL(20,8))*
			      CAST(b.UpperBound AS DECIMAL(20,8))) END AS OverTotal
				  FROM PD_GoodsStock_Bound b
				  INNER JOIN '+@StockTb+' s ON s.WhsID = b.WhsID AND s.GoodsID = b.GoodsID
				  INNER JOIN BD_Goods g ON g.GoodsID = b.GoodsID '	
                         
    --仓库权限 
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	                   
    IF @KtypeLimit = 1 --部份权限
	   SET @Sql +=' INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON s.WhsID = rWhs.WhsID '
        
    IF @WhsID <> 0 
	   SET @SqlParam +=' AND b.WhsID = @WhsID '
            
    IF @GoodsTypeID <> 0
       BEGIN
            --可以选非子节点的商品分类，需找出该分类下的所有子节点
			INSERT INTO @TVP_GoodsType([TypeID],[ChildTypeID]) 
			SELECT gt.GoodsTypeID, cgt.GoodsTypeID FROM BD_Goods_Type gt 
				 INNER JOIN BD_Goods_Type cgt ON cgt.[Path] Like gt.[Path] + '%'
				 WHERE 	gt.GoodsTypeID = @GoodsTypeID and cgt.SonNum = 0
			SET @Sql +=' INNER JOIN @TVP_GoodsType goodsType ON goodsType.ChildTypeID = g.GoodsTypeID '
       END 
    
    IF @GoodsNo <> ''   --商品编号 
	   BEGIN 
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND g.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND g.GoodsNo = @GoodsNo ' 
	   END
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsName = @GoodsName ' 
	   END
		
	/*新增商品查询条件 start 150906*/
	IF @Model <> ''      --商品型号
	   BEGIN 
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND g.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND g.Model = @Model ' 
	   END       
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND g.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND g.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND g.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND g.Brand = @Brand ' 
	   END    
	IF @Spec <> ''       --商品规格 
	   BEGIN 
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND g.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND g.Spec = @Spec '  
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = g.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND pri.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/	
	  
    SET @Sql= N'SET NOCOUNT ON;' + @Sql + @SqlParam + ' )' +
			 N' SELECT SUM(StockQty) AS StockQty, SUM(Total) AS Total,  
						         SUM(OverQty) AS OverQty, SUM(OverTotal) AS OverTotal FROM PagingData '	
					  
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT 1 FROM PD_GoodsStock WHERE 1 <> 1'
		
    --print @sql

	EXEC sp_executesql @Sql, N'@WhsID VARCHAR(1000), @GoodsTypeID INT, @GoodsNo VARCHAR(50), 
	                           @GoodsName VARCHAR(100), @TVP_GoodsType TVP_Type READONLY, @Model VARCHAR(50), @AbbName VARCHAR(50), 
	                           @Brand VARCHAR(50), @Spec VARCHAR(50), @BarCode VARCHAR(100), @OperatorID INT', 
	                           @WhsID, @GoodsTypeID, @GoodsNo, @GoodsName, @TVP_GoodsType, @Model, @AbbName, 
	                           @Brand, @Spec, @BarCode, @OperatorID
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockVirtual]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_StockVirtual
GO
/****** Object:  StoredProcedure [UP_PD_StockVirtual]    Script Date: 07/08/2014 18:31:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		leiyang
-- Create date:  2015/3/30
-- Description:	 虚拟库存表
-- =============================================
CREATE PROCEDURE UP_PD_StockVirtual(
     @PageNo INT = 0,                      --页码
     @PageSize INT = 0,                    --页大小
	 @WhsID VARCHAR(1000) = '',            --仓库
	 @GoodsNo VARCHAR(50) = '',            --商品编号
	 @GoodsNoMatch INT = 0,                --商品编号匹配方式 0:包含 1:等于
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @GoodsNameMatch INT = 0,              --商品名称匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',               --规格
	 @SpecMatch INT = 0,                   --规格匹配方式 0:包含 1:等于
	 @Model VARCHAR(50) = '',              --型号
	 @ModelMatch INT = 0,                  --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',            --简名
	 @AbbNameMatch INT = 0,				   --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',              --品牌
	 @BrandMatch INT = 0,			       --品牌匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',            --条码
	 @BarCodeMatch INT = 0,                --条码匹配方式 0:包含 1:等于
	 @ShowStop BIT = 0,                    --显示停用商品
	 @ShowPpt BIT = 0,                     --显示商品属性
	 @SumParam1 INT = 1,                   --汇总条件一 0:空 1:仓库分类 (可以为空)
	 @SumLevel1 INT = 1,                   --汇总等级一 0:空 1-5:仓库分类层级 6:仓库 汇总条件一为1时必须选层级
	 @SumParam2 INT = 1,                   --汇总条件二 0:空 1:商品分类 (不能为空)
	 @SumLevel2 INT = 1,                   --汇总等级二 0:空 1-5:商品分类层级 6:商品 汇总条件二为1时必须选层级
	 @OperatorID INT = 0,                  --操作员ID
	 @OrderStr VARCHAR(50) = ''            --排序字符串        
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @HeadSql NVARCHAR(2000),
	        @Sql NVARCHAR(MAX), @SqlWhs varchar(max)='', @SqlWhsOut varchar(max)='',@SqlWhsIn varchar(max)='',@SaleOrdStr varchar(max)='',@BuyOrdStr varchar(max)='',@SqlGoods varchar(500)='',
	        @SqlGroup NVARCHAR(1000) = N'',@GoodsSql varchar(max)='', 
		    @SqlParam NVARCHAR(1000) = N'',@DraftSql Varchar(Max)='',@OrderName varchar(Max)='',@sqlSelStr varchar(Max)= '',
		    @BuyNotValidSql NVARCHAR(1000) = N'',@SaleNotValidSql NVARCHAR(1000) = N'',
	        @Alias NVARCHAR(10) = N'stock', @VirtualFormula varchar(300) = '',
	        @DataSql NVARCHAR(2000) = N'', 
	        @BaseSql NVARCHAR(2000) = N'',
	        @PageDataName NVARCHAR(20) = N'PagingData', 
	        @KtypeLimit INT = 0,@KtypeLimtStr varchar(max)='',@LimitSql VARCHAR(max)='',@LimitSqlIN VARCHAR(max)='',@LimitSqlOut VARCHAR(max)='',@LimitSql1 varchar(max)='',
	        @SqlCreateTable varchar(max) = '',@CreatTableFlag INT=0 
                         
    --仓库权限                    
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	SELECT @VirtualFormula = Remark from SS_OtherCfg where ID = 102
	select @VirtualFormula = REPLACE(@VirtualFormula,'账面库存','sum(isnull(Qty,0))')
	select @VirtualFormula = REPLACE(@VirtualFormula,'采购订单在途数','sum(isnull(BuyOrderQty,0))')
	select @VirtualFormula = REPLACE(@VirtualFormula,'销售订单未发数','sum(isnull(SaleOrderQty,0))')
	select @VirtualFormula = REPLACE(@VirtualFormula,'草稿数量','sum(isnull(DraftQty,0))')                   
	select @VirtualFormula = REPLACE(@VirtualFormula,'未生效采购订单数量','sum(isnull(BuyNotValidQty,0))')                   
	select @VirtualFormula = REPLACE(@VirtualFormula,'未生效销售订单数量','sum(isnull(SaleNotValidQty,0))')                   
    IF @KtypeLimit = 1 --部份权限
    BEGIN
		SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
		Set @LimitSql += ' INNER JOIN @LimitKType LW ON I.WhsID=LW.TypeID ' 
		Set @LimitSql1 += ' INNER JOIN @LimitKType LW ON Detail.WhsID=LW.TypeID ' 
		Set @LimitSqlIN += ' INNER JOIN @LimitKType LW ON I.InWhsID=LW.TypeID ' 	
		Set @LimitSqlOut += ' INNER JOIN @LimitKType LW ON I.OutWhsID=LW.TypeID '
	END
    IF @WhsID <> ''     --仓库
    BEGIN
		SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
		Set @SqlWhs += ' Inner JOIN  @KType W on Detail.WhsID=W.TypeID ' 		
		--Set @SqlWhsOut += ' Inner JOIN  @KType W ON I.OutWhsID = W.TypeID or I.InWhsID=W.TypeID ' 
		Set @SqlWhsOut += ' Inner JOIN  @KType W ON I.OutWhsID = W.TypeID ' 
		Set @SqlWhsIn += ' Inner JOIN  @KType W ON I.InWhsID=W.TypeID ' 
	END						
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN
		   SET @CreatTableFlag = 1
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND goods.GoodsNo = @GoodsNo '
	   END 
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   SET @CreatTableFlag = 1
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsName = @GoodsName ' 
	   END 
	   
	IF @Spec <> ''       --商品规格 
	   BEGIN
	       SET @CreatTableFlag = 1
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
	   END 
	   
	IF @Model <> ''      --商品型号
	   BEGIN 
			SET @CreatTableFlag = 1
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
	   END

	/*新增商品查询条件 start 150901*/
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = goods.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND barcode.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/
	IF @ShowStop = 0        --不显示停用商品
	   SET @SqlParam += N' AND goods.Stt = 1 ' 
	   
	IF @CreatTableFlag = 1
	BEGIN
	   SET @SqlCreateTable += ' DECLARE @PTYPE AS TABLE(TYPEID	INT) INSERT INTO @PTYPE SELECT GOODSID FROM BD_GOODS goods WHERE 1=1' + @SqlParam	
	   SET @SqlGoods += ' Inner join @PTYPE g on detail.GoodsID = g.TYPEID '
	END
	ELSE 
	   SET @SqlGoods += ' Inner join (select GoodsID from BD_Goods goods where 1=1 '+@SqlParam+') g on detail.GoodsID = g.GoodsID '
	  ---汇总层级
	if(@SumParam1 = 1)
	Begin
		if(@SumLevel1 <> 6 )
		BEGIN
			Select @OrderName += ' Wt.WhsTypeID,Wt.TypeCode as WhsTypeCode,Wt.TypeName as WhsTypeName,'
			Select @SqlGroup += ' Wt.WhsTypeID,Wt.TypeCode,Wt.TypeName,'
			Select @sqlSelStr += ' WhsTypeID,WTypeCode,WTypeName,'
		END
		ELSE
		BEGIN
			Select @OrderName += ' A.WhsID,WhsName,WhsNO,'
			Select @SqlGroup += ' A.WhsID,W.WhsName,W.WhsNO,'
			Select @sqlSelStr += ' WhsID,WhsName,WhsNO,'
		END
	End
	if(@SumLevel2 <> 6 )
	BEGIN
		Select @OrderName += ' Gt.GoodsTypeID,Gt.TypeCode as GoodsTypeCode,Gt.TypeName as GoodsTypeName,'
		Select @SqlGroup += ' Gt.GoodsTypeID,Gt.TypeCode,Gt.TypeName'
		Select @sqlSelStr += ' GoodsTypeID,GoodsTypeCode,GoodsTypeName,'
	END
	ELSE
	BEGIN
		Select @OrderName += ' A.GoodsID,GoodsName,GoodsNo,G.Stt,'
		Select @SqlGroup += ' A.GoodsID,G.GoodsName,G.GoodsNo,G.Stt'
		Select @sqlSelStr += ' GoodsID,GoodsName,GoodsNo,Stt,'
		SET @BaseSql += N', _DATA_Price1 AS (SELECT GoodsID AS GoodsID1, UnitID AS UnitID1, Unit AS Unit1, Convfactor AS Convfactor1, BarCode from BD_Goods_Price)
		                    , _DATA_Goods AS (SELECT GoodsID AS _GoodsID, Spec, Model, Brand, GoodsAbbName FROM BD_Goods)'  
		                   
		SET @DataSql += N' LEFT JOIN _DATA_Price1 ON Data.GoodsID = _DATA_Price1.GoodsID1 AND _DATA_Price1.UnitID1 = 1
							 LEFT JOIN _DATA_Goods ON Data.GoodsID = _DATA_Goods._GoodsID '
	END
	---销售订单数据
	SET @SaleOrdStr += 'select detail.GoodsID,detail.WhsID,0 as Qty,0 as Total,(sum(isnull(bsQty,0)) - sum(isnull(comQty,0))) as SaleOrderQty ,0 as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty, ReplaceStr
		from PD_SellOrdBill ord inner join PD_SellOrdDetail detail on ord.BillNo = detail.BillNo '+@SqlGoods+@LimitSql1+@SqlWhs+'
	where ord.isDraft = 0 and detail.StopTag = 0 and BSQty > ComQty  group by detail.GoodsID ,detail.WhsID , ReplaceStr'
	---采购订单数据
	SET @BuyOrdStr += 'select detail.GoodsID,detail.WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,(sum(isnull(bsQty,0)) - sum(isnull(comQty,0)) )	as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty, ReplaceStr
		from PD_PchOrdBill ord inner join PD_PchOrdDetail detail on ord.BillNo = detail.BillNo '+@SqlGoods+@LimitSql1+@SqlWhs+'
	where ord.isDraft = 0 and detail.StopTag = 0 and BSQty > ComQty  group by detail.GoodsID ,detail.WhsID, ReplaceStr  '
		--订单未生效订单，采购为正销售为负		
	Select @BuyNotValidSql+=' 
				SELECT Detail.GoodsID,Detail.WhsID as WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,0 as BuyOrderQty,0 as BuyNotValidQty,Sum(BSQty) as SaleNotValidQty,0 as DraftQty, ReplaceStr
				FROM  PD_SellOrdBill ord inner join PD_SellOrdDetail detail on ord.BillNo = detail.BillNo '
				+@SqlGoods+@LimitSql1+@SqlWhs
				+'where ord.isDraft = 1 and detail.StopTag = 0 group by detail.GoodsID ,detail.WhsID, ReplaceStr '
	Select @SaleNotValidSql+=' 
				SELECT Detail.GoodsID,Detail.WhsID as WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,0 as BuyOrderQty,Sum(BSQty) as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty, ReplaceStr
				FROM  PD_PchOrdBill ord inner join PD_PchOrdDetail detail on ord.BillNo = detail.BillNo '
				+@SqlGoods+@LimitSql1+@SqlWhs
				+'where ord.isDraft = 1 and detail.StopTag = 0 group by detail.GoodsID ,detail.WhsID, ReplaceStr '	
	
	---草稿数据
	Select @DraftSql +=' 
UNION ALL 
	SELECT Detail.GoodsID,I.WhsID,' + Case When BillTypeID IN (101,202,303,306) Then ' Sum(BSQty)' Else ' -Sum(BSQty)' End +' AS DraftQty, ReplaceStr'
	+ ' From ' + BillDetail +' detail Inner Join '+BillTable+' I on detail.BillNo = I.billNo'
	 +@SqlGoods+@LimitSql+@SqlWhs
	 +' Where IsDraft = 1 '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	+' group by detail.GoodsID,I.WhsID, ReplaceStr '
	from PD_BillType where BillTypeID in (101,102,201,202,303,304,305,306,600)
	Select @DraftSql+='
	UNION ALL
		SELECT Detail.GoodsID,Detail.OutWhsID as WhsID, -Sum(BSQty) AS DraftQty, ReplaceStr
		FROM  PD_AllotDetail Detail  Inner Join PD_AllotBill I ON  I.BillNo=Detail.BillNo '
		+@SqlGoods+@LimitSqlOut+@SqlWhsOut
		+'where IsDraft=1 ' 
		+' And BillTypeID = ' + Cast(BillTypeID as varchar(10))
		+' group by Detail.GoodsID,Detail.OutWhsID,Detail.InWhsID, ReplaceStr ' from PD_BillType where BillTypeID in (301,309)
Select @DraftSql+=' 
	UNION ALL 
		SELECT Detail.GoodsID,Detail.InWhsID as WhsID, Sum(BSQty) AS DraftQty, ReplaceStr
		FROM  PD_AllotDetail Detail Inner Join PD_AllotBill I ON  I.BillNo=Detail.BillNo '
		+@SqlGoods+@LimitSqlIN+@SqlWhsIn
		+'where IsDraft=1 ' 
		+' And BillTypeID = ' + Cast(BillTypeID as varchar(10))
	   +' group by Detail.GoodsID,Detail.OutWhsID,Detail.InWhsID, ReplaceStr ' from PD_BillType where BillTypeID in (301,309)
  Select @DraftSql+='
	UNION ALL
		SELECT Detail.GoodsID,Detail.WhsID as WhsID, -Sum(BSQty) AS DraftQty, ReplaceStr
		FROM  PD_AssemblyDetail Detail  Inner Join PD_AssemblyBill I ON  I.BillNo=Detail.BillNo '
		+@SqlGoods+@LimitSqlOut+@SqlWhsOut
		+'where IsDraft=1 and Detail.DetailType=2  group by Detail.GoodsID,Detail.WhsID, ReplaceStr '
	Select @DraftSql+=' 
		UNION ALL 
			SELECT Detail.GoodsID,Detail.WhsID as WhsID, Sum(BSQty) AS DraftQty, ReplaceStr
			FROM  PD_AssemblyDetail Detail Inner Join PD_AssemblyBill I ON  I.BillNo=Detail.BillNo '
			+@SqlGoods+@LimitSqlIN+@SqlWhsIn
			+'where IsDraft=1 and Detail.DetailType=1 group by Detail.GoodsID,Detail.WhsID, ReplaceStr '
	/*增加, ReplaceStr，用于判断查询条件后替换为列*/
	DECLARE @ReplaceStr VARCHAR(1000) = '', @StockDataPpt VARCHAR(1000) = '', 
	        @StockQT VARCHAR(1000) = ' SUM(ISNULL(Detail.Qty,0)) AS Qty, SUM(ISNULL(Detail.Total,0)) AS Total '
	IF @ShowPpt = 1 AND @SumLevel2 = 6   --显示商品属性（商品汇总的情况下)
		BEGIN
			SET @ReplaceStr = N', detail.Ppt1ID, detail.Ppt2ID ' 
			SET @SqlGroup += ',Ppt1ID, Ppt2ID'
			SET @StockDataPpt  += ' LEFT JOIN dbo.PD_GoodsStock_Detail sd ON sd.GoodsID = Detail.GoodsID AND sd.StockID = Detail.StockID '
			SET @BaseSql += N', _DATA_Ppt1 AS (SELECT Ppt1ID AS P1ID, Value AS Ppt1Name from dbo.BD_Goods_Ppt1)
		                      , _DATA_Ppt2 AS (SELECT Ppt2ID AS P2ID, Value AS Ppt2Name from dbo.BD_Goods_Ppt2)'
			SET @DataSql += N' LEFT JOIN _DATA_Ppt1 ON Data.Ppt1ID = _DATA_Ppt1.P1ID
							   LEFT JOIN _DATA_Ppt2 ON Data.Ppt2ID = _DATA_Ppt2.P2ID '
	        SET @StockQT = ' SUM(ISNULL(sd.Qty,0)) AS Qty, SUM(ISNULL(sd.Qty,0)*ISNULL(Detail.Price,0)) AS Total '
		END	
    SET @SaleOrdStr = REPLACE(@SaleOrdStr,', ReplaceStr',@ReplaceStr)
    SET @BuyOrdStr = REPLACE(@BuyOrdStr,', ReplaceStr',@ReplaceStr)
    SET @BuyNotValidSql = REPLACE(@BuyNotValidSql,', ReplaceStr',@ReplaceStr)
    SET @SaleNotValidSql = REPLACE(@SaleNotValidSql,', ReplaceStr',@ReplaceStr)
    IF @ReplaceStr <> ''
		SET @ReplaceStr = REPLACE(@ReplaceStr,'detail.','Detail.')
    SET @DraftSql = REPLACE(@DraftSql,', ReplaceStr',@ReplaceStr)
    IF @ReplaceStr <> ''
		SET @ReplaceStr = REPLACE(@ReplaceStr,'Detail.','')
	/**/
	Select @Sql =@SqlCreateTable+
	';WITH SaleOrdBill AS 
	('	+@SaleOrdStr+'
	),BuyOrdBill AS (
		'+@BuyOrdStr+'
	),BuyNotValid AS('
	+@BuyNotValidSql+'
	),SaleNotValid AS('
	+@SaleNotValidSql+'
	),DraftBill AS(
	'+STUFF(@DraftSql,1,12,'')+'
	),DraftData as(
		select goodsID,WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,0 as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,SUM(DraftQty) as DraftQty '+@ReplaceStr+'  from DraftBill group by goodsID,WhsID '+@ReplaceStr+' 
	),StockData as(
		SELECT  goods.GoodsID ,WhsID ,'+@StockQT+', 
			  0 as SaleOrderQty,0 as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty '+@ReplaceStr+' 
			   FROM BD_Goods goods LEFT JOIN PD_GoodsStock Detail ON goods.GoodsID = Detail.GoodsID ' + @StockDataPpt+ ' 
			   '+@LimitSql1+@SqlWhs+'
			   Where 1=1 '+@SqlParam+' 
			    GROUP BY  goods.GoodsID ,WhsID'+@ReplaceStr+' 
	),AllData As(
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty '+@ReplaceStr+'  from SaleOrdBill
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty '+@ReplaceStr+'  from BuyOrdBill
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty '+@ReplaceStr+'  from DraftData
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty '+@ReplaceStr+'  from StockData
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty '+@ReplaceStr+'  from SaleNotValid
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty '+@ReplaceStr+'  from BuyNotValid
	),PagingData as
	('		
	Select @sql += ' select '+ @OrderName+ ' Sum(Qty) as Qty,Sum(Total) as Total,Sum(SaleOrderQty) as SaleOrderQty,Sum(BuyOrderQty) as BuyOrderQty ,Sum(BuyNotValidQty) as BuyNotValidQty ,Sum(SaleNotValidQty) as SaleNotValidQty ,Sum(DraftQty) as DraftQty
	,(CASE WHEN SUM(ISNULL(Qty,0)) = 0 THEN 0 ELSE CAST(Cast(SUM(ISNULL(Total,0)) as DECIMAL(20,8))/SUM(ISNULL(Qty,0)) AS DECIMAL(20,8)) END) AS Price,'+ @VirtualFormula+' as VQty '+@ReplaceStr+' 
	
	from AllData A Inner Join BD_Goods G on A.GoodsID = G.GoodsID '
	if(@SumParam1 = 1)
	Begin
		if(@SumLevel1 <> 6 )
		Begin
		Select @sql += ' Inner Join BD_Whs W on A.WhsID = w.WhsID 
						  Inner Join dbo.UF_BD_BaseSummary(''KTYPE'', @SumLevel1) BW ON W.WhsTypeID = BW.ParID 
						  Inner Join BD_Whs_Type Wt On Wt.WhsTypeID = BW.BaseID
						 '
		End
		ELSE
			Select @Sql += ' Inner Join BD_Whs W on A.WhsID = w.WhsID '
	End
	if(@SumLevel2 <> 6 )
	BEGIN
		Select @Sql += ' Inner Join dbo.UF_BD_BaseSummary(''PTYPE'', @SumLevel2) BS ON G.GoodsTypeID = BS.ParID 
							Inner Join BD_Goods_Type Gt On gt.GoodsTypeID = bs.BaseID  '
	END
	
	
	Select @Sql += ' where A.WhsID is not null Group By '+ @SqlGroup+'
) '
  	    	

    SET @Sql += @BaseSql + 
			 ', DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM ' + @PageDataName + ') A 
						 CROSS JOIN
						(SELECT ROW_NUMBER() OVER(ORDER BY '+@OrderStr+') AS ROWID,* FROM ' + @PageDataName + ') B
						  WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				SELECT *, Qty AS BSQty FROM DATA ' + @DataSql + ' ORDER BY ROWID'
	
	IF @KtypeLimit = 0
		SET @Sql = N' SELECT * FROM PD_GoodsStock WHERE 1 <> 1'
	--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
	-- WHILE (@curPos < len(@sql))  
	-- BEGIN  
	--	 PRINT substring(@sql, @curPos, @curPos + 3999)  
	--	 SET @curPos += 3999 + 1  
	--	 SET @count += 1  
	-- END 				
	EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT, @WhsID VARCHAR(1000), @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100),
	                           @Spec VARCHAR(50), @Model VARCHAR(50), @SumLevel1 INT, @SumLevel2 INT, @OperatorID INT,
	                           @AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100)', 
	                         @PageNo, @PageSize, @WhsID, @GoodsNo, @GoodsName, @Spec, 
							 @Model, @SumLevel1, @SumLevel2, @OperatorID,@AbbName,@Brand,@BarCode
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_StockVirtualSum]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_StockVirtualSum
GO
/****** Object:  StoredProcedure [UP_PD_StockSummarySum]    Script Date: 07/28/2014 18:12:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/28
-- Description:	 库存状况表合计
-- =============================================
CREATE PROCEDURE [UP_PD_StockVirtualSum](
	 @WhsID VARCHAR(1000) = '',            --仓库
	 @GoodsNo VARCHAR(50) = '',            --商品编号
	 @GoodsNoMatch INT = 0,                --商品编号匹配方式 0:包含 1:等于
	 @GoodsName VARCHAR(100) = '',         --商品名称
	 @GoodsNameMatch INT = 0,              --商品名称匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',               --规格
	 @SpecMatch INT = 0,                   --规格匹配方式 0:包含 1:等于
	 @Model VARCHAR(50) = '',              --型号
	 @ModelMatch INT = 0,                  --型号匹配方式 0:包含 1:等于
	 @AbbName VARCHAR(50) = '',            --简名
	 @AbbNameMatch INT = 0,				   --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',              --品牌
	 @BrandMatch INT = 0,			       --品牌匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',            --条码
	 @BarCodeMatch INT = 0,                --条码匹配方式 0:包含 1:等于
	 @ShowStop BIT = 0,                    --显示停用商品
	 @OperatorID INT = 0                  --操作员ID       
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX), @SqlWhs varchar(max)='', @SqlWhsOut varchar(max)='',@SqlWhsIn varchar(max)='',@SaleOrdStr varchar(max)='',
			@BuyOrdStr varchar(max)='',@SqlGoods varchar(500)='',@SqlParam NVARCHAR(1000) = N'',@DraftSql Varchar(Max)='',@VirtualFormula varchar(300) = '',
	        @KtypeLimit INT = 0,@KtypeLimtStr varchar(max)='',@LimitSql VARCHAR(max)='',@LimitSqlIN VARCHAR(max)='',@LimitSqlOut VARCHAR(max)='',
		    @BuyNotValidSql NVARCHAR(1000) = N'',@SaleNotValidSql NVARCHAR(1000) = N'',
	        @LimitSql1 varchar(max)='',@SqlCreateTable varchar(max) = '',@CreatTableFlag INT=0 
                         
    --仓库权限                    
	SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID)  
	SELECT @VirtualFormula = Remark from SS_OtherCfg where ID = 102
	select @VirtualFormula = REPLACE(@VirtualFormula,'账面库存','sum(isnull(Qty,0))')
	select @VirtualFormula = REPLACE(@VirtualFormula,'采购订单在途数','sum(isnull(BuyOrderQty,0))')
	select @VirtualFormula = REPLACE(@VirtualFormula,'销售订单未发数','sum(isnull(SaleOrderQty,0))')
	select @VirtualFormula = REPLACE(@VirtualFormula,'草稿数量','sum(isnull(DraftQty,0))')     
	select @VirtualFormula = REPLACE(@VirtualFormula,'未生效采购订单数量','sum(isnull(BuyNotValidQty,0))')                   
	select @VirtualFormula = REPLACE(@VirtualFormula,'未生效销售订单数量','sum(isnull(SaleNotValidQty,0))')               
    IF @KtypeLimit = 1 --部份权限
    BEGIN
		SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) insert into @LimitKType Select WhsID from UF_BD_KtypeLimit(@OperatorID) '	
		Set @LimitSql += ' INNER JOIN @LimitKType LW ON I.WhsID=LW.TypeID ' 
		Set @LimitSql1 += ' INNER JOIN @LimitKType LW ON Detail.WhsID=LW.TypeID ' 
		Set @LimitSqlIN += ' INNER JOIN @LimitKType LW ON I.InWhsID=LW.TypeID ' 	
		Set @LimitSqlOut += ' INNER JOIN @LimitKType LW ON I.OutWhsID=LW.TypeID '
	END
    IF @WhsID <> ''     --仓库
    BEGIN
		SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) insert into @KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,'','') '
		Set @SqlWhs += ' Inner JOIN  @KType W on Detail.WhsID=W.TypeID ' 		
		--Set @SqlWhsOut += ' Inner JOIN  @KType W ON I.OutWhsID = W.TypeID or I.InWhsID=W.TypeID ' 
		Set @SqlWhsOut += ' Inner JOIN  @KType W ON I.OutWhsID = W.TypeID ' 
		Set @SqlWhsIn += ' Inner JOIN  @KType W ON I.InWhsID=W.TypeID ' 
	END						
	IF @GoodsNo <> ''   --商品编号 
	   BEGIN
		   SET @CreatTableFlag = 1
		   IF @GoodsNoMatch = 0
			   SET @SqlParam += N' AND goods.GoodsNo LIKE ''%'' + @GoodsNo +''%'''
		   ELSE IF @GoodsNoMatch = 1
			   SET @SqlParam += N' AND goods.GoodsNo = @GoodsNo '
	   END 
	   
	IF @GoodsName <> ''  --商品名称
	   BEGIN 
		   SET @CreatTableFlag = 1
		   IF @GoodsNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsName LIKE ''%'' + @GoodsName +''%'''
		   ELSE IF @GoodsNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsName = @GoodsName ' 
	   END 
	   
	IF @Spec <> ''       --商品规格 
	   BEGIN
	       SET @CreatTableFlag = 1
		   IF @SpecMatch = 0
			   SET @SqlParam += N' AND goods.Spec LIKE ''%'' + @Spec +''%'''
		   ELSE IF @SpecMatch = 1
			   SET @SqlParam += N' AND goods.Spec = @Spec '  
	   END 
	   
	IF @Model <> ''      --商品型号
	   BEGIN 
			SET @CreatTableFlag = 1
		   IF @ModelMatch = 0
			   SET @SqlParam += N' AND goods.Model LIKE ''%'' + @Model +''%'''
		   ELSE IF @ModelMatch = 1
			   SET @SqlParam += N' AND goods.Model = @Model ' 
	   END

	/*新增商品查询条件 start 150901*/
	IF @AbbName <> ''    --商品简名
	   BEGIN 
		   IF @AbbNameMatch = 0
			   SET @SqlParam += N' AND goods.GoodsAbbName LIKE ''%'' + @AbbName +''%'''
		   ELSE IF @AbbNameMatch = 1
			   SET @SqlParam += N' AND goods.GoodsAbbName = @AbbName ' 
	   END       
	IF @Brand <> ''      --商品品牌
	   BEGIN 
		   IF @BrandMatch = 0
			   SET @SqlParam += N' AND goods.Brand LIKE ''%'' + @Brand +''%'''
		   ELSE IF @BrandMatch = 1
			   SET @SqlParam += N' AND goods.Brand = @Brand ' 
	   END
	IF @BarCode <> ''      --商品条码
	   BEGIN 
		   SET @SqlParam += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price barcode WHERE barcode.GoodsID = goods.GoodsID '
		   IF @BarCodeMatch = 0
			   SET @SqlParam += N' AND barcode.BarCode LIKE ''%'' + @BarCode +''%'''
		   ELSE IF @BarCodeMatch = 1
			   SET @SqlParam += N' AND barcode.BarCode = @BarCode ' 
		   SET @SqlParam += ' ) '
	   END    
	/*end*/
	IF @ShowStop = 0        --不显示停用商品
	   SET @SqlParam += N' AND goods.Stt = 1 ' 
	   
	IF @CreatTableFlag = 1
	BEGIN
	   SET @SqlCreateTable += ' DECLARE @PTYPE AS TABLE(TYPEID	INT) INSERT INTO @PTYPE SELECT GOODSID FROM BD_GOODS goods WHERE 1=1' + @SqlParam	
	   SET @SqlGoods += ' Inner join @PTYPE g on detail.GoodsID = g.TYPEID '
	END
	ELSE 
	   SET @SqlGoods += ' Inner join (select GoodsID from BD_Goods goods where 1=1 '+@SqlParam+') g on detail.GoodsID = g.GoodsID '
	---销售订单数据
	SET @SaleOrdStr += 'select detail.GoodsID,detail.WhsID,0 as Qty,0 as Total,(sum(isnull(bsQty,0)) - sum(isnull(comQty,0))) as SaleOrderQty ,0 as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty
		from PD_SellOrdBill ord inner join PD_SellOrdDetail detail on ord.BillNo = detail.BillNo '+@SqlGoods+@LimitSql1+@SqlWhs+'
	where ord.isDraft = 0 and detail.StopTag = 0 and BSQty > ComQty  group by detail.GoodsID ,detail.WhsID '
	---采购订单数据
	SET @BuyOrdStr += 'select detail.GoodsID,detail.WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,(sum(isnull(bsQty,0)) - sum(isnull(comQty,0)) )	as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty
		from PD_PchOrdBill ord inner join PD_PchOrdDetail detail on ord.BillNo = detail.BillNo '+@SqlGoods+@LimitSql1+@SqlWhs+'
	where ord.isDraft = 0 and detail.StopTag = 0 and BSQty > ComQty  group by detail.GoodsID ,detail.WhsID  '
			--订单未生效订单，采购为正销售为负		
	Select @BuyNotValidSql+=' 
				SELECT Detail.GoodsID,Detail.WhsID as WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,0 as BuyOrderQty,0 as BuyNotValidQty,Sum(BSQty) as SaleNotValidQty,0 as DraftQty
				FROM  PD_SellOrdBill ord inner join PD_SellOrdDetail detail on ord.BillNo = detail.BillNo '
				+@SqlGoods+@LimitSql1+@SqlWhs
				+'where ord.isDraft = 1 and detail.StopTag = 0 group by detail.GoodsID ,detail.WhsID '
	Select @SaleNotValidSql+=' 
				SELECT Detail.GoodsID,Detail.WhsID as WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,0 as BuyOrderQty,Sum(BSQty) as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty
				FROM  PD_PchOrdBill ord inner join PD_PchOrdDetail detail on ord.BillNo = detail.BillNo '
				+@SqlGoods+@LimitSql1+@SqlWhs
				+'where ord.isDraft = 1 and detail.StopTag = 0 group by detail.GoodsID ,detail.WhsID '	
	
	---草稿数据
	Select @DraftSql +=' 
UNION ALL 
	SELECT Detail.GoodsID,I.WhsID,' + Case When BillTypeID IN (101,202,303,306) Then ' Sum(BSQty)' Else ' -Sum(BSQty)' End +' AS DraftQty'
	+ ' From ' + BillDetail +' detail Inner Join '+BillTable+' I on detail.BillNo = I.billNo'
	 +@SqlGoods+@LimitSql+@SqlWhs
	 +' Where IsDraft = 1 '
	+CASE WHEN BillTable IN (SELECT b.name FROM sys.columns a INNER JOIN sys.objects b ON a.object_id=b.object_id AND a.name='BilltypeID') THEN ' AND BillTypeID='+Cast(BillTypeID AS varchar) ELSE '' END
	+' group by detail.GoodsID,I.WhsID '
	from PD_BillType where BillTypeID in (101,102,201,202,303,304,305,306,600)
	Select @DraftSql+='
	UNION ALL
		SELECT Detail.GoodsID,Detail.OutWhsID as WhsID, -Sum(BSQty) AS DraftQty
		FROM  PD_AllotDetail Detail  Inner Join PD_AllotBill I ON  I.BillNo=Detail.BillNo '
		+@SqlGoods+@LimitSqlOut+@SqlWhsOut
		+'where IsDraft=1 ' 
		+' And BillTypeID = ' + Cast(BillTypeID as varchar(10))
		+' group by Detail.GoodsID,Detail.OutWhsID,Detail.InWhsID ' from PD_BillType where BillTypeID in (301,309)
Select @DraftSql+=' 
	UNION ALL 
		SELECT Detail.GoodsID,Detail.InWhsID as WhsID, Sum(BSQty) AS DraftQty
		FROM  PD_AllotDetail Detail Inner Join PD_AllotBill I ON  I.BillNo=Detail.BillNo '
		+@SqlGoods+@LimitSqlIN+@SqlWhsIn
		+'where IsDraft=1 ' 
		+' And BillTypeID = ' + Cast(BillTypeID as varchar(10))
	   +' group by Detail.GoodsID,Detail.OutWhsID,Detail.InWhsID ' from PD_BillType where BillTypeID in (301,309)
  Select @DraftSql+='
	UNION ALL
		SELECT Detail.GoodsID,Detail.WhsID as WhsID, -Sum(BSQty) AS DraftQty
		FROM  PD_AssemblyDetail Detail  Inner Join PD_AssemblyBill I ON  I.BillNo=Detail.BillNo '
		+@SqlGoods+@LimitSqlOut+@SqlWhsOut
		+'where IsDraft=1 and Detail.DetailType=2  group by Detail.GoodsID,Detail.WhsID '
	Select @DraftSql+=' 
		UNION ALL 
			SELECT Detail.GoodsID,Detail.WhsID as WhsID, Sum(BSQty) AS DraftQty
			FROM  PD_AssemblyDetail Detail Inner Join PD_AssemblyBill I ON  I.BillNo=Detail.BillNo '
			+@SqlGoods+@LimitSqlIN+@SqlWhsIn
			+'where IsDraft=1 and Detail.DetailType=1 group by Detail.GoodsID,Detail.WhsID '

	Select @Sql =@SqlCreateTable+
	';WITH SaleOrdBill AS 
	('	+@SaleOrdStr+'
	),BuyOrdBill AS (
		'+@BuyOrdStr+'
	),BuyNotValid AS('
	+@BuyNotValidSql+'
	),SaleNotValid AS('
	+@SaleNotValidSql+'
	),DraftBill AS(
	'+STUFF(@DraftSql,1,12,'')+'
	),DraftData as(
		select goodsID,WhsID,0 as Qty,0 as Total,0 as SaleOrderQty,0 as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,SUM(DraftQty) as DraftQty from DraftBill group by goodsID,WhsID
	),StockData as(
		SELECT  goods.GoodsID ,WhsID ,SUM(ISNULL(Detail.Qty,0)) AS Qty, SUM(ISNULL(Detail.Total,0)) AS Total, 
			  0 as SaleOrderQty,0 as BuyOrderQty,0 as BuyNotValidQty,0 as SaleNotValidQty,0 as DraftQty
			   FROM BD_Goods goods LEFT JOIN PD_GoodsStock Detail ON goods.GoodsID = Detail.GoodsID 
			   '+@LimitSql1+@SqlWhs+'
			   Where 1=1 '+@SqlParam+' 
			    GROUP BY  goods.GoodsID ,WhsID 
	),AllData As(
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty from SaleOrdBill
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty from BuyOrdBill
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty from DraftData
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty from StockData
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty from SaleNotValid
		Union All
		Select GoodsID,WhsID,Qty,Total,SaleOrderQty,BuyOrderQty,BuyNotValidQty,SaleNotValidQty,DraftQty from BuyNotValid
	)'	
		
	Select @sql += ' select Sum(Qty) as Qty,Sum(Total) as Total
	,'+ @VirtualFormula+' as VQty,SUM(SaleOrderQty) as SaleOrderQty,SUM(BuyOrderQty) as BuyOrderQty,SUM(BuyNotValidQty) as BuyNotValidQty,SUM(SaleNotValidQty) as SaleNotValidQty,SUM(DraftQty) as DraftQty
	from AllData '
  	    	
			
	EXEC sp_executesql @Sql, N'@WhsID VARCHAR(1000), @GoodsNo VARCHAR(50), @GoodsName VARCHAR(100),
	                           @Spec VARCHAR(50), @Model VARCHAR(50), @OperatorID INT,
	                           @AbbName VARCHAR(50), @Brand VARCHAR(50), @BarCode VARCHAR(100)', 
	                          @WhsID, @GoodsNo, @GoodsName, @Spec, @Model, @OperatorID,@AbbName,@Brand,@BarCode
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_SysRebuild]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_PD_SysRebuild]
GO
/****** Object:  StoredProcedure [UP_PD_SysRebuild]    Script Date: 03/11/2014 16:39:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/11/03
-- Description:	 系统重建
-- =============================================
CREATE PROCEDURE [UP_PD_SysRebuild](
     @ClearDraft BIT = 0,       --清除所有草稿
     @ClearFundsQc BIT = 0,     --清除现金银行期初
     @ClearBTypeQc BIT = 0,     --清除往来期初
     @ClearStockQc BIT = 0,     --清除库存期初
     @ClearPriceTrail BIT = 0,  --清除价格跟踪信息
     @ClearIEQc BIT = 0,        --清除收入支出期初
     @StartDate DATETIME
     ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX) = ' SET XACT_ABORT ON
								   BEGIN TRAN T
								   BEGIN 
								 '
								  
	--清除所有草稿							  
	IF @ClearDraft = 1
		BEGIN 
		    --删除所有单据、单据序列号明细
			SELECT @Sql += N' DELETE detail FROM '+ BillDetail + ' detail; '
						   +' DELETE FROM '+ BillTable +' ; '
						   + CASE WHEN BillSerial <> '' THEN ' DELETE FROM '+ BillSerial +' ; ' ELSE '' END
			FROM PD_BillType WHERE BillTable <> ''
			
			--删除所有单据编号种子、多账户、审核信息、删除积分明细
			SET @Sql += N' DELETE seed FROM PD_BillNoSeed seed; 
			               DELETE FROM PD_MulAccounts; 
			               DELETE FROM PD_AuditingBill; 
			               DELETE FROM PD_BillAuditStep; 
			               DELETE FROM PD_BillAuditEly; 
			               DELETE FROM dbo.PD_VipCardBillScore; '
		END
    ELSE
        BEGIN 
            --删除已处理的盘点单(删除序列号明细、审核信息）
			SELECT @Sql += N' DELETE bs FROM '+ BillSerial +' bs INNER JOIN '+ BillDetail +' detail ON bs.BillDID = detail.DID 
			                  INNER JOIN '+ BillTable +' bill ON detail.BillNo = bill.BillNo
			                  WHERE bill.Stt = 1; '+
						   N' DELETE ae FROM PD_BillAuditEly ae INNER JOIN PD_BillAuditStep asd ON ae.AuditStepID = asd.ID 
							  INNER JOIN PD_AuditingBill ab ON asd.AuditingID = ab.ID 
							  INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo WHERE bill.Stt = 1 AND ab.BillTypeID = 307; 
							  DELETE asd FROM PD_BillAuditStep asd INNER JOIN PD_AuditingBill ab ON asd.AuditingID = ab.ID 
							  INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo WHERE bill.Stt = 1 AND ab.BillTypeID = 307;
							  DELETE ab FROM PD_AuditingBill ab INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo 
							  WHERE bill.Stt = 1 AND ab.BillTypeID = 307;'+
						   N' DELETE detail FROM '+ BillDetail + ' detail WHERE EXISTS (SELECT bill.BillNo FROM '+ BillTable +' bill WHERE bill.BillNo = detail.BillNo AND bill.Stt = 1); '
					       +' DELETE FROM '+ BillTable +' WHERE Stt = 1; '
			FROM PD_BillType WHERE BillTypeID = 307
			
			--删除已过账的单据(删除序列号明细、多账户、审核信息）、会员卡相关删除积分明细
			SELECT @Sql += N' DELETE ma FROM PD_MulAccounts ma INNER JOIN '+ BillTable +' bill ON ma.BillNo = bill.BillNo 
			                  WHERE bill.IsDraft = 0 AND ma.BillTypeID = ' + CAST(BillTypeID AS NVARCHAR(5)) + ';' +
			                  CASE WHEN BillSerial <> '' THEN 
						   N' DELETE bs FROM '+ BillSerial +' bs INNER JOIN '+ BillDetail +'  detail ON bs.BillDID = detail.DID
			                  INNER JOIN '+ BillTable +' bill ON detail.BillNo = bill.BillNo 
			                  WHERE bill.IsDraft = 0;' ELSE '' END +
						   N' DELETE ae FROM PD_BillAuditEly ae INNER JOIN PD_BillAuditStep asd ON ae.AuditStepID = asd.ID 
							  INNER JOIN PD_AuditingBill ab ON asd.AuditingID = ab.ID 
							  INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo WHERE bill.IsDraft = 0 
							  AND ab.BillTypeID = ' + CAST(BillTypeID AS NVARCHAR(5)) + '; 
							  DELETE asd FROM PD_BillAuditStep asd INNER JOIN PD_AuditingBill ab ON asd.AuditingID = ab.ID 
							  INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo WHERE bill.IsDraft = 0 
							  AND ab.BillTypeID = ' + CAST(BillTypeID AS NVARCHAR(5)) + ';
							  DELETE ab FROM PD_AuditingBill ab INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo 
							  WHERE bill.IsDraft = 0 AND ab.BillTypeID = ' + CAST(BillTypeID AS NVARCHAR(5)) + ';'+
						   N' DELETE detail FROM '+ BillDetail + ' detail WHERE EXISTS (SELECT bill.BillNo FROM '+ BillTable +' bill WHERE bill.BillNo = detail.BillNo AND bill.IsDraft = 0); '
					       + CASE WHEN BillTypeID IN (201,202,600) THEN 
					         N' DELETE score FROM dbo.PD_VipCardBillScore score INNER JOIN '+ BillTable +' bill ON 
					            score.BillNo = bill.BillNo WHERE bill.IsDraft = 0 AND score.BillTypeID = ' 
					       + CAST(BillTypeID AS NVARCHAR(5)) + ';' ELSE '' END
					       +' DELETE FROM '+ BillTable +' WHERE IsDraft = 0; '
			FROM PD_BillType WHERE CanPost = 1
			
			--删除订单(已生效)、申请单(已生效)、发票及审核信息
			SELECT @Sql += N' DELETE ae FROM PD_BillAuditEly ae INNER JOIN PD_BillAuditStep asd ON ae.AuditStepID = asd.ID 
							  INNER JOIN PD_AuditingBill ab ON asd.AuditingID = ab.ID 
							  INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo WHERE ' + 
							  CASE WHEN BillTypeID = 100 OR BillTypeID = 200 OR BillTypeID = 308 THEN ' bill.IsDraft = 0 AND ' ELSE ''  END +
							  'ab.BillTypeID = ' + CAST(BillTypeID AS NVARCHAR(5)) + '; 
							  DELETE asd FROM PD_BillAuditStep asd INNER JOIN PD_AuditingBill ab ON asd.AuditingID = ab.ID 
							  INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo WHERE ' + 
							  CASE WHEN BillTypeID = 100 OR BillTypeID = 200 OR BillTypeID = 308 THEN ' bill.IsDraft = 0 AND ' ELSE ''  END + 
							  'ab.BillTypeID = ' + CAST(BillTypeID AS NVARCHAR(5)) + ';
							  DELETE ab FROM PD_AuditingBill ab INNER JOIN '+ BillTable +' bill ON ab.BillNo = bill.BillNo 
							  WHERE ab.BillTypeID = ' + CAST(BillTypeID AS NVARCHAR(5)) + 
							  CASE WHEN BillTypeID = 100 OR BillTypeID = 200 OR BillTypeID = 308 THEN ' AND bill.IsDraft = 0;' ELSE ';' END +
			               N' DELETE detail FROM '+ BillDetail + ' detail ' +  
			                  CASE WHEN BillTypeID = 100 OR BillTypeID = 200 OR BillTypeID = 308 THEN 
			                ' WHERE EXISTS (SELECT bill.BillNo FROM '+ BillTable +' bill WHERE bill.BillNo = detail.BillNo AND bill.IsDraft = 0); ' ELSE ';' END +
					        ' DELETE FROM '+ BillTable + CASE WHEN BillTypeID = 100 OR BillTypeID = 200 OR BillTypeID = 308 THEN 
					        ' WHERE IsDraft = 0; ' ELSE ' ; ' END
			FROM PD_BillType WHERE BillTypeID <> 307 AND BillTypeID <> 311 AND BillTable <> '' AND CanPost = 0
	        
	        --删除没有单据的类型种子
			SELECT @Sql += N' DELETE seed FROM PD_BillNoSeed seed WHERE seed.BillType = '+ CAST(BillTypeID AS NVARCHAR(5)) +' AND NOT EXISTS (SELECT bill.BillNo FROM '+ BillTable +' bill); '
		    FROM PD_BillType WHERE BillTable <> ''
        END
    
    --删除所有历史单据 (生产模板没有历史单据)
	SELECT @Sql += N' DELETE detail FROM '+ BillDetail + '_His detail '
			       +' DELETE FROM '+ BillTable + '_His'
				   + CASE WHEN BillSerial <> '' THEN ' DELETE FROM '+ BillSerial +'_His ; ' ELSE '' END
	FROM PD_BillType WHERE BillTable <> '' AND BillTypeID <> 311
	
	--删除单据科目、月结存相关、库存、收付款单据列表、发票明细（手工开票、按单开票下表体明细）、单据序列号明细历史、序列号记录、多账户历史、积分调整单、会员卡保留开卡金额和积分
	SET @Sql += N' DELETE FROM PD_ListTable;
                   DELETE FROM PD_ListTable_His;
                   DELETE FROM SS_MonthBalance;
                   DELETE FROM SS_MonthArAp;
                   DELETE FROM SS_MonthStock;
                   DELETE mp FROM SS_MonthProc mp WHERE Period <> 1;
                   UPDATE SS_MonthProc SET StartDate = @StartDate, EndDate = NULL, State = 1, Name = ''本期'' WHERE Period = 1;
                   DELETE FROM PD_GoodsStock_Detail;
                   DELETE FROM PD_GoodsStock;
                   DELETE list FROM MF_PayRecList list;
                   DELETE list_his FROM MF_PayRecList_His list_his; 
                   DELETE FROM MF_PchInvoiceContent;
                   DELETE FROM MF_PchInvoiceContent_His;
                   DELETE FROM MF_SellInvoiceContent;
                   DELETE FROM MF_SellInvoiceContent_His;
                   DELETE FROM PD_GoodsSerial;  
			       DELETE FROM PD_MulAccounts_His; 
			       DELETE FROM dbo.VS_CentAdjust; 
			       UPDATE dbo.VS_VipCard SET TotalMoney = BeginMoney,TotalExpenseMoney = BeginExpenseMoney,MoneyBalance = BeginStoreMoney
,TotalStoreMoney = isnull(BeginStoreMoney,0) + isnull(BeginExpenseMoney,0), TotalCent = BeginCent, CentBalance = BeginCent; ';
    
    --清除往来期初            
	IF @ClearBTypeQc = 1
		SET @Sql += N' DELETE FROM BD_ARAP; '
	ELSE
		BEGIN
		    --更新期末及期初应收应付为零
			SET @Sql += N' UPDATE BD_ARAP SET QmAR = 0, QmAP = 0, QmBR = 0, QmBP = 0, ARPaidTotal = 0, APPaidTotal = 0; '
			--删除各项为零的数据
			SET @Sql += N' DELETE FROM BD_ARAP WHERE QmAR = 0 AND QmAP = 0 AND QmBR = 0 AND QmBP = 0 AND ARPaidTotal = 0 AND APPaidTotal = 0 AND  
                                                     QcAR = 0 AND QcAP = 0 AND QcBR = 0 AND QcBP = 0; '
		END
		
    --清除现金银行期初              
	IF @ClearFundsQc = 1
		SET @Sql += N' DELETE a FROM BD_Funds a INNER JOIN BD_Finance b ON a.FinanceID = b.FinanceID 
					   WHERE b.[Path] LIKE ''00001%''; '
	ELSE
		BEGIN
		    --更新现金银行期末为零
			SET @Sql += N' UPDATE a SET a.QmBalances = 0 FROM BD_Funds a INNER JOIN BD_Finance b ON a.FinanceID = b.FinanceID 
							WHERE b.[Path] LIKE ''00001%''; '
			--删除现金银行各项为零的数据
			SET @Sql += N' DELETE a FROM BD_Funds a INNER JOIN BD_Finance b ON a.FinanceID = b.FinanceID 
							WHERE b.[Path] LIKE ''00001%'' AND  a.QcBalances = 0 AND a.QmBalances = 0; '
		END
    
    --清除库存期初              
	IF @ClearStockQc = 1
		SET @Sql += N' DELETE FROM BD_OpeningStock_Detail;
                       DELETE FROM BD_OpeningStock; 
                       DELETE FROM BD_OpeningSerial; '
                       
    --清除价格跟踪信息             
	IF @ClearPriceTrail = 1
		SET @Sql += N' DELETE FROM PD_PriceTrail; '
		
    --清除收入支出期初              
	IF @ClearIEQc = 1
		SET @Sql += N' DELETE a FROM BD_Funds a INNER JOIN BD_Finance b ON a.FinanceID = b.FinanceID 
					   WHERE b.[Path] LIKE ''00002%'' OR b.[Path] LIKE ''00003%''; '
	ELSE
		BEGIN
		    --更新收入支出期末为零
			SET @Sql += N' UPDATE a SET a.QmBalances = 0 FROM BD_Funds a INNER JOIN BD_Finance b ON a.FinanceID = b.FinanceID 
							WHERE b.[Path] LIKE ''00002%'' OR b.[Path] LIKE ''00003%''; '
			--删除收入支出各项为零的数据
			SET @Sql += N' DELETE a FROM BD_Funds a INNER JOIN BD_Finance b ON a.FinanceID = b.FinanceID 
							WHERE (b.[Path] LIKE ''00002%'' OR b.[Path] LIKE ''00003%'') AND  a.QcBalances = 0 AND a.QmBalances = 0; '
		END
	
	--更新为未开账、删除网店部分的单据、库存同步失败信息
	SET @Sql += N' UPDATE D9ZTInfo SET IsOpen = 0; 
				   DELETE FROM OS_OrderDetail;
                   DELETE FROM OS_OrderBill;
                   DELETE FROM OS_OrderDetailAll;
                   DELETE FROM OS_OrderBillAll;
                   DELETE FROM OS_FreightBill;
                   DELETE FROM OS_FreightBillAll;
                   DELETE FROM OS_BillRelation; 
                   DELETE FROM OS_SyncStockError; '
	
    SET @Sql += ' 
                  END
	              COMMIT TRAN T '

    EXEC sp_executesql @Sql, N'@StartDate DATETIME', @StartDate
END
GO




if exists (select * from sysobjects where id = object_id(N'[UP_PD_TransfersBill]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [UP_PD_TransfersBill]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		雷洋
-- Create date:  2014/6/17
-- Description:	 调价单
-- =============================================
CREATE PROCEDURE [UP_PD_TransfersBill](
     @BillNo int = 0
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	if exists( select 1 from MF_TransferBill where BillNo = @BillNo)
	begin	
		select  BillNo,
			BillDate,
			BillCode,
			Bill.DeptID,
			Bill.ElyID,
			bill.FinanceID,
			bill.PayRecTotal,
			bill.FeeFinanceID,
			bill.FeeTotal,		
			Total,
			Creator,
			PosElyID,
			Summary,
			Description,
			IsDraft,
			Red,
			f.FinanceName,
			ff.FinanceName as FeeFinanceName,
			d.DeptName,
			e.ElyName,
			ec.ElyName as CreatorName,
			ep.ElyName as PosName,
			 bill.AuditStatus
			from MF_TransferBill bill
		LEFT JOIN BD_Finance f ON bill.FinanceID = f.FinanceID
		LEFT JOIN BD_Finance ff ON bill.FeeFinanceID = ff.FinanceID
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 where BillNo = @BillNo
	     
		  SELECT	  detail.[DID]
			  ,detail.[BillNo]
			  ,detail.FinanceID
			  ,detail.Total
			  ,detail.[Remark]
			  ,f.FinanceNO
			  ,f.FinanceName
	 FROM MF_TransferDetail detail
		  INNER JOIN BD_Finance F ON detail.FinanceID=f.FinanceID	
	 WHERE detail.BillNo = @BillNo;  --查询明细       
	END
	ELSE
	BEGIN
		select  BillNo,
			BillDate,
			BillCode,
			Bill.DeptID,
			Bill.ElyID,
			bill.FinanceID,
			bill.PayRecTotal,
			bill.FeeFinanceID,
			bill.FeeTotal,		
			Total,
			Creator,
			PosElyID,
			Summary,
			Description,
			IsDraft,
			Red,
			f.FinanceName,
			ff.FinanceName as FeeFinanceName,
			d.DeptName,
			e.ElyName,
			ec.ElyName as CreatorName,
			ep.ElyName as PosName,
			 bill.AuditStatus
			from MF_TransferBill_His bill
		LEFT JOIN BD_Finance f ON bill.FinanceID = f.FinanceID
		LEFT JOIN BD_Finance ff ON bill.FeeFinanceID = ff.FinanceID
		 LEFT JOIN  BD_Dept d ON bill.DeptID=d.DeptID
		 LEFT JOIN  BD_Employee e ON bill.ElyID=e.ElyID
		 LEFT JOIN BD_Employee ec ON bill.Creator=ec.ElyID
		 LEFT JOIN BD_Employee ep ON bill.PosElyID=ep.ElyID
		 where BillNo = @BillNo
	     
		  SELECT	  detail.[DID]
			  ,detail.[BillNo]
			  ,detail.FinanceID
			  ,detail.Total
			  ,detail.[Remark]
			  ,f.FinanceNO
			  ,f.FinanceName
	 FROM MF_TransferDetail_His detail
		  INNER JOIN BD_Finance F ON detail.FinanceID=f.FinanceID	
	 WHERE detail.BillNo = @BillNo;  --查询明细      
	END                                          
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[UP_PD_UnsalableGoodsQuery]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [dbo].UP_PD_UnsalableGoodsQuery
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		HLin
-- Create date:  2015/2/28
-- Description:	 滞销商品查询
-- =============================================
CREATE PROCEDURE [dbo].[UP_PD_UnsalableGoodsQuery](
	 @PageSize INT=1,
	 @PageNo INT=1,
	 @BeginDate DATE,
	 @EndDate DATE,
	 @WhsID VARCHAR(1000) = '',            --仓库
	 @GoodsTypeID INT=0,				   --商品分类
	 @OperatorID INT = 0 ,                  --操作员ID 
	 @FullNameMatch INT,
	 @UserCodeMatch INT, 
	 @UserCode VARCHAR(200)='',
	 @FullName VARCHAR(200)='', 
	 @Model VARCHAR(50) = '',        --型号
	 @ModelMatch INT = 0,            --型号匹配方式 0:包含 1:等于
	 @GoodsAbbName VARCHAR(50) = '',      --简名
	 @GoodsAbbNameMatch INT = 0,          --简名匹配方式 0:包含 1:等于
	 @Brand VARCHAR(50) = '',        --品牌
	 @BrandMatch INT = 0,            --品牌匹配方式 0:包含 1:等于
	 @Spec VARCHAR(50) = '',         --规格
	 @SpecMatch INT = 0,             --规格匹配方式 0:包含 1:等于
	 @BarCode VARCHAR(100) = '',      --条码
	 @BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	 @SaleRate DECIMAL(20,4)=0, 
	 @OrderField VARCHAR(50),  
	 @Type INT
   ) 
AS
SET NOCOUNT ON;
	
	DECLARE @Sql NVARCHAR(4000)='',@JoinSql VARCHAR(max)='',@GoodsSql VARCHAR(max)=''
		,@BarCodeExist VARCHAR(max)=''
	IF @WhsID<>'' OR dbo.UF_BD_IsAllKtypeLimit(@OperatorID)<>2
	BEGIN
		CREATE TABLE #KType(TypeID INT) 
		IF @WhsID<>'' AND dbo.UF_BD_IsAllKtypeLimit(@OperatorID)=2
			INSERT INTO #KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,',') 
		ELSE IF @WhsID='' AND dbo.UF_BD_IsAllKtypeLimit(@OperatorID)<>2
			INSERT INTO #KType  Select WhsID from dbo.UF_BD_KtypeLimit(@OperatorID) 
		ELSE
			INSERT INTO #KType Select typeid from dbo.UF_OT_Split_Int(@WhsID,',') a inner join dbo.UF_BD_KtypeLimit(@OperatorID) kl ON kl.WhsID =a.typeid 
		SET @JoinSql=' INNER JOIN #KType W ON w.TypeID=b.WhsID '
	END   
	IF @GoodsTypeID=0                           
		SET @GoodsTypeID=1
	IF @GoodsTypeID<>1	
	BEGIN
		CREATE TABLE #PTypeType(TypeID INT) 
		INSERT INTO #PTypeType SELECT p1.GoodsTypeID  FROM dbo.BD_Goods_Type p INNER JOIN dbo.BD_Goods_Type p1 ON p1.Path LIKE p.Path+'%' WHERE p.GoodsTypeID=@GoodsTypeID
	END
	IF @FullName<>'' AND @UserCode=''
		SET @GoodsSql=' And p.GoodsName '+CASE @FullNameMatch WHEN 0 THEN ' Like''%'+@FullName+'%'' ' ELSE  ' ='''+@FullName+'''' END
	ELSE IF @FullName='' AND @UserCode<>''
		SET @GoodsSql=' And p.GoodsNO '+CASE @UserCodeMatch WHEN 0 THEN ' Like''%'+@UserCode+'%'' ' ELSE ' ='''+@UserCode+''''  END
	ELSE IF @FullName<>'' AND @UserCode<>''
		SET @GoodsSql=' And p.GoodsName '+CASE @FullNameMatch WHEN 0 THEN ' Like''%'+@FullName+'%'' ' ELSE  ' ='''+@FullName+'''' END
			+ ' And p.GoodsNO '+CASE @UserCodeMatch WHEN 0 THEN ' Like''%'+@UserCode+'%'' ' ELSE  ' ='''+@UserCode+'''' END
	--商品型号
	IF @Model <> ''      
	BEGIN 
	   IF @ModelMatch = 0
		   SET @GoodsSql += N' AND p.Model LIKE ''%'' + @Model +''%'''
	   ELSE IF @ModelMatch = 1
		   SET @GoodsSql += N' AND p.Model = @Model ' 
	END   
	--商品简名    
	IF @GoodsAbbName <> ''    
	BEGIN 
	   IF @GoodsAbbNameMatch = 0
		   SET @GoodsSql += N' AND p.GoodsAbbName LIKE ''%'' + @GoodsAbbName +''%'''
	   ELSE IF @GoodsAbbNameMatch = 1
		   SET @GoodsSql += N' AND p.GoodsAbbName = @GoodsAbbName ' 
	END       
	--商品品牌
	IF @Brand <> ''      
	BEGIN 
	   IF @BrandMatch = 0
		   SET @GoodsSql += N' AND p.Brand LIKE ''%'' + @Brand +''%'''
	   ELSE IF @BrandMatch = 1
		   SET @GoodsSql += N' AND p.Brand = @Brand ' 
	END
	--商品规格    
	IF @Spec <> ''        
	BEGIN 
	   IF @SpecMatch = 0
		   SET @GoodsSql += N' AND p.Spec LIKE ''%'' + @Spec +''%'''
	   ELSE IF @SpecMatch = 1
		   SET @GoodsSql += N' AND p.Spec = @Spec '  
	END
	--商品条码
	IF @BarCode <> ''      
	BEGIN 
	   IF @BarCodeMatch = 0
		  SET @BarCodeExist = N'AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=g.GoodsID)'
	   ELSE IF @BarCodeMatch = 1
		  SET @BarCodeExist = N'AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=g.GoodsID)'
	END 
	
	SET @sql='	
	;WITH PageData AS
	(
		SELECT p.GoodsNo,p.GoodsName,s.Qty SaleQty,g.Qty StockQty,u.Unit ,u.BarCode,p.Model,p.GoodsAbbName,p.Brand,p.Spec
		FROM(SELECT SUM(Qty)Qty,GoodsID FROM dbo.PD_GoodsStock B '+@JoinSql+' GROUP BY GoodsID)g
		INNER JOIN dbo.BD_Goods p ON g.GoodsID = p.GoodsID
		'+CASE WHEN @GoodsTypeID<>1 THEN 'INNER JOIN #PTypeType pt On pt.TypeID=p.GoodsTypeID 
		' ELSE '' END +'
		INNER JOIN dbo.BD_Goods_Price u ON u.GoodsID=p.GoodsID
		LEFT JOIN 
		(
			SELECT GoodsID,SUM(Qty)Qty
			FROM
			(
				SELECT d.GoodsID,SUM(BSQty)Qty FROM dbo.PD_SellDetail d
				INNER JOIN dbo.PD_SellBill b ON d.BillNo = b.BillNo'
				+@JoinSql+' 
				WHERE d.BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 AND Red=0 
				GROUP BY d.GoodsID
				UNION ALL
				SELECT d.GoodsID,SUM(BSQty)Qty FROM dbo.PD_SellDetail_His d
				INNER JOIN dbo.PD_SellBill_His b ON d.BillNo = b.BillNo'
				+@JoinSql+'
				WHERE d.BillDate BETWEEN @BeginDate AND @EndDate AND IsDraft=0 AND Red=0
				GROUP BY d.GoodsID
			)a
			Group BY GoodsID
		)s	ON g.GoodsID = s.GoodsID
		WHERE g.Qty>0 AND CAST(ISNULL(s.Qty,0)/g.Qty AS DECIMAL(20,6))<=@SaleRate/100
			AND u.UnitID=1 '+ @GoodsSql + @BarCodeExist
				 
	IF @Type=1	
		SET @sql+='
		)	
		SELECT * FROM 
		(SELECT COUNT(1)AS[RowCount] FROM PageData)a
		CROSS JOIN 
		(
			SELECT *,ROW_NUMBER() OVER( ORDER BY '+@OrderField+' ) AS ROWID
			FROM PageData
		)b		
		WHERE B.ROWID>(@PageNo-1)*@PageSize
		AND B.ROWID<=@PageNo*@PageSize'
	ELSE
		SET @sql+='
		)
		SELECT SUM(SaleQty)SaleQty,SUM(StockQty)StockQty FROM PageData
		'
	--PRINT @Sql
	EXEC sp_executesql @sql,N'@BeginDate Date,@EndDate Date,@SaleRate DECIMAL(20,4),@GoodsTypeID INT,@PageNo int,@PageSize INT,
	@Model VARCHAR(50), @ModelMatch INT, @GoodsAbbName VARCHAR(50), @GoodsAbbNameMatch INT, @Brand VARCHAR(50), @BrandMatch INT, @Spec VARCHAR(50), @SpecMatch INT, @BarCode VARCHAR(100), @BarCodeMatch INT',
	@BeginDate,@EndDate,@SaleRate,@GoodsTypeID,@PageNo,@PageSize,
	@Model , @ModelMatch, @GoodsAbbName, @GoodsAbbNameMatch, @Brand, @BrandMatch, @Spec, @SpecMatch, @BarCode, @BarCodeMatch
		
	if object_id('tempdb..#Ktype','U') is not null 
	DROP TABLE #Ktype
	if object_id('tempdb..#PTypeType','U') is not null 
	DROP TABLE #PTypeType
GO




IF exists (SELECT * FROM sysobjects WHERE id = object_id(N'[UP_PD_VipConsumDetail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [UP_PD_VipConsumDetail]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：wubin
	日期：2015-12-10
	描述：查询会员消费明细
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_VipConsumDetail]
(
	@PageNo INT=0,                       --页码
	@PageSize INT=0,                     --分页数
	@DateType INT=0,                     --单据日期类型 0:业务日期 1:制单日期 2:过账日期
	@BeginDate DATETIME,                 --单据开始日期
	@EndDate DATETIME,                   --单据结束日期
	@SaleBill INT = 1,                   --销售出库单勾选状态
	@SaleBackBill INT = 1,               --销售退货单勾选状态
	@ExchangeBill INT = 1,               --积分兑换单勾选状态
	@VipCardNO  VARCHAR(25)='',          --会员卡员
	@VipCardNOMatch INT=1,               --会员卡员匹配方式 0:包含 1:等于
	@VipCardTypeID VARCHAR(MAX)='',      --会员卡类型
	@VipName  VARCHAR(50)='',            --会员名称
	@VipNameMatch INT=0,                 --会员名称匹配方式 0:包含 1:等于
	@CardHolder  VARCHAR(50)='',         --持卡人
	@CardHolderMatch INT=0,              --持卡人匹配方式 0:包含 1:等于
	@Tel  VARCHAR(20)='',                --电话
	@TelMatch INT=0,                     --电话匹配方式 0:包含 1:等于
	@BTypeID VARCHAR(MAX)='',            --往来单位
	@DeptID VARCHAR(MAX)='',             --部门
	@ElyID VARCHAR(MAX)='',              --经手人
	@CreatorID VARCHAR(MAX)='',          --制单人
	@WhsID VARCHAR(MAX)='',              --仓库ID
	@UserCode VARCHAR(100)='',           --商品编号
	@UserCodeMatch INT=0,		         --商品编号匹配方式 0:包含 1:等于
	@FullName VARCHAR(100)='',           --商品名称
	@FullNameMatch INT=0,				 --商品名称匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',           --条码
	@BarCodeMatch INT = 0,               --条码匹配方式 0:包含 1:等于
	@GiftFlag INT=0,
	@OrderType1 VARCHAR(50)='VipCardNO', --排序一
	@OrderSeq1  INT=1,                   --排序一类型
	@OrderType2 VARCHAR(50)='PosTime',   --排序二
	@OrderSeq2  INT=1,                   --排序二类型
	@IsRedFlag INT = 0,
	@isHistory INT=0,				     --是否包含历史数据
	@OperatorID INT = 0,
	@Ppt1 VARCHAR(100)='',               --属性一
	@Ppt1Match INT=0,                    --属性一匹配方式 0:包含 1:等于
	@Ppt2 VARCHAR(100)='',               --属性二
	@Ppt2Match INT=0,                    --属性一匹配方式 0:包含 1:等于
	@ClassID1 INT = 0,		             --汇总条件一，ID
	@ClassType1 INT = 0,	             --汇总条件一类型
	@ClaseFlag1 INT = 0,	             --汇总条件一分类 0为非分类，1为分类汇总
	@ClassID2 INT = 0,		             --汇总条件二，ID
	@ClassType2 INT = 0,	             --汇总条件二类型
	@ClaseFlag2 INT = 0,		         --汇总条件二分类 0为非分类，1为分类汇总
	@GoodsDataFile1 VARCHAR(100) ='',    --商品自定义字段1
	@GoodsDataFile2 VARCHAR(100) ='',    --商品自定义字段2
	@GoodsDataFile3 VARCHAR(100) ='',    --商品自定义字段3
	@GoodsDataFile4 VARCHAR(100) ='',    --商品自定义字段4
	@GoodsDataFile5 VARCHAR(100) ='',    --商品自定义字段5
	@GoodsCFlag1 INT = 0,                --商品自定义字段1选中标识
	@GoodsCFlag2 INT = 0,                --商品自定义字段2选中标识
	@GoodsCFlag3 INT = 0,                --商品自定义字段3选中标识
	@GoodsCFlag4 INT = 0,                --商品自定义字段4选中标识
	@GoodsCFlag5 INT = 0                 --商品自定义字段5选中标识
)

AS
SET NOCOUNT ON
	-- 如果单据日期类型为业务日期 则检查是否存在归档数据
IF @DateType = 0
BEGIN
	DECLARE @re INT 
	execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
	IF( @re=1 )return @re;
END
DECLARE @sql NVARCHAR(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlCreateTable VARCHAR(MAX)='',@SqlTable VARCHAR(MAX)='',
        @SqlMatch VARCHAR(MAX)='',@SqlWhs VARCHAR(MAX), @SqlDept VARCHAR(MAX),@SqlEly VARCHAR(MAX),@SqlPost VARCHAR(MAX),
        @SqlUnit VARCHAR(2000),@SqlAuUnit VARCHAR(MAX)='',@SqlBtype VARCHAR(MAX)='',@SqlCreator VARCHAR(MAX),
        @SqlIn VARCHAR(MAX)='',@SqlOut VARCHAR(MAX)='',@OrderName VARCHAR(100)='',@OrderColumn VARCHAR(MAX)='',
        @OrderTable VARCHAR(MAX)='',@GoodsTable VARCHAR(MAX)='',@GoodsMath VARCHAR(MAX)='',@SqlGoods VARCHAR(1000)='',
        @SqlPpt1 VARCHAR(1000),@SqlPpt2 VARCHAR(1000), @LimitKtypeSql VARCHAR(MAX) = '', @LimitBtypeSql VARCHAR(MAX)='',
        @RedStr VARCHAR(100)='',@Red VARCHAR(100)='',@SqlClass1 VARCHAR(500)='',@SqlClass2 VARCHAR(500)='',
        @SqlBSUnit VARCHAR(1000)='',@SqlBase VARCHAR(MAX)='',@saleStr VARCHAR(MAX)='bill.BillNo,DID',
        @saleRetStr VARCHAR(MAX)='bill.BillNo,DID',@pageDataStr VARCHAR(MAX)=' BillNo,BillTypeID,DiD',
        @outSql VARCHAR(MAX)='',@SqlInStr VARCHAR(MAX)='',@SqlOutStr VARCHAR(MAX)='',@OutStr VARCHAR(MAX)='',
        @OutRetStr VARCHAR(MAX)='',@BtypeLimit INT=0,@KtypeLimit INT=0,@exchangeStr VARCHAR(MAX)='bill.BillNo,DID',
        @SqlVip VARCHAR(1000)='',@OutExchangeStr VARCHAR(MAX)='',@SqlEx VARCHAR(MAX)='',@SqlExStr VARCHAR(MAX)=''
        
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
SET @SqlMatch = ' AND bill.VipCardID > 0 '
IF @KtypeLimit = 1 --部分仓库权限
BEGIN
	SET @SqlCreateTable+=' DECLARE @LimitKType AS TABLE(TypeID INT) INSERT INTO @LimitKType SELECT WhsID FROM UF_BD_KtypeLimit(@OperatorID) '	
	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
END

IF @BtypeLimit = 1 --部分往来单位权限
BEGIN
	SET @SqlCreateTable+=' DECLARE @LimitBType AS TABLE(TypeID INT) INSERT INTO @LimitBType SELECT BtypeID FROM dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
END

SELECT @SqlCreateTable+= ' DECLARE @GoodsTypeID INT, @WhsTypeID INT, @DeptID INT
							IF @ClassID1 <> 0
							BEGIN
								IF (@ClassType1 = 1 and @ClaseFlag1 = 1) SET @GoodsTypeID = @ClassID1
								IF (@ClassType1 = 3 and @ClaseFlag1 = 1) SET @WhsTypeID = @ClassID1
								IF @ClassType1 = 5 SET @DeptID = @ClassID1
							END
							IF @ClassID2 <> 0
							BEGIN
								IF (@ClassType2 = 1 and @ClaseFlag2 = 1) SET @GoodsTypeID = @ClassID2
								IF (@ClassType2 = 3 and @ClaseFlag2 = 1) SELECT @WhsTypeID = @ClassID2
								IF @ClassType2 = 5 SELECT @DeptID = @ClassID2
							END '
IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType AS TABLE(TypeID INT) INSERT INTO @BType SELECT typeid FROM dbo.UF_OT_Split_INT(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END 
  
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType TABLE(TypeID INT) INSERT INTO @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_INT(@DeptID1,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON bill.DeptID=D.TypeID '
END	

IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType AS TABLE(TypeID INT) INSERT INTO @EType SELECT typeid FROM dbo.UF_OT_Split_INT(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON bill.ElyID=E.TypeID ' 
END	

IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType AS TABLE(TypeID INT) INSERT INTO @CreateEType SELECT typeid FROM dbo.UF_OT_Split_INT(@CreatorID,'','') '
	SET @SqlTable+=' INNER JOIN @CreateEType CE ON bill.Creator=CE.TypeID ' 
END	

IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType AS TABLE(TypeID INT) INSERT INTO @KType SELECT typeid FROM dbo.UF_OT_Split_INT(@WhsID,'','') '
	SET @SqlTable+=' INNER JOIN @KType W ON bill.WhsID=W.TypeID ' 
END	

IF (@VipCardNO <> '' OR @VipCardTypeID <> '' OR @VipName <> '' OR @CardHolder <> '' OR @Tel <> '')
BEGIN
	SET @SqlTable+=' INNER JOIN dbo.VS_VipCard VipCard ON bill.VipCardID=VipCard.VipCardID ' 
	IF(@VipCardNO <> '')
		SET @SqlMatch += ' AND VipCard.VipCardNO ' + CASE @VipCardNOMatch WHEN 0 THEN ' Like ''%''+@VipCardNO+''%''' ELSE ' =@VipCardNO ' END
	IF(@VipCardTypeID <> '')
	BEGIN		
		SET @SqlCreateTable+=' DECLARE @VipCardType AS TABLE(TypeID INT) INSERT INTO @VipCardType SELECT typeid FROM dbo.UF_OT_Split_INT(@VipCardTypeID,'','') '
	    SET @SqlTable+=' INNER JOIN @VipCardType VCT ON VipCard.VipCardTypeID=VCT.TypeID ' 
	END	
	IF(@VipName <> '')
		SET @SqlMatch += ' AND VipCard.VipName ' + CASE @VipNameMatch WHEN 0 THEN ' Like ''%''+@VipName+''%''' ELSE ' =@VipName ' END
	IF(@CardHolder <> '')
		SET @SqlMatch += ' AND VipCard.CardHolder ' + CASE @CardHolderMatch WHEN 0 THEN ' Like ''%''+@CardHolder+''%''' ELSE ' =@CardHolder ' END
	IF(@Tel <> '')
		SET @SqlMatch += ' AND VipCard.Tel ' + CASE @TelMatch WHEN 0 THEN ' Like ''%''+@Tel+''%''' ELSE ' =@Tel ' END
END	

IF @ClassID1 <> 0
BEGIN
	SET @SqlClass1 +=' DECLARE @CTb1 AS TABLE(typeid INT) INSERT INTO @CTb1(typeid) '
	SET @SqlCreateTable += CASE @ClassType1 WHEN 2 THEN CASE @ClaseFlag1 WHEN 0 THEN '' else @SqlClass1 + ' SELECT VipCardID FROM dbo.VS_VipCard WHERE VipCardTypeID = @ClassID1 ' END 
											WHEN 1 THEN CASE @ClaseFlag1 WHEN 0 THEN '' else @SqlClass1 + dbo.UF_BD_GetGoodsID_Str('') END 
											WHEN 3 THEN CASE @ClaseFlag1 WHEN 0 THEN '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) END
											WHEN 5 THEN @SqlClass1 + dbo.UF_BD_GetDeptID_Str() 
											else '' END
    SET @SqlTable += CASE @ClassType1 WHEN 2 THEN CASE @ClaseFlag1 WHEN 0 THEN ' AND bill.VipCardID = @ClassID1 ' else ' INNER JOIN @CTb1 C1 ON bill.VipCardID = C1.TypeID' END
									  WHEN 1 THEN CASE @ClaseFlag1 WHEN 0 THEN ' AND detail.GoodsID = @ClassID1 ' else ' INNER JOIN @CTb1 C1 ON detail.GoodsID = C1.TypeID' END 
									  WHEN 3 THEN CASE @ClaseFlag1 WHEN 0 THEN ' AND bill.WhsID = @ClassID1 ' else ' INNER JOIN @CTb1 C1 ON Bill.WhsID = C1.TypeID' END
									  WHEN 5 THEN ' INNER JOIN BD_Employee EE ON Bill.ElyID = EE.ElyID INNER JOIN @CTb1 C1 ON EE.DeptId = C1.TypeID'
									  WHEN 6 THEN ' AND bill.ElyID = @ClassID1 '  
									  When 7 THEN ' AND bill.Creator = @ClassID1' END 	
	
END

IF @ClassID2 <> 0
BEGIN
	SET @SqlClass2 +=' DECLARE @CTb2  AS TABLE(typeid INT) INSERT INTO @CTb2(typeid) '
	SET @SqlCreateTable += CASE @ClassType2 WHEN 2 THEN CASE @ClaseFlag2 WHEN 0 THEN '' else @SqlClass2 + ' SELECT VipCardID FROM dbo.VS_VipCard WHERE VipCardTypeID = @ClassID2 ' END 
											WHEN 1 THEN CASE @ClaseFlag2 WHEN 0 THEN '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') END 
											WHEN 3 THEN CASE @ClaseFlag2 WHEN 0 THEN '' else @SqlClass2 + dbo.UF_BD_GetWhsID_Str(@WhsID) END
											WHEN 5 THEN @SqlClass2 + dbo.UF_BD_GetDeptID_Str() 
											else '' END
    SET @SqlTable += CASE @ClassType2 WHEN 2 THEN CASE @ClaseFlag2 WHEN 0 THEN ' AND bill.VipCardID = @ClassID2 ' else ' INNER JOIN @CTb2 C2 ON bill.VipCardID = C2.TypeID' END
									  WHEN 1 THEN CASE @ClaseFlag2 WHEN 0 THEN ' AND detail.GoodsID = @ClassID2 ' else ' INNER JOIN @CTb2 C2 ON detail.GoodsID = C2.TypeID' END 
									  WHEN 3 THEN CASE @ClaseFlag2 WHEN 0 THEN ' AND bill.WhsID = @ClassID2 ' else ' INNER JOIN @CTb2 C2 ON Bill.WhsID = C2.TypeID' END
									  WHEN 5 THEN ' INNER JOIN BD_Employee EE ON Bill.ElyID = EE.ElyID INNER JOIN @CTb2 C2 ON EE.DeptId = C2.TypeID'
									  WHEN 6 THEN ' AND bill.ElyID = @ClassID2 '  
									  When 7 THEN ' AND bill.Creator = @ClassID2' END 		
END

-- 判断单据时间类型
IF @DateType = 0
	SET @SqlDTStr = 'detail.BillDate'
IF @DateType=1
	SET @SqlDTStr = 'bill.CreateTime'	
IF @DateType=2
	SET @SqlDTStr = 'bill.PosTime'
	
IF @FullName <> '' or @UserCode <> ''
BEGIN
	IF(@FullName <> '')
		SET @GoodsMath += ' AND G.GoodsName ' + CASE @FullNameMatch WHEN 0 THEN ' Like ''%''+@FullName+''%''' ELSE ' =@FullName ' END
	IF(@UserCode <> '')
		SET @GoodsMath += ' AND G.GoodsNo ' + CASE @UserCodeMatch WHEN 0 THEN ' Like ''%''+@UserCode+''%''' ELSE ' =@UserCode ' END
	SET @GoodsTable += ' AND exists(SELECT 1 FROM BD_GOODS G Where detail.GoodsID = G.GoodsID '+@GoodsMath+')'
END

--商品条码
IF @BarCode <> ''      
BEGIN 
   SET @SqlTable += ' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID and pri.UnitID = 1 '	
   SET @GoodsTable += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = detail.GoodsID '
   IF @BarCodeMatch = 0
	   SET @GoodsTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @GoodsTable += N' AND pri.BarCode = @BarCode ' 
   SET @GoodsTable += ' ) '
END 

IF (@ClassType1 = 1 AND @ClaseFlag1 = 0) OR (@ClassType2 = 1 AND @ClaseFlag2 = 0)
BEGIN
	IF @Ppt1Match = 1
	BEGIN
		IF @Ppt1 <> ''
			SET @GoodsTable += ' AND exists(SELECT 1 FROM BD_Goods_Ppt1 GP1 Where detail.Ppt1ID = GP1.Ppt1ID AND GP1.Value = @Ppt1)'
		ELSE 
			SET @GoodsTable += ' AND Ppt1ID = 0 ' 
	END
	IF @Ppt2Match = 1
	BEGIN	
		IF @Ppt2 <> ''
			SET @GoodsTable += ' AND exists(SELECT 1 FROM BD_Goods_Ppt2 GP2 Where detail.Ppt2ID = GP2.Ppt2ID AND GP2.Value = @Ppt2)'
		ELSE 
			SET @GoodsTable += ' AND Ppt2ID = 0 ' 	
	END
END
		
--自定义字段汇总查询明细
IF(@GoodsDataFile1 <> '' OR @GoodsCFlag1 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG1 ON detail.GoodsID = BG1.BaseID '
	SET @SqlMatch += ' AND BG1.CustVal1 = @GoodsDataFile1 '
END
IF(@GoodsDataFile2 <> '' OR @GoodsCFlag2 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG2 ON detail.GoodsID = BG2.BaseID '
	SET @SqlMatch += ' AND BG2.CustVal2 = @GoodsDataFile2 '
END
IF(@GoodsDataFile3 <> '' OR @GoodsCFlag3 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG3 ON detail.GoodsID = BG3.BaseID '
	SET @SqlMatch += ' AND BG3.CustVal3 = @GoodsDataFile3 '
END
IF(@GoodsDataFile4 <> '' OR @GoodsCFlag4 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG4 ON detail.GoodsID = BG4.BaseID '
	SET @SqlMatch += ' AND BG4.CustVal4 = @GoodsDataFile4 '
END
IF(@GoodsDataFile5 <> '' OR @GoodsCFlag5 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG5 ON detail.GoodsID = BG5.BaseID '
	SET @SqlMatch += ' AND BG5.CustVal5 = @GoodsDataFile5 '
END

IF(@IsRedFlag = 0) --不显红冲
	SET @Red = ' AND Red = 0 '
ELSE
	SET @RedStr = ' ,Red '
	
--按排序条件拼接首次需要查询的数据
IF(@OrderType1 <> '')
BEGIN
	SET @saleStr += CASE WHEN @OrderType1 in ('BTypeCode','BTypeName') THEN ',bill.BTypeID '
							When @OrderType1 in ('GoodsNo','GoodsName') THEN ',detail.GoodsID'
							When @OrderType1 = 'Profit' THEN ',(detail.DiscTotal-detail.GoodsCostTotal) AS Profit'
							When @OrderType1 = 'ProfitMargin' THEN ',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin'
							When @OrderType1 = 'BillTypeID' THEN '' 
							When @OrderType1 in ('BillCode','CreateTime','PosTime') THEN ','+@OrderType1
							When @OrderType1 = 'BillDate' THEN ',bill.'+@OrderType1
							WHEN @OrderType1 in ('VipCardNO','TypeName','VipName') THEN ',bill.VipCardID'
							else ',detail.'+@OrderType1 END --加入会卡信息的排序
	SET @saleRetStr += CASE WHEN @OrderType1 in ('BTypeCode','BTypeName') THEN ',bill.BTypeID '
						When @OrderType1 in ('GoodsNo','GoodsName') THEN ',detail.GoodsID'
						When @OrderType1 = 'Profit' THEN ',(detail.DiscTotal-detail.GoodsCostTotal)*-1 AS Profit'
						When @OrderType1 = 'ProfitMargin' THEN ',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin'
						When @OrderType1 in ('Qty','Total','DiscTotal','CostPrice') THEN ',detail.'+@OrderType1+'*-1'
						When @OrderType1 = 'BillTypeID' THEN '' 
						When @OrderType1 in ('BillCode','CreateTime','PosTime') THEN ','+@OrderType1
						When @OrderType1 = 'BillDate' THEN ',bill.'+@OrderType1
						WHEN @OrderType1 in ('VipCardNO','TypeName','VipName') THEN ',bill.VipCardID' --加入会卡信息的排序
						else ',detail.'+@OrderType1 END
						
	SET @exchangeStr +=  CASE WHEN @OrderType1 in ('BTypeCode','BTypeName') THEN ',bill.BTypeID '
						When @OrderType1 in ('GoodsNo','GoodsName') THEN ',detail.GoodsID'
						When @OrderType1 = 'Profit' THEN ', -detail.GoodsCostTotal AS Profit'
						When @OrderType1 in ('ProfitMargin','Price','Total','DiscPrice','DiscTotal','Discount') THEN ', 0 AS '+@OrderType1
						When @OrderType1 = 'BillTypeID' THEN '' 
						When @OrderType1 in ('BillCode','CreateTime','PosTime') THEN ','+@OrderType1
						When @OrderType1 = 'BillDate' THEN ',bill.'+@OrderType1
						WHEN @OrderType1 in ('VipCardNO','TypeName','VipName') THEN ',bill.VipCardID' --加入会卡信息的排序
						else ',detail.'+@OrderType1 END
						
	SET @pageDataStr += CASE When @OrderType1 in ('BTypeCode','BTypeName') THEN ',bill.BTypeID '
						When @OrderType1 in ('GoodsNo','GoodsName') THEN ',bill.GoodsID'
						When @OrderType1 = 'CreateTime' THEN ',CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime'
						When @OrderType1 = 'PosTime' THEN ',CONVERT(VARCHAR(100), PosTime, 120) AS PosTime'
						When @OrderType1 = 'BillTypeID' THEN '' 
						WHEN @OrderType1 in ('VipCardNO','TypeName','VipName') THEN ',bill.VipCardID' --加入会卡信息的排序
						ELSE ','+@OrderType1 END
END		
IF(@OrderType2 <> '')
BEGIN			
	SET @saleStr += CASE WHEN @OrderType2 in ('BTypeCode','BTypeName') THEN CASE When @OrderType1 in ('BTypeCode','BTypeName') THEN '' else ',bill.BTypeID ' END 
							When @OrderType2 in ('GoodsNo','GoodsName') THEN CASE When @OrderType1 in ('GoodsNo','GoodsName') THEN '' else ',detail.GoodsID' END
							When @OrderType2 = 'Profit' THEN ',(detail.DiscTotal-detail.GoodsCostTotal) AS Profit'
							When @OrderType2 = 'ProfitMargin' THEN ',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin'
							When @OrderType2 = 'BillTypeID' THEN '' 
							When @OrderType2 in ('BillCode','CreateTime','PosTime') THEN ','+@OrderType2
							When @OrderType2 = 'BillDate' THEN ',bill.'+@OrderType2
							WHEN @OrderType2 in ('VipCardNO','TypeName','VipName')  THEN CASE When @OrderType1 in ('VipCardNO','TypeName','VipName') THEN '' else ',bill.VipCardID' END --加入会卡信息的排序
							else ',detail.'+@OrderType2 END
						
	SET @saleRetStr += CASE WHEN @OrderType2 in ('BTypeCode','BTypeName') THEN CASE When @OrderType1 in ('BTypeCode','BTypeName') THEN '' else ',bill.BTypeID ' END 
						When @OrderType2 in ('GoodsNo','GoodsName') THEN CASE When @OrderType1 in ('GoodsNo','GoodsName') THEN '' else ',detail.GoodsID' END
						When @OrderType2 = 'Profit' THEN ',(detail.DiscTotal-detail.GoodsCostTotal)*-1 AS Profit'
						When @OrderType2 = 'ProfitMargin' THEN ',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin'
						When @OrderType2 in ('Qty','Total','DiscTotal','CostPrice') THEN ',detail.'+@OrderType2+'*-1'
						When @OrderType2 = 'BillTypeID' THEN '' 
						When @OrderType2 in ('BillCode','CreateTime','PosTime') THEN ','+@OrderType2
						When @OrderType2 = 'BillDate' THEN ',bill.'+@OrderType2
						WHEN @OrderType2 in ('VipCardNO','TypeName','VipName')  THEN CASE When @OrderType1 in ('VipCardNO','TypeName','VipName') THEN '' else ',bill.VipCardID' END --加入会卡信息的排序
						else ',detail.'+@OrderType2 END	
						
	SET @exchangeStr +=  CASE WHEN @OrderType2 in ('BTypeCode','BTypeName') THEN CASE When @OrderType1 in ('BTypeCode','BTypeName') THEN '' else ',bill.BTypeID ' END
						When @OrderType2 in ('GoodsNo','GoodsName') THEN CASE When @OrderType1 in ('GoodsNo','GoodsName') THEN '' else ',detail.GoodsID' END
						When @OrderType2 = 'Profit' THEN ', -detail.GoodsCostTotal AS Profit'
						When @OrderType2 in ('ProfitMargin','Price','Total','DiscPrice','DiscTotal','Discount') THEN ', 0 AS '+@OrderType2
						When @OrderType2 = 'BillTypeID' THEN '' 
						When @OrderType2 in ('BillCode','CreateTime','PosTime') THEN ','+@OrderType2
						When @OrderType2 = 'BillDate' THEN ',bill.'+@OrderType2
						WHEN @OrderType2 in ('VipCardNO','TypeName','VipName') THEN CASE When @OrderType1 in ('VipCardNO','TypeName','VipName') THEN '' else ',bill.VipCardID' END --加入会卡信息的排序
						else ',detail.'+@OrderType2 END
							
	SET @pageDataStr += CASE When @OrderType2 in ('BTypeCode','BTypeName') THEN CASE When @OrderType1 in ('BTypeCode','BTypeName') THEN '' else ',bill.BTypeID ' END	
						When @OrderType2 in ('GoodsNo','GoodsName') THEN CASE When @OrderType1 in ('GoodsNo','GoodsName') THEN '' else ',bill.GoodsID' END 
						When @OrderType2 = 'CreateTime' THEN ',CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime'
						When @OrderType2 = 'PosTime' THEN ',CONVERT(VARCHAR(100), PosTime, 120) AS PosTime'
						When @OrderType2 = 'BillTypeID' THEN '' 
						WHEN @OrderType2 in ('VipCardNO','TypeName','VipName') THEN CASE When @OrderType1 in ('VipCardNO','TypeName','VipName') THEN '' else ',bill.VipCardID' END --加入会卡信息的排序
						ELSE ','+@OrderType2 END				
END				

	
--拼接查询字段
SET @OutStr +=',bill.BillDate,BillCode,bill.BTypeID,CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime,CONVERT(VARCHAR(100), PosTime, 120) AS PosTime,detail.GoodsID,detail.Discount,bill.VipCardID
	,CASE When Bill.Red = 2 THEN detail.Qty * -1 ELSE detail.Qty END AS Qty,detail.Price
	,CASE When Bill.Red = 2 THEN detail.Total * -1 ELSE detail.Total END AS Total,detail.DiscPrice
	,CASE WHEN Bill.Red = 2 Then detail.DiscTotal * -1 ELSE detail.DiscTotal END AS DiscTotal,detail.CostPrice
	,CASE When Bill.Red = 2 THEN detail.GoodsCostTotal * -1 ELSE detail.GoodsCostTotal END AS GoodsCostTotal
	,CASE When Bill.Red = 2 THEN (detail.DiscTotal-detail.GoodsCostTotal)*-1 ELSE (detail.DiscTotal-detail.GoodsCostTotal) END AS Profit
	,CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin	'
SET @OutRetStr +=',bill.BillDate,BillCode,bill.BTypeID,CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime,CONVERT(VARCHAR(100), PosTime, 120) AS PosTime,detail.GoodsID,detail.Discount,bill.VipCardID
  ,CASE When Bill.Red = 2 THEN detail.Qty ELSE detail.Qty*-1 END AS Qty,detail.Price
  ,CASE When Bill.Red = 2 Then detail.Total ELSE detail.Total*-1 END AS Total,detail.DiscPrice
  ,CASE When Bill.Red = 2 Then detail.DiscTotal ELSE detail.DiscTotal*-1 END AS  DiscTotal,detail.CostPrice
  ,CASE When Bill.Red = 2 Then detail.GoodsCostTotal ELSE detail.GoodsCostTotal*-1 END AS GoodsCostTotal
  ,CASE When Bill.Red = 2 Then (detail.DiscTotal-detail.GoodsCostTotal) ELSE (detail.DiscTotal-detail.GoodsCostTotal)*-1 END AS Profit
  ,CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin  '
  
SET @OutStr = CASE WHEN @OrderType1 in ('BTypeCode','BTypeName') THEN REPLACE(@OutStr,',bill.BTypeID','')
					WHEN @OrderType1 in ('GoodsNo','GoodsName') THEN REPLACE(@OutStr,',detail.GoodsID','')
					When @OrderType1 = 'BillCode' THEN REPLACE(@OutStr,',BillCode','') 
					When @OrderType1 = 'BillDate' THEN REPLACE(@OutStr,',bill.BillDate','') 
					When @OrderType1 = 'CreateTime' THEN REPLACE(@OutStr,',CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' THEN REPLACE(@OutStr,',CONVERT(VARCHAR(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN detail.Qty * -1 ELSE detail.Qty END AS Qty','') 
					When @OrderType1 = 'Price' THEN REPLACE(@OutStr,',detail.Price','') 
					When @OrderType1 = 'Total' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN detail.Total * -1 ELSE detail.Total END AS Total','') 
					When @OrderType1 = 'Discount' THEN REPLACE(@OutStr,',detail.Discount','') 
					When @OrderType1 = 'DiscPrice' THEN REPLACE(@OutStr,',detail.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' THEN REPLACE(@OutStr,',CASE WHEN Bill.Red = 2 Then detail.DiscTotal * -1 ELSE detail.DiscTotal END AS DiscTotal','') 
					When @OrderType1 = 'GoodsCostTotal' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN detail.GoodsCostTotal * -1 ELSE detail.GoodsCostTotal END AS GoodsCostTotal','') 
					When @OrderType1 = 'CostPrice' THEN REPLACE(@OutStr,',detail.CostPrice','') 
					When @OrderType1 = 'Profit' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN (detail.DiscTotal-detail.GoodsCostTotal)*-1 ELSE (detail.DiscTotal-detail.GoodsCostTotal) END AS Profit','') 
					When @OrderType1 = 'ProfitMargin' THEN REPLACE(@OutStr,',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin','') 
					When @OrderType1 in ('VipCardNO','TypeName','VipName') THEN REPLACE(@OutStr,',bill.VipCardID','') 
					ELSE @OutStr END
SET @OutStr = CASE WHEN @OrderType2 in ('BTypeCode','BTypeName') THEN REPLACE(@OutStr,',bill.BTypeID','')
					WHEN @OrderType2 in ('GoodsNo','GoodsName') THEN REPLACE(@OutStr,',detail.GoodsID','')
					When @OrderType2 = 'BillCode' THEN REPLACE(@OutStr,',BillCode','') 
					When @OrderType2 = 'BillDate' THEN REPLACE(@OutStr,',bill.BillDate','') 
					When @OrderType2 = 'CreateTime' THEN REPLACE(@OutStr,',CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' THEN REPLACE(@OutStr,',CONVERT(VARCHAR(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN detail.Qty * -1 ELSE detail.Qty END AS Qty','') 
					When @OrderType2 = 'Price' THEN REPLACE(@OutStr,',detail.Price','') 
					When @OrderType2 = 'Total' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN detail.Total * -1 ELSE detail.Total END AS Total','') 
					When @OrderType2 = 'Discount' THEN REPLACE(@OutStr,',detail.Discount','') 
					When @OrderType2 = 'DiscPrice' THEN REPLACE(@OutStr,',detail.DiscPrice','') 
					When @OrderType2 = 'DiscTotal' THEN REPLACE(@OutStr,',CASE WHEN Bill.Red = 2 Then detail.DiscTotal * -1 ELSE detail.DiscTotal END AS DiscTotal','') 
					When @OrderType2 = 'GoodsCostTotal' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN detail.GoodsCostTotal * -1 ELSE detail.GoodsCostTotal END AS GoodsCostTotal','') 
					When @OrderType2 = 'CostPrice' THEN REPLACE(@OutStr,',detail.CostPrice','') 
					When @OrderType2 = 'Profit' THEN REPLACE(@OutStr,',CASE When Bill.Red = 2 THEN (detail.DiscTotal-detail.GoodsCostTotal)*-1 ELSE (detail.DiscTotal-detail.GoodsCostTotal) END AS Profit','') 
					When @OrderType2 = 'ProfitMargin' THEN REPLACE(@OutStr,',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin','')
					When @OrderType2 in ('VipCardNO','TypeName','VipName') THEN REPLACE(@OutStr,',bill.VipCardID','') 
					ELSE @OutStr END
SET @OutRetStr = CASE WHEN @OrderType1 in ('BTypeCode','BTypeName') THEN REPLACE(@OutRetStr,',bill.BTypeID','')
					WHEN @OrderType1 in ('GoodsNo','GoodsName') THEN REPLACE(@OutRetStr,',detail.GoodsID','')
					When @OrderType1 = 'BillCode' THEN REPLACE(@OutRetStr,',BillCode','') 
					When @OrderType1 = 'BillDate' THEN REPLACE(@OutRetStr,',bill.BillDate','') 
					When @OrderType1 = 'CreateTime' THEN REPLACE(@OutRetStr,',CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType1 = 'PosTime' THEN REPLACE(@OutRetStr,',CONVERT(VARCHAR(100), PosTime, 120) AS PosTime','') 
					When @OrderType1 = 'Qty' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 THEN detail.Qty ELSE detail.Qty*-1 END AS Qty','') 
					When @OrderType1 = 'Price' THEN REPLACE(@OutRetStr,',detail.Price','') 
					When @OrderType1 = 'Total' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then detail.Total ELSE detail.Total*-1 END AS Total','') 
					When @OrderType1 = 'Discount' THEN REPLACE(@OutRetStr,',detail.Discount','') 
					When @OrderType1 = 'DiscPrice' THEN REPLACE(@OutRetStr,',detail.DiscPrice','') 
					When @OrderType1 = 'DiscTotal' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then detail.DiscTotal ELSE detail.DiscTotal*-1 END AS  DiscTotal','') 
					When @OrderType1 = 'GoodsCostTotal' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then detail.GoodsCostTotal ELSE detail.GoodsCostTotal*-1 END AS GoodsCostTotal','') 
					When @OrderType1 = 'CostPrice' THEN REPLACE(@OutRetStr,',detail.CostPrice','') 
					When @OrderType1 = 'Profit' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then (detail.DiscTotal-detail.GoodsCostTotal) ELSE (detail.DiscTotal-detail.GoodsCostTotal)*-1 END AS Profit','') 
					When @OrderType1 = 'ProfitMargin' THEN REPLACE(@OutRetStr,',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin','') 
					When @OrderType1 in ('VipCardNO','TypeName','VipName') THEN REPLACE(@OutRetStr,',bill.VipCardID','') 
					ELSE @OutRetStr END
SET @OutRetStr = CASE WHEN @OrderType2 in ('BTypeCode','BTypeName') THEN REPLACE(@OutRetStr,',bill.BTypeID','')
					WHEN @OrderType2 in ('GoodsNo','GoodsName') THEN REPLACE(@OutRetStr,',detail.GoodsID','')
					When @OrderType2 = 'BillCode' THEN REPLACE(@OutRetStr,',BillCode','') 
					When @OrderType2 = 'BillDate' THEN REPLACE(@OutRetStr,',bill.BillDate','') 
					When @OrderType2 = 'CreateTime' THEN REPLACE(@OutRetStr,',CONVERT(VARCHAR(100), CreateTime, 120) AS CreateTime','') 
					When @OrderType2 = 'PosTime' THEN REPLACE(@OutRetStr,',CONVERT(VARCHAR(100), PosTime, 120) AS PosTime','') 
					When @OrderType2 = 'Qty' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 THEN detail.Qty ELSE detail.Qty*-1 END AS Qty','') 
					When @OrderType2 = 'Price' THEN REPLACE(@OutRetStr,',detail.Price','') 
					When @OrderType2 = 'Total' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then detail.Total ELSE detail.Total*-1 END AS Total','') 
					When @OrderType2 = 'Discount' THEN REPLACE(@OutRetStr,',detail.Discount','') 
					When @OrderType2 = 'DiscPrice' THEN REPLACE(@OutRetStr,',detail.DiscPrice','') 
					When @OrderType2 = 'DiscTotal' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then detail.DiscTotal ELSE detail.DiscTotal*-1 END AS  DiscTotal','') 
					When @OrderType2 = 'GoodsCostTotal' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then detail.GoodsCostTotal ELSE detail.GoodsCostTotal*-1 END AS GoodsCostTotal','') 
					When @OrderType2 = 'CostPrice' THEN REPLACE(@OutRetStr,',detail.CostPrice','') 
					When @OrderType2 = 'Profit' THEN REPLACE(@OutRetStr,',CASE When Bill.Red = 2 Then (detail.DiscTotal-detail.GoodsCostTotal) ELSE (detail.DiscTotal-detail.GoodsCostTotal)*-1 END AS Profit','') 
					When @OrderType2 = 'ProfitMargin' THEN REPLACE(@OutRetStr,',CASE detail.DiscTotal WHEN 0 THEN 0 else ((detail.DiscTotal-detail.GoodsCostTotal)/detail.DiscTotal)*100 END AS ProfitMargin','') 
					When @OrderType2 in ('VipCardNO','TypeName','VipName') THEN REPLACE(@OutRetStr,',bill.VipCardID','') 
					ELSE @OutRetStr END
--拼接主表查询字段语句					
SET  @SqlIn += ' SELECT 201 AS BillTypeID,'+@saleStr+@RedStr
		+' ,detail.UnitID FROM PD_SellBill bill INNER JOIN PD_SellDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=0 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
		
SET  @SqlEx += ' SELECT 600 AS BillTypeID,'+@exchangeStr+@RedStr
		+' ,detail.UnitID FROM PD_InOutWhsBill bill INNER JOIN PD_InOutWhsDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=0  AND bill.BillTypeID = 600 ' + CASE  WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
		
SET @SqlOut += ' SELECT 202 AS BillTypeID,'+@saleRetStr+@RedStr
		+' ,detail.UnitID FROM PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=0 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
--拼接查询字段
SET @OutExchangeStr = REPLACE(@OutStr, 'detail.Discount', '1 AS Discount')
SET @OutExchangeStr = REPLACE(@OutExchangeStr, 'detail.Total', '0')
SET @OutExchangeStr = REPLACE(@OutExchangeStr, 'detail.DiscTotal', '0')
SET @OutExchangeStr = REPLACE(@OutExchangeStr, 'detail.Price', '0 AS Price')
SET @OutExchangeStr = REPLACE(@OutExchangeStr, 'detail.DiscPrice', '0 AS DiscPrice')
--拼接排序后语句字段
SET @SqlInStr += ' SELECT A.*,'''+'销售出库单' +''' AS BillName,bill.DeptID,bill.ElyID,PosElyID
		,detail.WhsID,Creator AS CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 AS BSUnitID,detail.UnitID,Convfactor,
		CASE When Bill.Red = 2 THEN detail.BSQty * -1 else detail.BSQty END BSQty,Summary,Description,detail.Remark ' +@OutStr
		+' FROM #tempTable A INNER JOIN PD_SellBill bill On a.BillNo = bill.BillNo INNER JOIN PD_SellDetail detail ON bill.BillNo = detail.BillNo and a.DID = detail.DID
		WHERE a.BillTypeID = 201' 
		
SET @SqlExStr += ' SELECT A.*,'''+'积分兑换单' +''' AS BillName,bill.DeptID,bill.ElyID,PosElyID
		,detail.WhsID,Creator AS CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 AS BSUnitID,detail.UnitID,Convfactor,
		CASE When Bill.Red = 2 Then detail.BSQty* -1 ELSE detail.BSQty END AS BSQty,Summary,Description,detail.Remark ' +@OutExchangeStr
		+' FROM #tempTable A INNER JOIN dbo.PD_InOutWhsBill bill On a.BillNo = bill.BillNo INNER JOIN dbo.PD_InOutWhsDetail detail ON bill.BillNo = detail.BillNo and a.DID = detail.DID
		WHERE a.BillTypeID = 600 '
		
SET @SqlOutStr += ' SELECT A.*,'''+'销售退货单' +''' AS BillName,bill.DeptID,bill.ElyID,PosElyID
		,detail.WhsID,Creator AS CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 AS BSUnitID,detail.UnitID,Convfactor,
		CASE When Bill.Red = 2 Then detail.BSQty ELSE detail.BSQty*-1 END AS BSQty,Summary,Description,detail.Remark ' +@OutRetStr
		+' FROM #tempTable A INNER JOIN PD_SellRetBill bill On a.BillNo = bill.BillNo INNER JOIN PD_SellRetDetail detail ON bill.BillNo = detail.BillNo and a.DID = detail.DID
		WHERE a.BillTypeID = 202 '
IF(@IsRedFlag <> 0) --显示红冲
BEGIN
	SET  @SqlIn += '
		Union All
		SELECT 201 AS BillTypeID,'+@saleStr+@RedStr
		+' ,detail.UnitID FROM PD_SellBill bill INNER JOIN PD_SellDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=1 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
  SET  @SqlEx += ' Union All
		(SELECT 600 AS BillTypeID,'+@exchangeStr+@RedStr
		+' ,detail.UnitID FROM dbo.PD_InOutWhsBill bill INNER JOIN dbo.PD_InOutWhsDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=1 ' 
		+ CASE  WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable + ' ) '	
	SET  @SqlIn += '
		Union All
		 SELECT 201 AS BillTypeID,'+@saleRetStr+@RedStr  
		+' ,detail.UnitID FROM PD_SellBill bill INNER JOIN PD_SellDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=2' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
SET  @SqlEx += ' Union All
		(SELECT 600 AS BillTypeID,'+ Replace(@exchangeStr,'-detail.GoodsCostTotal','detail.GoodsCostTotal') +@RedStr
		+' ,detail.UnitID FROM dbo.PD_InOutWhsBill bill INNER JOIN dbo.PD_InOutWhsDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=2 ' 
		+ CASE  WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable + ' ) '
	SET @SqlOut += ' 
		Union All
		SELECT 202 AS BillTypeID,'+@saleRetStr+@RedStr  
		+' ,detail.UnitID FROM PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=1 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
	SET @SqlOut += ' 
		Union All
		SELECT 202 AS BillTypeID,'+@saleStr+@RedStr  
		+' ,detail.UnitID FROM PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=2 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
END

IF @isHistory=1
BEGIN
	SET  @SqlIn += '
		UNION ALL
	 SELECT 201 AS BillTypeID,'+@saleStr+@RedStr  
		+' ,detail.UnitID FROM PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=0 '  + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END +
		 +@SqlMatch + @GoodsTable
	SET  @SqlEx += '
	 UNION ALL (SELECT 600 AS BillTypeID,'+@exchangeStr+@RedStr
		+' ,detail.UnitID FROM PD_InOutWhsBill_His bill INNER JOIN PD_InOutWhsDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=0  AND bill.BillTypeID = 600 ' + CASE  WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable + ' ) '
	SET @SqlOut += '
		UNION ALL
	 SELECT 202 AS BillTypeID,'+@saleRetStr+@RedStr  
		+' ,detail.UnitID FROM PD_SellRetBill_his bill INNER JOIN PD_SellRetDetail_his detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=0' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END +
		+@SqlMatch + @GoodsTable
	--拼接排序后语句字段
SET @SqlInStr += ' 
		UNION ALL
		SELECT A.*,'''+'销售出库单' +''' AS BillName,bill.DeptID,bill.ElyID,PosElyID
		,detail.WhsID,Creator AS CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 AS BSUnitID,detail.UnitID,Convfactor,
		CASE When Bill.Red = 2 THEN detail.BSQty * -1 else detail.BSQty END BSQty,Summary,Description,detail.Remark ' + @OutStr
		+' FROM #tempTable A INNER JOIN PD_SellBill_His bill On a.BillNo = bill.BillNo INNER JOIN PD_SellDetail_His detail ON bill.BillNo = detail.BillNo and a.DID = detail.DID
		WHERE a.BillTypeID = 201 '
		
SET @SqlExStr += ' UNION ALL (SELECT A.*,'''+'积分兑换单' +''' AS BillName,bill.DeptID,bill.ElyID,PosElyID
		,detail.WhsID,Creator AS CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 AS BSUnitID,detail.UnitID,Convfactor,
		CASE When Bill.Red = 2 Then detail.BSQty* -1 ELSE detail.BSQty END AS BSQty,Summary,Description,detail.Remark ' +@OutExchangeStr
		+' FROM #tempTable A INNER JOIN dbo.PD_InOutWhsBill_His bill On a.BillNo = bill.BillNo INNER JOIN dbo.PD_InOutWhsDetail_His detail ON bill.BillNo = detail.BillNo and a.DID = detail.DID)'
		
SET @SqlOutStr += ' 
		UNION ALL
		SELECT A.*,'''+'销售退货单' +''' AS BillName,bill.DeptID,bill.ElyID,PosElyID
		,detail.WhsID,Creator AS CreatorID,detail.Ppt1ID,detail.Ppt2ID,1 AS BSUnitID,detail.UnitID,Convfactor,
		CASE When Bill.Red = 2 Then detail.BSQty ELSE detail.BSQty*-1 END AS BSQty,Summary,Description,detail.Remark ' +@OutRetStr
		+' FROM #tempTable A INNER JOIN PD_SellRetBill_His bill On a.BillNo = bill.BillNo INNER JOIN PD_SellRetDetail_His detail ON bill.BillNo = detail.BillNo and a.DID = detail.DID
		WHERE a.BillTypeID = 202 '
  IF(@IsRedFlag <> 0)
  BEGIN
	SET  @SqlIn += '
		Union All
		SELECT 201 AS BillTypeID,'+@saleStr+@RedStr    
		+' ,detail.UnitID FROM PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=1 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable	
			
	SET  @SqlIn += '
		Union All
		 SELECT 201 AS BillTypeID,'+@saleRetStr+@RedStr 
		+' ,detail.UnitID FROM PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=2' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
		
   SET  @SqlEx += ' Union All
		(SELECT 600 AS BillTypeID,'+@exchangeStr+@RedStr
		+' ,detail.UnitID FROM dbo.PD_InOutWhsBill_His bill INNER JOIN dbo.PD_InOutWhsDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=1 ' 
		+ CASE  WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable + ' ) '
		
SET  @SqlEx += ' Union All
		(SELECT 600 AS BillTypeID,'+Replace(@exchangeStr,'-detail.GoodsCostTotal','detail.GoodsCostTotal') +@RedStr
		+' ,detail.UnitID FROM dbo.PD_InOutWhsBill_His bill INNER JOIN dbo.PD_InOutWhsDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=2 ' 
		+ CASE  WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable + ' ) '
		
	SET @SqlOut += ' 
		Union All
		SELECT 202 AS BillTypeID,'+@saleRetStr+@RedStr   
		+' ,detail.UnitID FROM PD_SellRetBill_His bill INNER JOIN PD_SellRetDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=1 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
		
	SET @SqlOut += ' 
		Union All
		SELECT 202 AS BillTypeID,'+@saleStr+@RedStr    
		+' ,detail.UnitID FROM PD_SellRetBill_His bill INNER JOIN PD_SellRetDetail_His detail ON bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 AND Red=2 ' + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END + 
		+@SqlMatch + @GoodsTable
  END
END
	
IF (@SaleBill = 1)  
BEGIN  
 IF(@SaleBackBill = 1 OR @ExchangeBill = 1)  
 BEGIN
  SELECT @Sql += @SqlIn+ ' UNION ALL ' ;  
  SELECT @outSql += @SqlInStr+ ' UNION ALL ' ;  
 END
 else  
 BEGIN
  SELECT @Sql += @SqlIn ;  
  SELECT @outSql += @SqlInStr ;  
 END
END  
IF (@SaleBackBill = 1)  
BEGIN
 SELECT @Sql += @SqlOut;  
 SELECT @outSql += @SqlOutStr;  
END
IF (@ExchangeBill = 1)  
BEGIN
	IF (@SaleBackBill = 1) 
	 BEGIN
	  SELECT @Sql += ' UNION ALL ' ;  
	  SELECT @outSql += ' UNION ALL ' ;  
	 END
 SELECT @Sql += @SqlEx;  
 SELECT @outSql += @SqlExStr;  
END

IF (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
BEGIN
	SET @OrderColumn += ',BT.BTypeCode,BT.BTypeName '
	SET @OrderTable +=' INNER JOIN BD_Btype BT ON bill.BTypeID = BT.BTypeID '
END 
IF (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
BEGIN
	SET @OrderColumn += ',G.GoodsNo,G.GoodsName,G.Model,G.GoodsAbbName,G.Brand,G.Spec,pri.BarCode '
	SET @OrderTable +=' INNER JOIN BD_GOODS G ON bill.GoodsID = G.GoodsID '
	SET @OrderTable +=' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = bill.GoodsID and pri.UnitID = bill.UnitID  '
END 
IF (@OrderType1 in ('VipCardNO','VipName','TypeName') or @OrderType2 in ('VipCardNO','VipName','TypeName') )
BEGIN
	SET @OrderTable +=' INNER JOIN dbo.VS_VipCard V ON bill.VipCardID = V.VipCardID '
	IF @OrderType1 in ('TypeName') or @OrderType2 in ('TypeName')
	BEGIN 
		SET @OrderColumn += ' ,V.VipCardTypeID, VT.TypeName '
		SET @OrderTable +=' INNER JOIN dbo.VS_VipCardType VT ON VT.VipCardTypeID = V.VipCardTypeID  '
	END
	ELSE
		SET @OrderColumn += ' ,V.VipCardTypeID, V.VipCardNO, V.VipName '
END --会员排序信息

SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
),
 PagingData AS
 (
	SELECT '+@pageDataStr+@OrderColumn+@RedStr+'  
		FROM Bill bill '+@OrderTable
 SET @sql +=' )
'

IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType  ---返回一一个空记录，不让页面报错
	RETURN 
END

---排序字段
IF @OrderType1 <> ''
BEGIN
	IF @OrderSeq1 = 1 SET @OrderName = @OrderType1+' ASC' ELSE SET @OrderName = @OrderType1 +' DESC'
END
IF @OrderType2 <> ''
BEGIN
	IF @OrderName <> '' SET @OrderName +=', '
	IF @OrderSeq2 = 1 SET @OrderName += @OrderType2+' ASC' ELSE SET @OrderName += @OrderType2 +' DESC'
END						

------------------添加参数---------------------------------------
IF Not (@OrderType1 in ('BTypeCode','BTypeName') or  @OrderType2 in ('BTypeCode','BTypeName'))
BEGIN	
	SELECT @SqlBtype+= ' INNER JOIN BD_Btype B ON Data.BtypeID = B.BtypeID '
	SELECT @SqlBase +=' ,B.BTypeCode,B.BTypeName '
END
IF Not (@OrderType1 in ('GoodsNo','GoodsName') or @OrderType2 in ('GoodsNo','GoodsName') )
BEGIN
	SELECT @SqlGoods+= ' INNER JOIN BD_Goods G ON Data.GoodsID = G.GoodsID '
	SELECT @SqlGoods+= ' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = Data.GoodsID and pri.UnitID = Data.UnitID '
	SELECT @SqlBase +=' ,G.GoodsNo,G.GoodsName,G.Model,G.GoodsAbbName,G.Brand,G.Spec,pri.BarCode '
END
SET @SqlVip+= ' INNER JOIN dbo.VS_VipCard Vip ON Vip.VipCardID = Data.VipCardID '
SET @SqlBase +=' ,Vip.VipName,Vip.CardHolder,Vip.CardHolder,Vip.IDNO,Vip.Sex,Vip.Birthday,Vip.Address,Vip.Tel,Vip.Email,Vip.Status,Vip.EndDate '
IF Not (@OrderType1 in ('VipCardNO','VipName') or @OrderType2 in ('VipCardNO','VipName') )
	SET @SqlBase +=' ,Vip.VipCardNO, Vip.VipName '
IF @OrderType1 <> 'TypeName' AND @OrderType2 <> 'TypeName'
BEGIN
	SET @SqlVip+= ' INNER JOIN dbo.VS_VipCardType VipT ON VipT.VipCardTypeID = Vip.VipCardTypeID '
	SET @SqlBase +=' ,VipT.VipCardTypeID, VipT.TypeName '
END

SET @SqlAuUnit += ' LEFT JOIN BD_Goods_Price BGP1 ON Data.GoodsID=BGP1.GoodsID AND BGP1.UnitID = 1 '
SET @SqlAuUnit += ' LEFT JOIN BD_Goods_Price BGP2 ON Data.GoodsID=BGP2.GoodsID AND BGP2.UnitID = 2'
SET @SqlAuUnit += ' LEFT JOIN BD_Goods_Price BGP3 ON Data.GoodsID=BGP3.GoodsID AND BGP3.UnitID = 3'
SELECT @SqlBase += ' ,BGP1.Unit AS Unit1,BGP1.Convfactor AS Convfactor1 '
SELECT @SqlBase += ' ,BGP2.Unit AS Unit2,CASE WHEN BGP2.Convfactor IS NULL THEN 1 else BGP2.Convfactor END AS Convfactor2'
SELECT @SqlBase += ' ,BGP3.Unit AS Unit3,CASE WHEN BGP3.Convfactor IS NULL THEN 1 else BGP3.Convfactor END AS Convfactor3'

SELECT @sql += ',DATA AS (
   SELECT * FROM (SELECT COUNT(1) AS '''+'ROWCOUNT'+''' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY '+@OrderName+') AS ROWID,
	*
	FROM PagingData

   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize
	)
	SELECT * INTO #tempTable FROM DATA
	--SELECT * FROM DATA
	'
SELECT @sql +=' SELECT Data.*,WhsNO,WhsName,DeptCode,DeptName,E.ElyCode,E.ElyName AS ElyName,EC.ElyName AS Creator,EP.ElyName AS PostName,Gpc.Unit,BSGpc.Unit AS BSUnit
	,GP1.Value AS Ppt1Name,GP2.Value AS Ppt2Name '+@SqlBase+'
	 FROM ('+@outSql+') Data  
	INNER JOIN BD_Whs W On Data.WhsID = W.WhsID
	Left JOIN BD_Dept D ON Data.DeptID = D.DeptID  
	LEFT JOIN BD_Employee E ON Data.ElyID = E.ElyID 
	LEFT JOIN BD_Employee EC ON Data.CreatorID = EC.ElyID 
	LEFT JOIN BD_Employee EP ON Data.PosElyID = EP.ElyID 
	INNER JOIN BD_Goods_Price Gpc On Data.UnitID = Gpc.UnitID and Data.GoodsID = Gpc.GoodsID 
	INNER JOIN BD_Goods_Price BSGpc On Data.BSUnitID = BSGpc.UnitID and Data.GoodsID = BSGpc.GoodsID 
	LEFT JOIN BD_Goods_Ppt1 GP1 ON Data.Ppt1ID = GP1.Ppt1ID 
	LEFT JOIN BD_Goods_Ppt2 GP2 ON Data.Ppt2ID = GP2.Ppt2ID 
	' + @SqlBtype + @SqlGoods + @SqlAuUnit + @SqlVip
SELECT @sql += ' ORDER BY ROWID '
SELECT @sql += ' drop table #tempTable '
--DECLARE @curPos INT = 1 , @count INT = 1  ,@dec NVARCHAR(max)=N''
--	 WHILE (@curPos < len(@sql))  
--	 BEGIN  
--		 PRINT substring(@sql, @curPos, @curPos + 3999)  
--		 SET @curPos += 3999 + 1  
--		 SET @count += 1  
--	 END 
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
exec sp_executesql @Sql,N'@PageNo INT,@PageSize INT,@DateType INT,@BeginDate DateTime,@EndDate DateTime,@OperatorID INT,@ClassID1 INT,@ClassType1 INT,@ClaseFlag1 INT,@ClassID2 INT,@ClassType2 INT,@ClaseFlag2 INT,@BTypeID VARCHAR(MAX),@DeptID1 VARCHAR(MAX),@ElyID VARCHAR(MAX),@CreatorID VARCHAR(MAX),@WhsID VARCHAR(MAX),@FullName VARCHAR(100),@UserCode VARCHAR(100), @BarCode VARCHAR(100), @BarCodeMatch INT,@GoodsDataFile1 VARCHAR(100),@GoodsDataFile2 VARCHAR(100),@GoodsDataFile3 VARCHAR(100),@GoodsDataFile4 VARCHAR(100),@GoodsDataFile5 VARCHAR(100), @Ppt1 VARCHAR(100), @Ppt2 VARCHAR(100),@VipCardNO  VARCHAR(25), @VipCardTypeID VARCHAR(MAX), @VipName VARCHAR(50), @CardHolder VARCHAR(50), @Tel VARCHAR(20)',@PageNo,@PageSize,@DateType,@BeginDate,@EndDate,@OperatorID,@ClassID1,@ClassType1,@ClaseFlag1,@ClassID2,@ClassType2,@ClaseFlag2,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@FullName,@UserCode,@BarCode,@BarCodeMatch,@GoodsDataFile1,@GoodsDataFile2 ,@GoodsDataFile3 ,@GoodsDataFile4 ,@GoodsDataFile5,@Ppt1,@Ppt2, @VipCardNO, @VipCardTypeID, @VipName, @CardHolder, @Tel
GO



IF exists (SELECT * FROM sysobjects WHERE id = object_id(N'[UP_PD_VipConsumDetailSum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [UP_PD_VipConsumDetailSum]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：wubin
	日期：2015-12-10
	描述：会员消费明细合计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_VipConsumDetailSum]
(
	@DateType INT=0,                     --单据日期类型 0:业务日期 1:制单日期 2:过账日期
	@BeginDate DATETIME,                 --单据开始日期
	@EndDate DATETIME,                   --单据结束日期
	@SaleBill INT = 1,                   --销售出库单勾选状态
	@SaleBackBill INT = 1,               --销售退货单勾选状态
	@ExchangeBill INT = 1,               --积分兑换单勾选状态
	@VipCardNO  VARCHAR(25)='',          --会员卡员
	@VipCardNOMatch INT=1,               --会员卡员匹配方式 0:包含 1:等于
	@VipCardTypeID VARCHAR(max)='',      --会员卡类型
	@VipName  VARCHAR(50)='',            --会员名称
	@VipNameMatch INT=0,                 --会员名称匹配方式 0:包含 1:等于
	@CardHolder  VARCHAR(50)='',         --持卡人
	@CardHolderMatch INT=0,              --持卡人匹配方式 0:包含 1:等于
	@Tel  VARCHAR(20)='',                --电话
	@TelMatch INT=0,                     --电话匹配方式 0:包含 1:等于
	@BTypeID VARCHAR(max)='',            --往来单位
	@DeptID VARCHAR(max)='',             --部门
	@ElyID VARCHAR(max)='',              --经手人
	@CreatorID VARCHAR(max)='',          --制单人
	@WhsID VARCHAR(max)='',              --仓库ID
	@UserCode VARCHAR(100)='',           --商品编号
	@UserCodeMatch INT=0,		         --商品编号匹配方式 0:包含 1:等于
	@FullName VARCHAR(100)='',           --电话
	@FullNameMatch INT=0,				 --电话匹配方式 0:包含 1:等于
	@BarCode VARCHAR(100) = '',           --条码
	@BarCodeMatch INT = 0,               --条码匹配方式 0:包含 1:等于
	@GiftFlag INT=0,
	@IsRedFlag Int = 0,
	@isHistory INT=0,				     --是否包含历史数据
	@OperatorID INT = 0,
	@Ppt1 VARCHAR(100)='',               --属性一
	@Ppt1Match INT=0,                    --属性一匹配方式 0:包含 1:等于
	@Ppt2 VARCHAR(100)='',               --属性二
	@Ppt2Match INT=0,                    --属性一匹配方式 0:包含 1:等于
	@ClassID1 Int = 0,		             --汇总条件一，ID
	@ClassType1 Int = 0,	             --汇总条件一类型
	@ClaseFlag1 Int = 0,	             --汇总条件一分类 0为非分类，1为分类汇总
	@ClassID2 Int = 0,		             --汇总条件二，ID
	@ClassType2 Int = 0,	             --汇总条件二类型
	@ClaseFlag2 Int = 0,		         --汇总条件二分类 0为非分类，1为分类汇总
	@GoodsDataFile1 VARCHAR(100) ='',    --商品自定义字段1
	@GoodsDataFile2 VARCHAR(100) ='',    --商品自定义字段2
	@GoodsDataFile3 VARCHAR(100) ='',    --商品自定义字段3
	@GoodsDataFile4 VARCHAR(100) ='',    --商品自定义字段4
	@GoodsDataFile5 VARCHAR(100) ='',    --商品自定义字段5
	@GoodsCFlag1 int = 0,                --商品自定义字段1选中标识
	@GoodsCFlag2 int = 0,                --商品自定义字段2选中标识
	@GoodsCFlag3 int = 0,                --商品自定义字段3选中标识
	@GoodsCFlag4 int = 0,                --商品自定义字段4选中标识
	@GoodsCFlag5 int = 0                 --商品自定义字段5选中标识
)

AS
SET NOCOUNT ON
DECLARE @sql NVARCHAR(MAX)='',@SqlDTStr VARCHAR(20)='',@SqlCreateTable VARCHAR(MAX)='',@SqlTable VARCHAR(MAX)='',
        @SqlMatch VARCHAR(MAX)='', @SqlIn VARCHAR(MAX)='',@SqlOut VARCHAR(MAX)='',@GoodsTable VARCHAR(MAX)='',
        @GoodsMath VARCHAR(MAX)='',@LimitKtypeSql VARCHAR(MAX) = '', @LimitBtypeSql VARCHAR(MAX)='',
        @Red VARCHAR(100)='',@SqlClass1 VARCHAR(500)='',@SqlClass2 VARCHAR(500)='',@BtypeLimit INT=0,
        @KtypeLimit INT=0,@SqlEx VARCHAR(MAX)='',@DecParam NVARCHAR(MAX)='',@param NVARCHAR(MAX)='',
        @ExcSql NVARCHAR(MAX)=''
        
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
SET @SqlMatch = ' AND bill.VipCardID > 0 '

IF @KtypeLimit = 1 --部分仓库权限
BEGIN
	SET @SqlCreateTable+=' DECLARE @LimitKType As Table(TypeID INT) INSERT INTO @LimitKType SELECT WhsID FROM UF_BD_KtypeLimit(@OperatorID) '	
	SET @LimitKtypeSql = ' INNER JOIN @LimitKType kl ON kl.TypeID =bill.WhsID '
END

IF @BtypeLimit = 1 --部分往来单位权限
BEGIN
	SET @SqlCreateTable+=' DECLARE @LimitBType As Table(TypeID INT) INSERT INTO @LimitBType SELECT BtypeID FROM dbo.UF_BD_BtypeLimit(@OperatorID) '	
	SET @LimitBtypeSql = ' INNER JOIN @LimitBType B1 ON B1.TypeID =bill.BtypeID '
END

SELECT @SqlCreateTable+= ' DECLARE @GoodsTypeID INT, @WhsTypeID INT, @DeptID INT
							IF @ClassID1 <> 0
							BEGIN
								IF (@ClassType1 = 1 and @ClaseFlag1 = 1) SET @GoodsTypeID = @ClassID1
								IF (@ClassType1 = 3 and @ClaseFlag1 = 1) SET @WhsTypeID = @ClassID1
								IF @ClassType1 = 5 SET @DeptID = @ClassID1
							END
							IF @ClassID2 <> 0
							BEGIN
								IF (@ClassType2 = 1 and @ClaseFlag2 = 1) SET @GoodsTypeID = @ClassID2
								IF (@ClassType2 = 3 and @ClaseFlag2 = 1) SELECT @WhsTypeID = @ClassID2
								IF @ClassType2 = 5 SELECT @DeptID = @ClassID2
							END '

IF @BTypeID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @BType As Table(TypeID INT) INSERT INTO @BType SELECT typeid FROM dbo.UF_OT_Split_INT(@BTypeID,'','') '
	SET @SqlTable+=' INNER JOIN @BType B ON bill.BTypeID=B.TypeID '
END 
  
IF @DeptID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @DType Table(TypeID INT) INSERT INTO @DType SELECT d2.DeptID FROM BD_Dept d INNER JOIN dbo.UF_OT_Split_INT(@DeptID1,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%'''
	SET @SqlTable+=' INNER JOIN @DType D ON bill.DeptID=D.TypeID '
END	

IF @ElyID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @EType As Table(TypeID INT) INSERT INTO @EType SELECT typeid FROM dbo.UF_OT_Split_INT(@ElyID,'','') '
	SET @SqlTable+=' INNER JOIN @EType E ON bill.ElyID=E.TypeID ' 
END	

IF @CreatorID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @CreateEType As Table(TypeID INT) INSERT INTO @CreateEType SELECT typeid FROM dbo.UF_OT_Split_INT(@CreatorID,'','') '
	SET @SqlTable+=' INNER JOIN @CreateEType CE ON bill.Creator=CE.TypeID ' 
END	

IF @WhsID<>''
BEGIN
	SET @SqlCreateTable+=' DECLARE @KType As Table(TypeID INT) INSERT INTO @KType SELECT typeid FROM dbo.UF_OT_Split_INT(@WhsID,'','') '
	SET @SqlTable+=' INNER JOIN @KType W ON bill.WhsID=W.TypeID ' 
END	

IF (@VipCardNO <> '' OR @VipCardTypeID <> '' OR @VipName <> '' OR @CardHolder <> '' OR @Tel <> '')
BEGIN
	SET @SqlTable+=' INNER JOIN dbo.VS_VipCard VipCard ON bill.VipCardID=VipCard.VipCardID ' 
	IF(@VipCardNO <> '')
		SET @SqlMatch += ' AND VipCard.VipCardNO ' + CASE @VipCardNOMatch WHEN 0 THEN ' Like ''%''+@VipCardNO+''%''' ELSE ' =@VipCardNO ' END
	IF(@VipCardTypeID <> '')
	BEGIN		
		SET @SqlCreateTable+=' DECLARE @VipCardType AS TABLE(TypeID INT) INSERT INTO @VipCardType SELECT typeid FROM dbo.UF_OT_Split_INT(@VipCardTypeID,'','') '
	    SET @SqlTable+=' INNER JOIN @VipCardType VCT ON VipCard.VipCardTypeID=VCT.TypeID ' 
	END	
	IF(@VipName <> '')
		SET @SqlMatch += ' AND VipCard.VipName ' + CASE @VipNameMatch WHEN 0 THEN ' Like ''%''+@VipName+''%''' ELSE ' =@VipName ' END
	IF(@CardHolder <> '')
		SET @SqlMatch += ' AND VipCard.CardHolder ' + CASE @CardHolderMatch WHEN 0 THEN ' Like ''%''+@CardHolder+''%''' ELSE ' =@CardHolder ' END
	IF(@Tel <> '')
		SET @SqlMatch += ' AND VipCard.Tel ' + CASE @TelMatch WHEN 0 THEN ' Like ''%''+@Tel+''%''' ELSE ' =@Tel ' END
END	

IF @ClassID1 <> 0
BEGIN
	SET @SqlClass1 +=' DECLARE @CTb1 AS Table(typeid INT) INSERT INTO @CTb1(typeid) '
	SET @SqlCreateTable += CASE @ClassType1 WHEN 2 THEN CASE @ClaseFlag1 WHEN 0 THEN '' else @SqlClass1 + ' SELECT VipCardID FROM dbo.VS_VipCard WHERE VipCardTypeID = @ClassID1 ' END
											WHEN 1 THEN CASE @ClaseFlag1 WHEN 0 THEN '' else @SqlClass1 + dbo.UF_BD_GetGoodsID_Str('') END 
											WHEN 3 THEN CASE @ClaseFlag1 WHEN 0 THEN '' else @SqlClass1 + dbo.UF_BD_GetWhsID_Str(@WhsID) END
											WHEN 5 THEN @SqlClass1 + dbo.UF_BD_GetDeptID_Str() 
											else '' END
    SET @SqlTable += CASE @ClassType1 WHEN 2 THEN CASE @ClaseFlag1 WHEN 0 THEN ' AND bill.VipCardID = @ClassID1 ' else ' INNER JOIN @CTb1 C1 ON bill.VipCardID = C1.TypeID' END
									  WHEN 1 THEN CASE @ClaseFlag1 WHEN 0 THEN ' AND detail.GoodsID = @ClassID1 ' else ' INNER JOIN @CTb1 C1 on detail.GoodsID = C1.TypeID' END 
									  WHEN 3 THEN CASE @ClaseFlag1 WHEN 0 THEN ' AND bill.WhsID = @ClassID1 ' else ' INNER JOIN @CTb1 C1 on Bill.WhsID = C1.TypeID' END
									  WHEN 5 THEN ' INNER JOIN BD_Employee EE ON Bill.ElyID = EE.ElyID INNER JOIN @CTb1 C1 on EE.DeptId = C1.TypeID'
									  WHEN 6 THEN ' AND bill.ElyID = @ClassID1 '  
									  When 7 THEN ' AND bill.Creator = @ClassID1' END 	
	
END

IF @ClassID2 <> 0
BEGIN
	SET @SqlClass2 +=' DECLARE @CTb2  AS Table(typeid INT) INSERT INTO @CTb2(typeid) '
	SET @SqlCreateTable += CASE @ClassType2 WHEN 2 THEN CASE @ClaseFlag2 WHEN 0 THEN '' else @SqlClass2 + ' SELECT VipCardID FROM dbo.VS_VipCard WHERE VipCardTypeID = @ClassID2 ' END 
											WHEN 1 THEN CASE @ClaseFlag2 WHEN 0 THEN '' else @SqlClass2 + dbo.UF_BD_GetGoodsID_Str('') END 
											WHEN 3 THEN CASE @ClaseFlag2 WHEN 0 THEN '' else @SqlClass2 + dbo.UF_BD_GetWhsID_Str(@WhsID) END
											WHEN 5 THEN @SqlClass2 + dbo.UF_BD_GetDeptID_Str() 
											else '' END
    SET @SqlTable += CASE @ClassType2 WHEN 2 THEN CASE @ClaseFlag2 WHEN 0 THEN ' AND bill.VipCardID = @ClassID2 ' else ' INNER JOIN @CTb2 C2 ON bill.VipCardID = C2.TypeID' END
									  WHEN 1 THEN CASE @ClaseFlag2 WHEN 0 THEN ' AND detail.GoodsID = @ClassID2 ' else ' INNER JOIN @CTb2 C2 on detail.GoodsID = C2.TypeID' END 
									  WHEN 3 THEN CASE @ClaseFlag2 WHEN 0 THEN ' AND bill.WhsID = @ClassID2 ' else ' INNER JOIN @CTb2 C2 on Bill.WhsID = C2.TypeID' END
									  WHEN 5 THEN ' INNER JOIN BD_Employee EE ON Bill.ElyID = EE.ElyID INNER JOIN @CTb2 C2 on EE.DeptId = C2.TypeID'
									  WHEN 6 THEN ' AND bill.ElyID = @ClassID2 '  
									  When 7 THEN ' AND bill.Creator = @ClassID2' END 		
END

-- 判断单据时间类型
IF @DateType = 0
	SET @SqlDTStr = 'detail.BillDate'
IF @DateType=1
	SET @SqlDTStr = 'bill.CreateTime'	
IF @DateType=2
	SET @SqlDTStr = 'bill.PosTime'
	
IF @FullName <> '' or @UserCode <> ''
BEGIN
	IF(@FullName <> '')
		SET @GoodsMath += ' AND G.GoodsName ' + CASE @FullNameMatch WHEN 0 THEN ' Like ''%''+@FullName+''%''' ELSE ' =@FullName ' END
	IF(@UserCode <> '')
		SET @GoodsMath += ' AND G.GoodsNo ' + CASE @UserCodeMatch WHEN 0 THEN ' Like ''%''+@UserCode+''%''' ELSE ' =@UserCode ' END
	SET @GoodsTable += ' AND exists(SELECT 1 FROM BD_GOODS G Where detail.GoodsID = G.GoodsID '+@GoodsMath+')'
END

--商品条码
IF @BarCode <> ''      
BEGIN 
   SET @SqlTable += ' INNER JOIN BD_Goods_Price pri ON detail.GoodsID = pri.GoodsID and pri.UnitID = 1 '	
   SET @GoodsTable += ' AND EXISTS (SELECT 1 FROM dbo.BD_Goods_Price pri WHERE pri.GoodsID = detail.GoodsID '
   IF @BarCodeMatch = 0
	   SET @GoodsTable += N' AND pri.BarCode LIKE ''%'' + @BarCode +''%'''
   ELSE IF @BarCodeMatch = 1
	   SET @GoodsTable += N' AND pri.BarCode = @BarCode ' 
   SET @GoodsTable += ' ) '
END 

IF (@ClassType1 = 1 AND @ClaseFlag1 = 0) OR (@ClassType2 = 1 AND @ClaseFlag2 = 0)
BEGIN
	IF @Ppt1Match = 1
	BEGIN
		IF @Ppt1 <> ''
			SET @GoodsTable += ' AND exists(SELECT 1 FROM BD_Goods_Ppt1 GP1 Where detail.Ppt1ID = GP1.Ppt1ID AND GP1.Value = @Ppt1)'
		ELSE 
			SET @GoodsTable += ' AND Ppt1ID = 0 ' 	
	END
	IF @Ppt2Match = 1
	BEGIN
		IF @Ppt2 <> ''
			SET @GoodsTable += ' AND exists(SELECT 1 FROM BD_Goods_Ppt2 GP2 Where detail.Ppt2ID = GP2.Ppt2ID AND GP2.Value = @Ppt2)'
		ELSE 
			SET @GoodsTable += ' AND Ppt2ID = 0 ' 	
	END
END
	
--自定义字段汇总查询明细
IF(@GoodsDataFile1 <> '' OR @GoodsCFlag1 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG1 ON detail.GoodsID = BG1.BaseID '
	SET @SqlMatch += ' AND BG1.CustVal1 = @GoodsDataFile1 '
END
IF(@GoodsDataFile2 <> '' OR @GoodsCFlag2 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG2 ON detail.GoodsID = BG2.BaseID '
	SET @SqlMatch += ' AND BG2.CustVal2 = @GoodsDataFile2 '
END
IF(@GoodsDataFile3 <> '' OR @GoodsCFlag3 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG3 ON detail.GoodsID = BG3.BaseID '
	SET @SqlMatch += ' AND BG3.CustVal3 = @GoodsDataFile3 '
END
IF(@GoodsDataFile4 <> '' OR @GoodsCFlag4 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG4 ON detail.GoodsID = BG4.BaseID '
	SET @SqlMatch += ' AND BG4.CustVal4 = @GoodsDataFile4 '
END
IF(@GoodsDataFile5 <> '' OR @GoodsCFlag5 = 1)
BEGIN
	SET @SqlTable += ' INNER JOIN BD_Goods_CustomVal BG5 ON detail.GoodsID = BG5.BaseID '
	SET @SqlMatch += ' AND BG5.CustVal5 = @GoodsDataFile5 '
END

SET @Red = ' AND Red = 0 '

SET  @SqlIn = ' SELECT 
		SUM(detail.BSQty) AS Qty, 0 AS ExchangeQty, SUM(detail.Total) AS Total,SUM(detail.DiscTotal) AS DiscTotal,SUM(detail.GoodsCostTotal) AS GoodsCostTotal,
		(isnull(SUM(detail.DiscTotal),0)-isnull(SUM(detail.GoodsCostTotal),0)) AS Profit
		 FROM PD_SellBill bill INNER JOIN PD_SellDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 ' + @Red + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END 
		+@SqlMatch + @GoodsTable

SET  @SqlEx = ' SELECT 
		SUM(detail.BSQty) AS Qty, SUM(detail.BSQty) AS ExchangeQty, 0 AS Total,0 AS DiscTotal,SUM(detail.GoodsCostTotal) AS GoodsCostTotal,
		-SUM(detail.GoodsCostTotal) AS Profit
		 FROM dbo.PD_InOutWhsBill bill INNER JOIN dbo.PD_InOutWhsDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0   AND bill.BillTypeID = 600 ' + @Red 
		+ CASE WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END 
		+@SqlMatch + @GoodsTable
		
SELECT @SqlOut = ' SELECT 
		SUM(detail.BSQty)*-1 AS Qty, 0 AS ExchangeQty, SUM(detail.Total)*-1 AS Total,SUM(detail.DiscTotal)*-1 AS  DiscTotal,SUM(detail.GoodsCostTotal)*-1 AS GoodsCostTotal, 
		(isnull(SUM(detail.DiscTotal),0)-isnull(SUM(detail.GoodsCostTotal),0))*-1 AS Profit
		 FROM PD_SellRetBill bill INNER JOIN PD_SellRetDetail detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND  IsDraft = 0 ' + @Red + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END 
		+@SqlMatch + @GoodsTable
		
IF @isHistory=1
BEGIN
	SELECT  @SqlIn += ' 
			UNION ALL
			SELECT 
		SUM(detail.BSQty) AS Qty, 0 AS ExchangeQty, SUM(detail.Total) AS Total,SUM(detail.DiscTotal) AS DiscTotal,SUM(detail.GoodsCostTotal) AS GoodsCostTotal,
			(isnull(SUM(detail.DiscTotal),0)-isnull(SUM(detail.GoodsCostTotal),0)) AS Profit
			 FROM PD_SellBill_His bill INNER JOIN PD_SellDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
			WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 ' + @Red + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END 
			+@SqlMatch + @GoodsTable

SET  @SqlEx += ' 
			UNION ALL
			SELECT 
		SUM(detail.BSQty) AS Qty, SUM(detail.BSQty) AS ExchangeQty, 0 AS Total,0 AS DiscTotal,SUM(detail.GoodsCostTotal) AS GoodsCostTotal,
		-SUM(detail.GoodsCostTotal) AS Profit
		 FROM dbo.PD_InOutWhsBill_His bill INNER JOIN dbo.PD_InOutWhsDetail_His detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
		WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0   AND bill.BillTypeID = 600 ' + @Red 
		+ CASE WHEN @GiftFlag = 1 THEN ' AND 1<>1 ' ELSE '' END 
		+@SqlMatch + @GoodsTable
		
	SELECT @SqlOut += ' 
			UNION ALL
			SELECT 
			SUM(detail.BSQty)*-1 AS Qty, 0 AS ExchangeQty, SUM(detail.Total)*-1 AS Total,SUM(detail.DiscTotal)*-1 AS  DiscTotal,SUM(detail.GoodsCostTotal)*-1 AS GoodsCostTotal, 
			(isnull(SUM(detail.DiscTotal),0)-isnull(SUM(detail.GoodsCostTotal),0))*-1 AS Profit
			 FROM PD_SellRetBill_his bill INNER JOIN PD_SellRetDetail_his detail on bill.BillNo = detail.BillNo '+@SqlTable+@LimitKtypeSql + @LimitBtypeSql+'
			WHERE ' + @SqlDTStr + ' BETWEEN @BeginDate AND @EndDate AND IsDraft = 0 ' + @Red + CASE @GiftFlag WHEN 1 THEN ' AND Gift=1 ' WHEN 2 THEN ' AND Gift=0 ' ELSE '' END 
			+@SqlMatch + @GoodsTable
END
	
IF (@SaleBill = 1)  
BEGIN  
 IF(@SaleBackBill = 1 OR @ExchangeBill = 1)  
  SET @Sql += @SqlIn+ ' UNION ALL ' ;  
 ELSE  
  SET @Sql += @SqlIn ;  
END  
IF (@SaleBackBill = 1)  
 SET @Sql += @SqlOut;
   
IF (@ExchangeBill = 1)  
BEGIN
	IF (@SaleBackBill = 1) 
	  SELECT @Sql += ' UNION ALL ' ; 
 SELECT @Sql += @SqlEx;  
END

SELECT @sql= @SqlCreateTable +'
;WITH Bill AS 
('	+@sql+'
)'
SELECT @Sql += ' SELECT SUM(Qty) AS BSQty, SUM(total) AS Total,SUM(DiscTotal) AS DiscTotal,SUM(GoodsCostTotal) AS GoodsCostTotal,SUM(Profit) AS Profit
	 FROM  Bill ' --, SUM(ExchangeQty) AS ExchangeQty
	 
IF @sql IS NULL OR @sql=''
BEGIN
	SELECT TOP 0 0 FROM PD_BillType
	RETURN 
END

IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
exec sp_executesql @Sql,N'@DateType INT,@BeginDate DateTime,@EndDate DateTime,@OperatorID INT,@ClassID1 INT,@ClassType1 INT,@ClaseFlag1 INT,@ClassID2 INT,@ClassType2 INT,@ClaseFlag2 INT,@BTypeID VARCHAR(MAX),@DeptID1 VARCHAR(MAX),@ElyID VARCHAR(MAX),@CreatorID VARCHAR(MAX),@WhsID VARCHAR(MAX),@FullName VARCHAR(100),@UserCode VARCHAR(100), @BarCode VARCHAR(100), @BarCodeMatch INT,@GoodsDataFile1 VARCHAR(100),@GoodsDataFile2 VARCHAR(100),@GoodsDataFile3 VARCHAR(100),@GoodsDataFile4 VARCHAR(100),@GoodsDataFile5 VARCHAR(100), @Ppt1 VARCHAR(100), @Ppt2 VARCHAR(100),@VipCardNO  VARCHAR(25), @VipCardTypeID VARCHAR(MAX), @VipName VARCHAR(50), @CardHolder VARCHAR(50), @Tel VARCHAR(20)',@DateType,@BeginDate,@EndDate,@OperatorID,@ClassID1,@ClassType1,@ClaseFlag1,@ClassID2,@ClassType2,@ClaseFlag2,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@FullName,@UserCode,@BarCode,@BarCodeMatch,@GoodsDataFile1,@GoodsDataFile2 ,@GoodsDataFile3 ,@GoodsDataFile4 ,@GoodsDataFile5,@Ppt1,@Ppt2, @VipCardNO, @VipCardTypeID, @VipName, @CardHolder, @Tel
GO




/****** Object:  StoredProcedure [UP_PD_SaleSummaryListSum]    Script Date: 06/23/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_PD_VipConsumSummaryListSum]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_PD_VipConsumSummaryListSum]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：HLIN
	日期：2015-12-25
	描述：会员消费统计合计
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_VipConsumSummaryListSum]
(			   
	@BillDateType INT=1,			--单据日期类型:1=录单日期,2=制单日期,3=过账日期  对应BillDate,CreateTime,PosTime
	@BillStartDate DATETIME,		--单据开始日期
	@BillEndDate DATETIME,			--单据结束日期
	@SaleBillOut INT=1,				--销售出库单勾选状态
	@SaleBillIn INT=1,				--销售退货单勾选状态
	@ExchangeBill INT=1,			--积分兑换单勾选状态
	@VipCardNo VARCHAR(30) = '',   
	@VipCardMatch INT = 0,          
	@VipCardTypeID VARCHAR(1000) = '',
	@VipName VARCHAR(50) = '',   
	@VipNameMatch INT = 0,       
	@CardHolder VARCHAR(50) = '',   
	@CardHolderMatch INT = 0,       
	@Tel VARCHAR(20) = '',   
	@TelMatch INT = 0,       
	@BTypeID VARCHAR(1000) = '',		--部门
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@CreatorID VARCHAR(1000)='',    --制单人
	@WhsID VARCHAR(1000) = '',		--仓库
	@GoodsID VARCHAR(1000) = '',	--商品
	@GoodsNoMatch INT=0,			--商品编号配置模式:0=包含,1=等于
	@GoodsNo VARCHAR(20) = '',		--商品编号
	@GoodsNameMatch INT=0,			--商品名称配置模式:0=包含,1=等于
	@GoodsName VARCHAR(50) = '',	--商品名称
	@BarCode VARCHAR(100) = '',      --条码
	@BarCodeMatch INT = 0,          --条码匹配方式 0:包含 1:等于
	@GiftState INT=9,				--赠品状态：9=全部,1=是,0=否
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)
AS
SET NOCOUNT ON
BEGIN
	-- 当日期类型为业务日期的场合，做归档日期的范围判断
	IF @BillDateType = 1
	BEGIN
		DECLARE @Re INT 
		EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
		IF( @Re=1 )RETURN @Re;
	END

DECLARE @Sql NVARCHAR(MAX)='',@SqlDTStr VARCHAR(20)=''
	,@SumData NVARCHAR(MAX),@VbSumHead VARCHAR(50)='',@SumHead NVARCHAR(MAX),@SumHeadFH NVARCHAR(MAX),@SumJoin NVARCHAR(MAX)='',@SumParam NVARCHAR(MAX)
	,@Sql_PPB NVARCHAR(MAX),@Sql_PPB_His NVARCHAR(MAX),@Sql_PRB NVARCHAR(MAX),@Sql_PRB_His NVARCHAR(MAX)
	,@VbBDHead VARCHAR(500)='',@BDHead VARCHAR(200),@VbSumBDHead VARCHAR(200)='',@VbBDJoin VARCHAR(400)='',@CFBDJoin NVARCHAR(MAX)=''
	,@Profit VARCHAR(100)
	,@BtypeLimit INT=0,@KtypeLimit INT=0 
	,@Sql_Exchange NVARCHAR(MAX),@Sql_Exchange_His NVARCHAR(MAX),@SumHeadEX NVARCHAR(max),@VipTableStr NVARCHAR(max)
--INNER JOIN BEGIN
IF @BTypeID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@BTypeID, '','') _BType ON _BType.typeid = p.BTypeID '
IF @DeptID <> ''
BEGIN
	SET @SumJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=p.DeptID '
END
IF @ElyID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = p.ElyID '
IF @CreatorID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@CreatorID, '','') _PEly ON _PEly.typeid = p.Creator '
IF @WhsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@WhsID, '','') _Whs ON _Whs.typeid = p.WhsID '
/*权限使用公用方法*/
--往来单位权限
SELECT @BtypeLimit = dbo.UF_BD_IsAllBtypeLimit(@OperatorID) 
IF @BtypeLimit = 1  --部份权限
	SET @SumJoin += '
	INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) rBtype ON rBtype.BTypeID=p.BTypeID '
--仓库权限
SELECT @KtypeLimit = dbo.UF_BD_IsAllKtypeLimit(@OperatorID) 
IF( @KtypeLimit = 1 ) --部份权限
	SET @SumJoin += '
	INNER JOIN UF_BD_KtypeLimit(@OperatorID) rWhs ON rWhs.WhsID=p.WhsID '
IF @GoodsID <> ''
	SET @SumJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@GoodsID, '','') _goods ON _goods.typeid=dtl.GoodsID '
IF @GoodsNo <> '' OR @GoodsName <> '' 
	SET @SumJoin +='
	INNER JOIN BD_Goods g ON g.GoodsID=dtl.GoodsID '
IF @BarCode <> ''
BEGIN 
	SET @SumJoin += ' INNER JOIN BD_Goods_Price pri ON pri.GoodsID = dtl.GoodsID and pri.UnitID = 1 '
END 
--INNER JOIN END

IF @VipCardNo<>'' OR @VipCardTypeID<> '' OR @VipName <>'' OR  @CardHolder<>'' OR @Tel<>''       
  SET @SumJoin += ' 
  INNER JOIN Vs_VipCard V ON V.VipCardID = p.VipCardID '
IF @VipCardTypeID<> ''
	SET @SumJoin += ' 
	INNER JOIN Vs_VipCardType Vt ON V.VipCardTypeID = vt.VipCardTypeID
	INNER JOIN dbo.UF_OT_Split_Int(@VipCardTypeID, '','') vtype ON vtype.typeid=vt.VipCardTypeID  '
--INNER JOIN END

--条件BEGIN
IF @BillDateType=1
	SET @SqlDTStr='dtl.BillDate'
IF @BillDateType=2
	SET @SqlDTStr='p.CreateTime'	
IF @BillDateType=3
	SET @SqlDTStr='p.PosTime'	
SET @SumParam = '
	WHERE '+@SqlDTStr+' BETWEEN @BillStartDate AND @BillEndDate AND p.IsDraft=0 AND p.Red=0 AND p.VipCardID<>0 '
	
IF @GoodsNo <> ''
BEGIN
	IF @GoodsNoMatch=0 SET @SumParam += 'AND g.GoodsNo LIKE ''%''+@GoodsNo+''%'' '  
	IF @GoodsNoMatch=1 SET @SumParam += 'AND g.GoodsNo=@GoodsNo '  
END
IF @GoodsName <> ''
BEGIN
	IF @GoodsNameMatch=0 SET @SumParam += 'AND g.GoodsName LIKE ''%''+@GoodsName+''%'' '  
	IF @GoodsNameMatch=1 SET @SumParam += 'AND g.GoodsName=@GoodsName '  
END

--商品条码
IF @BarCode <> ''      
BEGIN 
	IF @BarCodeMatch = 0
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode like ''%'' + @BarCode +''%'' AND u2.GoodsID=dtl.GoodsID) '
	ELSE IF @BarCodeMatch = 1 
	   SET @SumParam += N' AND Exists(SELECT 1 FROM BD_Goods_Price u2 WHERE u2.BarCode = @BarCode AND u2.GoodsID=dtl.GoodsID)'
END

IF @VipCardNo<>''
BEGIN
	IF @VipCardMatch=0 SET @SumParam += 'AND v.VipCardNO LIKE ''%''+@VipCardNO+''%'' '  
	IF @VipCardMatch=1 SET @SumParam += 'AND v.VipCardNO=@VipCardNO ' 
END
IF @VipName<>''
BEGIN
	IF @VipNameMatch=0 SET @SumParam += 'AND v.VipName LIKE ''%''+@VipName+''%'' '  
	IF @VipNameMatch=1 SET @SumParam += 'AND v.VipName=@VipName ' 
END
IF @CardHolder<>''
BEGIN
	IF @CardHolderMatch=0 SET @SumParam += 'AND v.CardHolder LIKE ''%''+@CardHolder+''%'' '  
	IF @CardHolderMatch=1 SET @SumParam += 'AND v.CardHolder=@CardHolder ' 
END
IF @Tel<>''
BEGIN
	IF @TelMatch=0 SET @SumParam += 'AND v.Tel LIKE ''%''+@Tel+''%'' '  
	IF @TelMatch=1 SET @SumParam += 'AND v.Tel=@Tel ' 
END
  
 
--条件END

SET @SumData=';WITH SumData AS('

SET @SumHead='SUM(dtl.BSQty)[BSQtyST]
	,SUM(dtl.TaxTotal)[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)[GiftQtyST] 
	,0 ExchangeQty '
SET @SumHeadFH='SUM(dtl.BSQty)*-1[BSQtyST]
	,SUM(dtl.TaxTotal)*-1[SaleTotalST]
	,SUM(dtl.GoodsCostTotal)*-1[CostTotalST]
	,SUM(CASE WHEN dtl.Gift=1 THEN dtl.BSQty ELSE 0 END)*-1[GiftQtyST]
	,0 ExchangeQty '
SET @SumHeadEX='SUM(dtl.BSQty) [BSQtyST]
	,0 [SaleTotalST]
	,SUM(dtl.GoodsCostTotal) [CostTotalST]
	,0 [GiftQtyST] 
	,SUM(dtl.BSQty) ExchangeQty '

SET @Sql_Exchange='
	SELECT ' + @SumHeadEX + @VbSumHead + '
	FROM PD_InoutWhsBill p 
	INNER JOIN PD_InoutWhsDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam +CASE WHEN @GiftState<>1 THEN '' ELSE ' AND 1<>1' END 
SET @Sql_Exchange_His='
	SELECT ' + @SumHeadEX + @VbSumHead + '
	FROM PD_InoutWhsBill_His p 
	INNER JOIN PD_InoutWhsDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam +CASE WHEN @GiftState<>1 THEN '' ELSE ' AND 1<>1' END 

IF @GiftState<>9 
	SET @SumParam += 'AND Gift=@GiftState '	
	
IF NOT((@SaleBillOut<>0 OR @ExchangeBill<>0) AND @SaleBillIn<>0)
	SET @SumHeadFH = @SumHead
	
SET @Sql_PPB='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill p 
	INNER JOIN PD_SellDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam 
SET @Sql_PPB_His='
	SELECT ' + @SumHead + @VbSumHead + '
	FROM PD_SellBill_His p 
	INNER JOIN PD_SellDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam 
SET @Sql_PRB='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill p 
	INNER JOIN PD_SellRetDetail dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam 
SET @Sql_PRB_His='
	SELECT ' + @SumHeadFH + @VbSumHead + '
	FROM PD_SellRetBill_His p 
	INNER JOIN PD_SellRetDetail_His dtl ON p.BillNo=dtl.BillNo ' + @SumJoin + @SumParam 



IF @SaleBillOut<>0
BEGIN
	SET @SumData+=@Sql_PPB+'
	UNION ALL '
END
IF @SaleBillIn<>0
BEGIN
	SET @SumData+=@Sql_PRB++'
	UNION ALL '
END
IF @ExchangeBill<>0
BEGIN
	SET @SumData+=@Sql_Exchange+'
	UNION ALL '
END

IF @IsHistory = 1
BEGIN
	IF @SaleBillOut<>0
	BEGIN
		SET @SumData+=@Sql_PRB_His+'
		UNION ALL '
	END
	IF @SaleBillIn<>0
	BEGIN
		SET @SumData+=@Sql_PPB_His+'
		UNION ALL '
	END
	IF @ExchangeBill<>0
	BEGIN
		SET @SumData+=@Sql_Exchange_His+'
		UNION ALL '
	END
END

SET @SumData=SUBSTRING(@SumData,0,LEN(@SumData)-11)
SET @SumData+=')'


SET @Sql += 'SET NOCOUNT ON;
' + @SumData + '
, PageData as (select [BSQtyST] as BSQTY,SaleTotalST as SaleToTal,CostTotalST as CostTotal,GiftQtyST as GiftQty,[SaleTotalST]-[CostTotalST] [Profit],ExchangeQty from SumData )
   select Sum(BSQTY) as BSQty,Sum(SaleToTal) as SaleTotal ,Sum(CostTotal) as CostTotal,Sum(Profit) as Profit, SUM(GiftQty) as GiftQty, SUM(ExchangeQty) as ExchangeQty  from PageData
 '
IF @BtypeLimit = 0 OR @KtypeLimit = 0 SET @Sql = N' SELECT * FROM BD_Area WHERE 1 <> 1'
print @Sql
--DECLARE @curPos INT = 1 , @count INT = 1
--WHILE (@curPos < len(@Sql))
--BEGIN
--	PRINT substring(@Sql, @curPos, @curPos + 3999)
--	SET @curPos += 3999 + 1
--	SET @count += 1
--END 

EXEC SP_EXECUTESQL @Sql,N'@BillDateType INT,@BillStartDate DATETIME,@BillEndDate DATETIME
,@BTypeID VARCHAR(1000),@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@CreatorID VARCHAR(1000),@WhsID VARCHAR(1000),@GoodsID VARCHAR(1000)
,@GoodsNo VARCHAR(20),@GoodsName VARCHAR(50),@GiftState INT
,@OperatorID INT, @BarCode VARCHAR(100), @BarCodeMatch INT
,@VipCardNo VARCHAR(30), @VipCardMatch INT,@VipCardTypeID VARCHAR(1000),@VipName VARCHAR(50), @VipNameMatch INT,@CardHolder VARCHAR(50)
,@CardHolderMatch INT,  @Tel VARCHAR(20),   @TelMatch INT '
,@BillDateType,@BillStartDate,@BillEndDate
,@BTypeID,@DeptID,@ElyID,@CreatorID,@WhsID,@GoodsID,@GoodsNo,@GoodsName,@GiftState
,@OperatorID, @BarCode, @BarCodeMatch
,@VipCardNo,@VipCardMatch ,@VipCardTypeID,@VipName ,@VipNameMatch,@CardHolder 
,@CardHolderMatch ,@Tel ,@TelMatch   
END



GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_PD_WaitSignList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE UP_PD_WaitSignList
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------
    作者：李文博
	日期：2015-06-03
	描述：我的待签收
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_WaitSignList]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@BeginDate DATE,
	@EndDate DATE,
	@BillTypeID VARCHAR(MAX)='',
	@BTypeID VARCHAR(MAX)='',
	@WhsID VARCHAR(MAX) = '',
	@DeptID VARCHAR(MAX)='',
	@ElyID VARCHAR(MAX)='',
	@CreatorID VARCHAR(MAX)='',
	@BillCode VARCHAR(50) = '',
	@BillCodeMatch BIT = 0,
	@Summary VARCHAR(256)='',
	@SummaryMatch BIT = 0,
	@Description VARCHAR(100)='',
	@DescriptionMatch BIT = 0,
	@OperatorID INT = 1
) 
AS

DECLARE @Sql NVARCHAR(MAX) = '', @IndexSql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = ''
DECLARE @TableSql NVARCHAR(MAX) = '', @BillTypeSql NVARCHAR(MAX) = '', @ARAPBill NVARCHAR(MAX) = ''
DECLARE @BtypeSql NVARCHAR(MAX) = '', @KtypeSql NVARCHAR(MAX) = '', @MulKtypeSql NVARCHAR(MAX) = ''
DECLARE @NoKBSql NVARCHAR(MAX) = '', @NKtypeIndexSql NVARCHAR(MAX) = '', @NBtypeIndexSql NVARCHAR(MAX) = ''

DECLARE @PchBill NVARCHAR(MAX) = '', @PchOrderBill NVARCHAR(MAX) = '', @PchRetBill NVARCHAR(MAX) = ''
DECLARE @SellBill NVARCHAR(MAX) = '', @SellOrderBill NVARCHAR(MAX) = '', @SellRetBill NVARCHAR(MAX) = ''
DECLARE @AllotReqBill NVARCHAR(MAX) = '', @AllotBill NVARCHAR(MAX) = '', @AdjPriceBill NVARCHAR(MAX) = ''
DECLARE @InOutWhsBill NVARCHAR(MAX) = '', @AssemblyBill NVARCHAR(MAX) = '', @LossSpillBill NVARCHAR(MAX) = ''
DECLARE @PayRecBill NVARCHAR(MAX) = '', @FeeRecBill NVARCHAR(MAX) = '', @TransferBill NVARCHAR(MAX) = ''
DECLARE @VipChargeBill NVARCHAR(MAX) = ''

--单据日期条件
SET @IndexSql = ' WHERE I.BillDate BETWEEN @BeginDate AND @EndDate '


IF @BillTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @BillType Table(BillTypeID INT)   
     INSERT  INTO @BillType SELECT typeid AS BillTypeID  FROM dbo.UF_OT_Split_Int(@BillTypeID,'','')   
     '  
	SET @BillTypeSql+=' INNER JOIN @BillType BT ON PR.BillTypeID=BT.BillTypeID '   
END

IF @DeptID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @DType Table(DeptID INT)   
     INSERT  INTO @DType SELECT d2.DeptID FROM BD_Dept d   
     INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID   
     INNER JOIN BD_Dept d2 ON d2.Path like d.Path+''%''  
     WHERE d2.SonNum = 0  
     '  
	SET @TableSql+=' INNER JOIN @DType D ON I.DeptID=D.DeptID '  
END

IF @ElyID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @EType Table(ElyID INT)   
     INSERT  INTO @EType SELECT typeid AS ElyID  FROM dbo.UF_OT_Split_Int(@ElyID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @EType E ON I.ElyID=E.ElyID '      
END

IF @CreatorID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @Creator Table(CreatorID INT)   
     INSERT  INTO @Creator SELECT typeid AS CreatorID  FROM dbo.UF_OT_Split_Int(@CreatorID,'','')   
     '  
	SET @TableSql+=' INNER JOIN @Creator C ON I.Creator = C.CreatorID '      
END

SET @NoKBSql = @TableSql

IF @BTypeID <> ''
BEGIN
	 SET @CreateTableSql += ' DECLARE @BType Table(BTypeID INT)   
     INSERT  INTO @BType SELECT typeid AS BTypeID  FROM dbo.UF_OT_Split_Int(@BTypeID,'','')   
     '
     SET @BtypeSql += ' INNER JOIN @BType B ON I.BTypeID=B.BTypeID '
     SET @TableSql += @BtypeSql
     SET @NBtypeIndexSql = ' AND 1=2 '
END

IF @WhsID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @Whs Table(WhsID INT)   
     INSERT  INTO @Whs SELECT typeid AS WhsID  FROM dbo.UF_OT_Split_Int(@WhsID,'','')   
     '
     SET @KtypeSql += ' INNER JOIN @Whs K ON I.WhsID=K.WhsID '
     SET @MulKtypeSql += ' INNER JOIN @Whs K ON (I.InWhsID=K.WhsID OR I.OutWhsID = K.WhsID)'
     SET @TableSql += @KtypeSql
     SET @NKtypeIndexSql = ' AND 1=2 '
END


IF @BillCode <> ''
BEGIN
	IF @BillCodeMatch = 1 
		SET @IndexSql += ' AND BillCode = @BillCode '
	ELSE
		SET @IndexSql += ' AND BillCode Like ''%''+@BillCode+''%'' ' 
END

IF @Summary <> ''
BEGIN
	IF @SummaryMatch = 1 
		SET @IndexSql += ' AND Summary = @Summary '
	ELSE
		SET @IndexSql += ' AND Summary Like ''%''+@Summary+''%'' ' 
END
IF @Description <> ''
BEGIN
	IF @DescriptionMatch = 1 
		SET @IndexSql += ' AND Description = @Description '
	ELSE
		SET @IndexSql += ' AND Description Like ''%''+@Description+''%'' ' 
END

--采购订单
SET @PchOrderBill = '
SELECT	100 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		''无需过账'' AS PostStatus
FROM PD_PchOrdBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 100
'+ @TableSql +@IndexSql+ 'AND I.AuditStatus = 4 AND AB.SignStatus = 0 '  

--采购入库单
SET @PchBill = '
SELECT	101 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_PchBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 101
'+ @TableSql +@IndexSql + ' AND I.AuditStatus = 4 AND AB.SignStatus = 0 '

--采购退货单
SET @PchRetBill = '
SELECT	102 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_PchRetBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 102
'+ @TableSql +@IndexSql + ' AND I.AuditStatus = 4 AND AB.SignStatus = 0 '


--销售订单
SET @SellOrderBill = '
SELECT	200 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		''无需过账'' AS PostStatus
FROM PD_SellOrdBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 200
'+ @TableSql +@IndexSql+ 'AND I.AuditStatus = 4 AND AB.SignStatus = 0'  

--销售出库单
SET @SellBill = '
SELECT	201 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_SellBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 201
'+ @TableSql +@IndexSql + ' AND I.AuditStatus = 4 AND AB.SignStatus = 0'

--销售退货单
SET @SellRetBill = '
SELECT	202 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_SellRetBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 202
'+ @TableSql +@IndexSql + ' AND I.AuditStatus = 4 AND AB.SignStatus = 0'

--调拨申请单
SET @AllotReqBill = '
SELECT	308 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		''无需过账'' AS PostStatus
FROM PD_AllotReqBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 308
'+ @NoKBSql + @MulKtypeSql +@IndexSql+ @NBtypeIndexSql + 'AND I.AuditStatus = 4 AND AB.SignStatus = 0' 

--同价/变价调拨单
SET @AllotBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,		I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_AllotBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND I.BillTypeID = ab.BillTypeID 
'+ @NoKBSql + @MulKtypeSql +@IndexSql+ @NBtypeIndexSql + 'AND I.AuditStatus = 4 AND AB.SignStatus = 0' 


--调价单
SET @AdjPriceBill = '
SELECT	302 AS BillTypeID,	BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,	I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_AdjPriceBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 302
'+ @NoKBSql + @KtypeSql +@IndexSql + @NBtypeIndexSql + ' AND I.AuditStatus = 4 AND AB.SignStatus = 0'


--其他出/入库单
SET @InOutWhsBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,				I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_InOutWhsBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND I.BillTypeID = AB.BillTypeID 
'+ @TableSql +@IndexSql+ 'AND I.AuditStatus = 4 AND AB.SignStatus = 0' 


--生产拆装单
SET @AssemblyBill = '
SELECT	310 AS BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,			I.DeptID,		I.ElyID,	I.BillNo,			CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_AssemblyBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 310
'+  @NoKBSql + @MulKtypeSql +@IndexSql+ @NBtypeIndexSql +'AND I.AuditStatus = 4 AND AB.SignStatus = 0'

--报损报溢单
SET @LossSpillBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,		I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM PD_LossSpillBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND I.BillTypeID = AB.BillTypeID 
'+ @NoKBSql + @KtypeSql +@IndexSql+ @NBtypeIndexSql + 'AND I.AuditStatus = 4 AND AB.SignStatus = 0' 

--收付款单
SET @PayRecBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,		I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM MF_PayRecBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND I.BillTypeID = AB.BillTypeID 
'+ @NoKBSql + @BtypeSql +@IndexSql+ @NKtypeIndexSql + 'AND I.AuditStatus = 4 AND AB.SignStatus = 0' 


--现金费用单,一般费用单,其他收入单
SET @FeeRecBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,		I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM MF_FeeRecBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND I.BillTypeID = AB.BillTypeID 
'+ @NoKBSql + @BtypeSql +@IndexSql+ @NKtypeIndexSql +'AND I.AuditStatus = 4 AND AB.SignStatus = 0' 

--转款单
SET @TransferBill = '
SELECT	406 AS BillTypeID,		BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,		I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM MF_TransferBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 406
'+ @NoKBSql +@IndexSql + @NKtypeIndexSql + @NBtypeIndexSql + ' AND I.AuditStatus = 4 AND AB.SignStatus = 0'

--应收应付
SET @ARAPBill = '
SELECT	I.BillTypeID,			BillCode,		BillDate,	Summary,			Description,	
		I.BTypeID,		I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM MF_ARAPBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND I.BillTypeID = AB.BillTypeID 
'+ @NoKBSql + @BtypeSql +@IndexSql+ @NKtypeIndexSql + 'AND I.AuditStatus = 4 AND AB.SignStatus = 0' 

--会员充值单
SET @VipChargeBill = '
SELECT	602 AS BillTypeID,		BillCode,		BillDate,	Summary,			Description,	
		'''' AS BTypeID,		I.DeptID,		I.ElyID,	I.BillNo,		    CreateTime,
		''审核通过'' AS AuditStatus,		CASE SignElyID WHEN 999999 THEN Creator ELSE SignElyID END AS SignElyID,
		CASE IsDraft WHEN 0 THEN ''已过账'' WHEN 1 THEN ''未过账'' END AS PostStatus 
FROM VS_VipChargeBill I INNER JOIN PD_AuditingBill AB ON I.BillNo = AB.BillNo AND AB.BillTypeID = 602
'+ @NoKBSql +@IndexSql + @NKtypeIndexSql + @NBtypeIndexSql + ' AND I.AuditStatus = 4 AND AB.SignStatus = 0'

SET @Sql = @CreateTableSql+'
;WITH PagingData AS 
(
SELECT	PR.BillTypeID,	PBT.BillName,	PR.BillCode,	BillDate,		Summary,		Description,	
		PR.BTypeID,		B.BTypeCode,	B.BTypeName,	PR.DeptID,		D.DeptCode,		D.DeptName,		
		PR.ElyID,		E.ElyCode,		E.ElyName,		BillNo,			CreateTime,		AuditStatus,
		PR.SignElyID,   BE.ElyCode AS SignElyCode,		BE.ElyName AS SignElyName,		PostStatus
	FROM(
	'+ @PchBill+'
	UNION ALL
	'+ @PchOrderBill+'
	UNION ALL
	'+@PchRetBill+'
	UNION ALL
	'+@SellBill+'
	UNION ALL
	'+@SellOrderBill+'
	UNION ALL
	'+@SellRetBill+'
	UNION ALL
	'+@AllotReqBill+'
	UNION ALL
	'+@AllotBill+'
	UNION ALL
	'+@AdjPriceBill+'
	UNION ALL
	'+@InOutWhsBill+'
	UNION ALL
	'+@AssemblyBill+'
	UNION ALL
	'+@LossSpillBill+'
	UNION ALL
	'+@PayRecBill+'
	UNION ALL
	'+@FeeRecBill+'
	UNION ALL
	'+@TransferBill+'
	UNION ALL
	'+@VipChargeBill+'
	UNION ALL
	'+@ARAPBill+'
	) PR
	LEFT JOIN BD_Btype B ON PR.BTypeID = B.BTypeID
	LEFT JOIN BD_Employee E ON PR.ElyID = E.ElyID
	LEFT JOIN BD_Employee BE ON PR.SignElyID = BE.ElyID
	LEFT JOIN BD_Dept D ON PR.DeptID = D.DeptID
	INNER JOIN PD_BillType PBT ON PR.BillTypeID = PBT.BillTypeID
	'+ @BillTypeSql + '
WHERE SignElyID = @OperatorID)'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate','DATE', @BeginDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate','DATE', @EndDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillTypeID','VARCHAR(MAX)',@BillTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BTypeID','VARCHAR(MAX)',@BTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@WhsID','VARCHAR(MAX)',@WhsID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@DeptID','VARCHAR(MAX)',@DeptID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@ElyID','VARCHAR(MAX)',@ElyID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@CreatorID','VARCHAR(MAX)',@CreatorID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BillCode','VARCHAR(50)',@BillCode)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Summary','VARCHAR(256)',@Summary)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Description','VARCHAR(100)',@Description)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize, 'CreateTime','','ROWID ASC',1,1



GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：leiyang
	日期：2014-6-15
	描述：单据往来对账查询
-------------------------------------------*/
CREATE PROCEDURE [UP_PD_WLDZBeforeBalance]
(
	@BeginDate DATE,
	@BTypeID Int=0,
	@isHistory INT=1				--是否包含历史数据	
)
	
AS
SET NOCOUNT ON

DECLARE @re int 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@isHistory
if( @re=1 )return @re;

declare @period int
declare @StartDate Date
DECLARE @sql nvarchar(MAX)='',@sqlListTable varchar(max)=''

select @period = isnull(MAX(Period),0) from SS_MonthProc where EndDate < @BeginDate and EndDate is not null
if (@period = 0)
begin
	select @sql = 'Declare @total float=0
				select @total=Case when sum(JTotal)-sum(DTotal) IS Not null then sum(JTotal)-sum(DTotal) else 0 end  
				from (select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal from PD_ListTable  where FinanceID in(33,37) And BtypeID = @BTypeID And BillDate < @BeginDate
						union all
					select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal from PD_ListTable_His  where FinanceID in(33,37) And BtypeID = @BTypeID  And BillDate < @BeginDate)
						 L 
				select @total=isnull(SUM(QcAR),0)-isnull(SUM(QcAP),0) + @total from BD_ARAP Where BtypeID = @BTypeID
				select CAST(@total as numeric(20,8)) as total
				'
end
else
Begin
	select @StartDate = EndDate from SS_MonthProc where Period = @period
	select @sql = 'Declare @total float=0
				select @total=Case when sum(JTotal)-sum(DTotal) IS Not null then sum(JTotal)-sum(DTotal) else 0 end  
				from (select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal from PD_ListTable  where FinanceID in(33,37) And BtypeID = @BTypeID And BillDate >@StartDate  And BillDate < @BeginDate
						union all
					select BillNo,BillTypeID,BillDate,FinanceID,BtypeID,isnull(JTotal,0) as JTotal,isnull(DTotal,0) as DTotal from PD_ListTable_His  where FinanceID in(33,37) And BtypeID = @BTypeID And BillDate >@StartDate  And BillDate < @BeginDate)
						 L 
				select @total= isnull(total,0) + @total from SS_MonthArAp Where BtypeID = @BTypeID and period = @period
				select CAST(@total as numeric(20,8)) as total
				'
End

 --print @sql
exec sp_executesql @sql,N'@BeginDate Date,@BTypeID VarChar(MAX),@period int,@StartDate Date',@BeginDate,@BTypeID,@period,@StartDate

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：hanlin
	日期：2015-5-29
	描述：单据审核查询
-------------------------------------------*/
CREATE PROCEDURE [UP_SS_AuditSetDetailQuery]
(
	@SetID INT
)

AS
SET NOCOUNT ON

SELECT  ID,
		ProjectCode,
		ProjectName,
		BillTypeID,
		IfUse,
		Range,
		CASE s.DeptID WHEN '' THEN '-1' ELSE s.DeptID END AS DeptID,
		CASE s.DeptID WHEN '' THEN '全部' 
				ELSE STUFF((
					SELECT ','+DeptName 
					FROM BD_Dept d 
					WHERE EXISTS(SELECT 1 FROM dbo.UF_OT_Split_Int(s.DeptID,',')a WHERE a.Typeid= d.DeptID)  ORDER BY DeptCode FOR XML PATH('')
				),1,1,'') END AS DeptName,
		SignElyID,
		CASE SignElyID WHEN 999999 THEN '制单人' ELSE  e1.ElyName END AS SignElyName,
		SpecElyID,
		e2.ElyName AS SpecElyName
FROM dbo.SS_AuditSet s
LEFT JOIN dbo.BD_Employee e1 ON e1.ElyID=s.SignElyID
LEFT JOIN dbo.BD_Employee e2 ON e2.ElyID=s.SpecElyID
WHERE id=@SetID


SELECT  ID,
		Level,
		Type,
		StepName,
		AuditType,
		'√' AS IsSet,
		ElyID,
		CASE ElyID WHEN '' THEN '' 
				ELSE STUFF((
					SELECT ','+ElyName 
					FROM dbo.BD_Employee e 
					WHERE EXISTS(SELECT 1 FROM dbo.UF_OT_Split_Int(s.ElyID,',')a WHERE a.Typeid= e.ElyID)  ORDER BY ElyCode FOR XML PATH('')
				),1,1,'') END AS ElyName
FROM dbo.SS_AuditSetDetail s
WHERE SetID=@SetID
ORDER BY Level,Sort

SELECT	SetDID,
		ItemsID,
		Value
FROM dbo.SS_AuditStepReason s
WHERE EXISTS(SELECT 1 FROM dbo.SS_AuditSetDetail WHERE SetID=@SetID AND ID=s.SetDID)
ORDER BY ItemsID

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：hanlin
	日期：2015-5-29
	描述：单据审核查询
-------------------------------------------*/
CREATE PROCEDURE [UP_SS_AuditSetQuery]
(
	@PageNo INT,
	@PageSize INT,
	@BillTypeID INT
)

AS
SET NOCOUNT ON
	;WITH PagingData AS
	(
		SELECT  s.ID,
				BillTypeID ,
				CreateDate,
				ModifyDate,
				ProjectName ,
				ProjectCode ,
				CASE IfUse WHEN 0 THEN '否' ELSE '是' END IfUse,
				CASE s.DeptID WHEN '' THEN '全部' 
				ELSE STUFF((
					SELECT ','+DeptName 
					FROM BD_Dept d 
					WHERE EXISTS(SELECT 1 FROM dbo.UF_OT_Split_Int(s.DeptID,',')a WHERE a.Typeid= d.DeptID)  ORDER BY DeptCode FOR XML PATH('')
				),1,1,'') END AS DeptName,
				CASE SignElyID WHEN 999999 THEN '制单人' ELSE  e.ElyName END AS SignElyName
		FROM dbo.SS_AuditSet s
		LEFT JOIN dbo.BD_Employee e ON s.SignElyID = e.ElyID
		WHERE BillTypeID=@billTypeID
	)
   SELECT * FROM (SELECT COUNT(1) AS 'ROWCOUNT' FROM PagingData) A
   CROSS JOIN
   (
	SELECT	ROW_NUMBER() OVER( ORDER BY  ProjectCode) AS ROWID,
	*
	FROM PagingData
   ) B
   WHERE B.ROWID>(@PageNo-1)*@PageSize
	AND B.ROWID<=@PageNo*@PageSize


GO



IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_SS_MacAddrList]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_SS_MacAddrList]
GO
/****** Object:  StoredProcedure [UP_SS_MacAddrList]    Script Date: 01/29/2015 14:20:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2015/1/29
-- Description:	 MAC地址列表
-- =============================================
CREATE PROCEDURE [UP_SS_MacAddrList](
     @PageNo INT = 0,
     @PageSize INT = 0,
     @SearchStr VARCHAR(4000) = ''
   ) 
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @Sql NVARCHAR(MAX)
	SET @Sql = ';WITH PagingData AS (SELECT [ID],[MacAddr],[Remark],[Creator],[CreateTime] FROM [SS_MacAddr_Jur] WHERE 1 = 1 '
	IF @SearchStr <> ''
		SET @Sql += ' AND ([MacAddr] LIKE ''%' + @SearchStr + '%'' 
						OR [Remark] LIKE ''%' + @SearchStr + '%'') '  
	
	SET @Sql += '), DATA AS (SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM PagingData) A CROSS JOIN
									  (SELECT ROW_NUMBER() OVER(ORDER BY ID) AS ROWID,* FROM PagingData) B
							 WHERE B.ROWID > (@PageNo-1) * @PageSize AND B.ROWID <= @PageNo * @PageSize)
				 SELECT * FROM DATA'	
    EXEC sp_executesql @Sql, N'@PageNo INT, @PageSize INT', @PageNo, @PageSize	
END
GO




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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*------------------------------------------
    作者：李文博
	日期：2014-06-24
	描述：月结存
-------------------------------------------*/
CREATE PROCEDURE UP_SS_MonthBalance
(
	@ThisEndDate VARCHAR(10),
	@ThisName VARCHAR(50)
)

AS

DECLARE @Period TINYINT, @StartDate VARCHAR(10), @IsOpen BIT

SELECT TOP 1 @IsOpen = IsOpen FROM D9ZTInfo
IF @IsOpen = 0 RETURN -2 /*系统尚在期初*/

IF EXISTS(SELECT 1 FROM SS_MonthProc WHERE Name = @ThisName) RETURN -3 /*月结存名称重复*/

IF EXISTS(SELECT 1 FROM PD_AllotBill WHERE IsDraft = 0 AND Red = 0 AND InspectTag = 0 AND BillDate <= @ThisEndDate) RETURN -4 /*存在未验收完成的调拨单*/

SET XACT_ABORT ON

BEGIN TRAN MonthBalance

	SELECT TOP 1 @Period = Period,@StartDate = StartDate FROM SS_MonthProc ORDER BY Period DESC
	
	UPDATE  SS_MonthProc SET Name = @ThisName, EndDate = @ThisEndDate WHERE Period = @Period
	IF @@ROWCOUNT = 0 GOTO ERROR
	
	INSERT INTO SS_MonthProc
	        ( Period ,Name ,StartDate ,EndDate ,Remark)
	VALUES  
			( @Period+1 ,'本期' , DATEADD(dd, 1, @ThisEndDate) , NULL , '')
	IF @@ROWCOUNT = 0 GOTO ERROR
	
	/*结存科目金额*/
	INSERT INTO SS_MonthBalance
	        (	Period, FinanceID, Total, BqTotal 
			)
	SELECT  @Period AS Period,fa.FinanceID, 0 AS Total,ISNULL(lt.Total, 0)*fa.LoanStt AS BqTotal    
	FROM BD_Finance fa  
	LEFT JOIN (
		SELECT  FinanceID, (SUM(JTotal)- SUM(DTotal)) AS Total 
		FROM PD_ListTable 
		WHERE BillDate BETWEEN @StartDate AND @ThisEndDate
		GROUP BY FinanceID
		) lt 
	ON fa.FinanceID = lt.FinanceID
	WHERE fa.SonNum = 0
	
	
	UPDATE SS_MonthBalance SET
					Total = mb.BqTotal + ba.Balance
	FROM SS_MonthBalance mb
	INNER JOIN (
		SELECT	fa.FinanceID, ISNULL(QcBalances,0)+ ISNULL(BqTotal,0) AS Balance 
		FROM BD_Finance fa
		LEFT JOIN BD_Funds fd 
		ON fa.FinanceID = fd.FinanceID
		LEFT JOIN (
			SELECT  FinanceID, SUM(BqTotal) AS BqTotal 
			FROM SS_MonthBalance WHERE Period < @Period GROUP BY FinanceID
			) mb
		ON fa.FinanceID = mb.FinanceID
	) ba
	ON mb.FinanceID = ba.FinanceID WHERE mb.Period = @Period
	
	
	DELETE FROM SS_MonthBalance WHERE Total = 0 AND BqTotal = 0
	
	/*结存库存数量金额*/
	INSERT INTO SS_MonthStock
	        ( Period ,WhsID ,GoodsID ,Total ,BqTotal ,Qty ,BqQty
	        )
	SELECT @Period AS Period,bw.WhsID, bg.GoodsID, 0 AS Total, ISNULL(BqTotal, 0) AS BqTotal, 
			0 AS Qty,  ISNULL(BqQty, 0) AS BqQty 
			FROM BD_Goods bg 
			CROSS JOIN BD_Whs bw
	LEFT JOIN (
	SELECT GoodsID, WhsID, SUM(BqTotal) AS BqTotal, SUM(BqQty) AS BqQty FROM (
			SELECT GoodsID, Detail.WhsID, GoodsCostTotal AS BqTotal, BSQty AS BqQty FROM PD_PchDetail Detail
			INNER JOIN PD_PchBill I ON Detail.BillNo = I.BillNo  WHERE I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT GoodsID, Detail.WhsID, GoodsCostTotal*(-1) AS BqTotal, BSQty*(-1) AS BqQty FROM PD_PchRetDetail Detail
			INNER JOIN PD_PchRetBill I ON Detail.BillNo = I.BillNo  WHERE I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT GoodsID, Detail.WhsID, GoodsCostTotal*(-1) AS BqTotal, BSQty*(-1) AS BqQty FROM PD_SellDetail Detail
			INNER JOIN PD_SellBill I ON Detail.BillNo = I.BillNo  WHERE I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT GoodsID, Detail.WhsID, GoodsCostTotal AS BqTotal, BSQty AS BqQty FROM PD_SellRetDetail Detail
			INNER JOIN PD_SellRetBill I ON Detail.BillNo = I.BillNo  WHERE I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT GoodsID, Detail.OutWhsID AS WhsID, GoodsCostTotal*(-1) AS BqTotal, BSQty*(-1) AS BqQty FROM PD_AllotDetail Detail
			INNER JOIN PD_AllotBill I ON Detail.BillNo = I.BillNo  WHERE I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT GoodsID, Detail.InWhsID AS WhsID, GoodsCostTotal AS BqTotal, BSQty AS BqQty FROM PD_AllotDetail Detail
			INNER JOIN PD_AllotBill I ON Detail.BillNo = I.BillNo  WHERE I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT GoodsID, Detail.WhsID, (AdjTotal- GoodsCostTotal) AS BqTotal, 0 AS BqQty FROM PD_AdjPriceDetail Detail
			INNER JOIN PD_AdjPriceBill I ON Detail.BillNo = I.BillNo  WHERE I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT Detail.GoodsID, Detail.WhsID, GoodsCostTotal AS BqTotal, BSQty AS BqQty FROM PD_InOutWhsDetail Detail 
			INNER JOIN PD_InOutWhsBill I ON I.BillNo = Detail.BillNo WHERE I.BillTypeID =303 AND I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT Detail.GoodsID, Detail.WhsID,  GoodsCostTotal*(-1) AS BqTotal, BSQty*(-1) AS BqQty FROM PD_InOutWhsDetail Detail 
			INNER JOIN PD_InOutWhsBill I ON I.BillNo = Detail.BillNo WHERE I.BillTypeID =304 AND I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT Detail.GoodsID, Detail.WhsID, GoodsCostTotal AS BqTotal, BSQty AS BqQty FROM PD_LossSpillDetail Detail 
			INNER JOIN PD_LossSpillBill I ON I.BillNo = Detail.BillNo WHERE BillTypeID =306 AND I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
			UNION ALL
			SELECT Detail.GoodsID, Detail.WhsID, GoodsCostTotal*(-1) AS BqTotal, BSQty*(-1) AS BqQty FROM PD_LossSpillDetail Detail 
			INNER JOIN PD_LossSpillBill I ON I.BillNo = Detail.BillNo WHERE BillTypeID =305 AND I.BillDate BETWEEN @StartDate AND @ThisEndDate AND IsDraft = 0 AND Red = 0
		) InOut
		GROUP BY GoodsID, WhsID
	) gs ON bg.GoodsID = gs.GoodsID AND bw.WhsID = gs.WhsID
	
	
	UPDATE SS_MonthStock SET 
			Total = ms.BqTotal +  bs.Total,
			Qty = ms.BqQty + bs.Qty
	FROM SS_MonthStock ms
	INNER JOIN (
		SELECT bg.GoodsID, bw.WhsID, ISNULL(os.Total, 0) + ISNULL(ms.BqTotal, 0) AS Total,
			ISNULL(os.Qty, 0) + ISNULL(ms.BqQty, 0) AS Qty FROM 
		BD_Goods bg CROSS JOIN BD_Whs bw
		LEFT JOIN BD_OpeningStock os
		ON os.GoodsID =  bg.GoodsID AND os.WhsID = bw.WhsID
		LEFT JOIN(
			SELECT GoodsID, WhsID, SUM(BqTotal) AS BqTotal, SUM(BqQty) AS BqQty
			FROM SS_MonthStock WHERE Period < @Period GROUP BY GoodsID, WhsID
		) ms
		ON bg.GoodsID = ms.GoodsID AND bw.WhsID = ms.WhsID
	) bs
	ON ms.GoodsID = bs.GoodsID AND ms.WhsID = bs.WhsID WHERE ms.Period = @Period
	
	
	DELETE FROM SS_MonthStock WHERE Total = 0 AND BqTotal = 0 AND Qty = 0 AND BqQty = 0
	
	/*结存往来余额*/
	INSERT INTO SS_MonthArAp
	        ( Period, BTypeID, Total, BqTotal )
	SELECT  @Period AS Period,bb.BTypeID, 0 AS Total,ISNULL(lt.Total, 0) AS BqTotal    
	FROM BD_Btype bb
	LEFT JOIN (
		SELECT  BTypeID, (SUM(JTotal)- SUM(DTotal)) AS Total 
		FROM PD_ListTable 
		WHERE BillDate BETWEEN @StartDate AND @ThisEndDate AND BtypeID > 0 AND FinanceID IN (33,37)
		GROUP BY BtypeID
		) lt 
	ON bb.BTypeID = lt.BTypeID
	
	
	UPDATE SS_MonthArAp SET
					Total = mrp.BqTotal + ba.Balance
	FROM SS_MonthArAp mrp
	INNER JOIN (
		SELECT	bb.BTypeID, ISNULL(QcAR,0) - ISNULL(QcAP, 0)+ ISNULL(BqTotal,0) AS Balance 
		FROM BD_Btype bb
		LEFT JOIN BD_ARAP rp
		ON bb.BTypeID = rp.BTypeID
		LEFT JOIN (
			SELECT  BTypeID, SUM(BqTotal) AS BqTotal 
			FROM SS_MonthArAp WHERE Period < @Period GROUP BY BTypeID
			) mb
		ON bb.BTypeID = mb.BTypeID
	) ba
	ON mrp.BTypeID = ba.BTypeID WHERE mrp.Period = @Period
	
	DELETE FROM SS_MonthArAp WHERE Total = 0 AND BqTotal = 0
	
	       
COMMIT TRAN  MonthBalance
RETURN 0


ERROR:
BEGIN 
	ROLLBACK TRAN MonthBalance
	return -1 /*数据库操作失败，请稍后重试*/
end

GO



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

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/*
    作者：韩林
	日期：2014-6-25
	描述：开账处理
	modify by wb 160308 合计会员储值对应项目期初
*/
CREATE   PROCEDURE UP_SS_OpenAccount
(
	@StartDate DATETIME,
    @ReturnValue	VARCHAR(3000) out	--  输出信息
)


AS
SET NOCOUNT ON

--CREATE TABLE #Ktype(TypeId VARCHAR(50),Fullname VARCHAR(200))
--INSERT INTO #Ktype(TypeId,Fullname) SELECT TypeId,FullName FROM Stock WHERE STypeId = @STypeId AND SonNum = 0

-----------------判断否开账,如果已经开账，则直接返回--------
--IF EXISTS(SELECT TOP 1 1 FROM D9ZTInfo WHERE IsOpen=1)
--	RETURN 0
UPDATE D9ZTInfo SET IsOpen=1 WHERE IsOpen=0   --通过update的自动加锁来避免并发
IF @@ROWCOUNT=0
	RETURN 0


DECLARE @GoodsID INT
DECLARE @BTypeID INT
DECLARE @WhsID INT
DECLARE @GoodsName VARCHAR(100)
DECLARE @BTypeName VARCHAR(100)
DECLARE @WhsName VARCHAR(100)
DECLARE @VipCardNO VARCHAR(100)


------------------------------判断期初库存-----------------------------------------------------------
IF EXISTS(SELECT TOP 1 1 FROM BD_OpeningStock I  WHERE I.Qty = 0 AND I.Total <> 0 )
BEGIN
	SELECT TOP 1 @GoodsID=I.GoodsID,@WhsID=I.WhsID FROM BD_OpeningStock I WHERE I.Qty = 0 AND I.Total <> 0

	SELECT TOP 1 @GoodsName=GoodsName FROM BD_Goods WHERE GoodsID=@GoodsID
	SELECT TOP 1 @WhsName=WhsName FROM BD_Whs WHERE WhsID=@WhsID

	SET @ReturnValue='在仓库【'+@WhsName+'】中的商品【'+@GoodsName+'】，期初库存数量为零，但期初库存金额不为零，请修改确认后重试！'
	RETURN -8
END

-- 判断会员卡是否有期初储值且但未设置财务项目
IF EXISTS (SELECT 1 FROM dbo.VS_VipCard vip INNER JOIN dbo.VS_VipCardType vipType ON vip.VipCardTypeID = vipType.VipCardTypeID 
           WHERE vip.BeginStoreMoney <> 0 AND vipType.FinanceID = 0)
BEGIN
	SELECT TOP 1 @VipCardNO = vip.VipCardNO FROM dbo.VS_VipCard vip INNER JOIN dbo.VS_VipCardType vipType ON vip.VipCardTypeID = vipType.VipCardTypeID 
           WHERE vip.BeginStoreMoney <> 0 AND vipType.FinanceID = 0

	SET @ReturnValue='会员卡号【'+@VipCardNO+'】存在期初储值，但未设置会员储值项目，请修改确认后重试'
	RETURN -10
END
           


-------------- 处理库存期初----------------------------------
DELETE FROM BD_OpeningStock
WHERE	Qty = 0 
		AND Total = 0 
		
DELETE FROM BD_OpeningStock_Detail		
WHERE	Qty=0

TRUNCATE TABLE PD_GoodsStock
INSERT INTO PD_GoodsStock( WhsID, GoodsID, Qty, Price, Total )
SELECT WhsID, GoodsID, Qty, Price, Total FROM BD_OpeningStock

TRUNCATE TABLE PD_GoodsStock_Detail
INSERT INTO PD_GoodsStock_Detail
( 
		StockID ,
		WhsPtID ,
		GoodsID ,
		Ppt1ID ,
		Ppt2ID ,
		Qty,
		CostPrice,
		BatchNumber,
		ProductDate,
		EndDate		
)
SELECT 	PS.StockID ,
		WhsPtID ,
		D.GoodsID ,
		Ppt1ID ,
		Ppt2ID ,
		D.Qty,
		D.CostPrice,
		D.BatchNumber,
		D.ProductDate,
		D.EndDate
FROM BD_OpeningStock_Detail D 
INNER JOIN BD_OpeningStock OS ON D.StockID = OS.StockID
INNER JOIN  PD_GoodsStock PS ON D.GoodsID = PS.GoodsID AND OS.WhsID = PS.WhsID

TRUNCATE Table PD_GoodsSerial
INSERT INTO dbo.PD_GoodsSerial
(
		Serial ,
		WhsID ,
		WhsPtID ,
		GoodsID ,
		Ppt1ID ,
		Ppt2ID ,
		InBTypeID ,
		OutBTypeID ,
		InTime ,
		Remark ,
		Flag ,
		CostPrice ,
		IsOpening,
		BatchNumber,
		ProductDate,
		EndDate
)
SELECT  Serial ,
		WhsID ,
		WhsPtID ,
		d.GoodsID ,
		Ppt1ID ,
		Ppt2ID ,
		0 ,
		0 ,
		getdate(),
		s.Remark ,
		1 ,
		CASE CostMethod when 1 THEN Price ELSE CostPrice END ,
		1,
		D.BatchNumber,
		D.ProductDate,
		D.EndDate
FROM dbo.BD_OpeningSerial s
INNER JOIN dbo.BD_OpeningStock_Detail d ON s.StockDetailID=d.DetailID
INNER JOIN dbo.BD_OpeningStock k ON k.StockID=d.StockID
INNER JOIN BD_Goods G on k.GoodsID=g.GoodsID

----------------- ----特殊处理会计科目-------------------------------------------------------------
DECLARE @Total NUMERIC(20,8),@GOODS_ID INT
 
SELECT @GOODS_ID=FinanceID FROM BD_Finance WHERE FinanceNO='1243'			--『库存商品总值合计』
DELETE FROM  BD_Funds WHERE FinanceID = @GOODS_ID

SELECT @Total=ISNULL(SUM(I.total),0) FROM BD_OpeningStock I 
INSERT INTO BD_Funds(FinanceID,QcBalances)VALUES(@GOODS_ID,@Total)

DECLARE	@AR_ID VARCHAR(50),		
		@AP_ID VARCHAR(50),
		@BR_ID VARCHAR(50),		
		@BP_ID VARCHAR(50)
		
SELECT @AR_ID=FinanceID FROM BD_Finance WHERE FinanceNO='1131'			
SELECT @AP_ID=FinanceID FROM BD_Finance WHERE FinanceNO='2121'			
SELECT @BR_ID=FinanceID FROM BD_Finance WHERE FinanceNO='2131'			
SELECT @BP_ID=FinanceID FROM BD_Finance WHERE FinanceNO='1151'

DELETE FROM  BD_Funds WHERE FinanceID IN (@AR_ID,@AP_ID,@BR_ID,@BP_ID)
INSERT INTO BD_Funds( FinanceID, QcBalances )
SELECT case FianceType when 'qcar' then @AR_ID 
						when 'qcap' then @AP_ID
						when 'qcbr' then @BR_ID
						when 'qcbp' then @BP_ID end as FinanceID,
		Sum(VALUE) as value 
FROM BD_ARAP UNPIVOT(VALUE FOR FianceType IN(QcAP,QcAR,QcBP,QcBR)) AS Total where total.value<>0 group by FianceType

-- 合计会员期初储值
DELETE fs FROM dbo.BD_Funds fs INNER JOIN dbo.BD_Finance f ON fs.FinanceID = f.FinanceID WHERE f.[Path] LIKE '%0000500003%'
INSERT INTO dbo.BD_Funds( FinanceID, QcBalances )
SELECT vipType.FinanceID, SUM(vip.BeginStoreMoney) FROM dbo.VS_VipCard vip INNER JOIN dbo.VS_VipCardType vipType
ON vip.VipCardTypeID = vipType.VipCardTypeID WHERE vip.BeginStoreMoney <> 0 AND vipType.FinanceID <> 0
GROUP BY vipType.FinanceID HAVING SUM(vip.BeginStoreMoney) <> 0 

--修改财务期初汇总值	
UPDATE	BD_Funds SET QmBalances=QcBalances

DELETE FROM BD_Funds WHERE QmBalances=0

--修改往来期初汇总值	
UPDATE	BD_ARAP 
SET		QmAR=QcAR,
		QmAP=QcAP,
		QmBR=QcBR,
		QmBP=QcBP	

--本期日期只有一个，统一处理
UPDATE	SS_MonthProc 
SET		startdate=@StartDate,period=1,State=0

RETURN 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  StoredProcedure [UP_SS_QueryOperator]    Script Date: 05/22/2014 18:05:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_SS_QueryOperator]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_SS_QueryOperator]
GO

/****** Object:  StoredProcedure [UP_SS_QueryOperator]    Script Date: 05/22/2014 18:05:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-05-222
	描述：操作员管理信息列表
-------------------------------------------*/
CREATE PROCEDURE [UP_SS_QueryOperator]
(
	@PageNo INT,
	@PageSize INT,
	@FullName VARCHAR(50)='',
	@UserCode VARCHAR(20)=''
)

AS
SET NOCOUNT ON

DECLARE @sql NVARCHAR(max)
SELECT @sql='
;WITH PagingData AS 
(
	SELECT o.ElyID,
		e.ElyCode,
		e.ElyCode as LoginCode,
		e.ElyName,
		o.PASSWORD,
		(SELECT STUFF((SELECT '',''+sr.RoleName
			FROM SS_Oper_Role sor 
			INNER JOIN SS_Role sr ON sor.RoleID = sr.RoleID 
			WHERE sor.OperID=o.ElyID 
			FOR XML PATH ('''')),1,1,'''')
		) AS RoleName
FROM SS_Operator o
INNER JOIN BD_Employee e ON o.ElyID = e.ElyID 
WHERE o.ElyID<>1'

IF @UserCode <> ''
	SET @sql +=' AND e.ElyCode Like ''%''+@UserCode+''%'' '
IF @FullName <> ''
	SET @sql +=' AND e.ElyName Like ''%''+@FullName+''%'' '		
SET @sql +='
)'



DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@FullName','VARCHAR(100)',@FullName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@UserCode','VARCHAR(50)',@UserCode)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'ElyCode','','',1,0


GO






/****** Object:  StoredProcedure [UP_SS_QueryRoleBtypeList]    Script Date: 06/05/2014 11:41:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_SS_QueryRoleBtypeList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_SS_QueryRoleBtypeList]
GO

/****** Object:  StoredProcedure [UP_SS_QueryRoleBtypeList]    Script Date: 06/05/2014 11:41:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-02
	描述：查询用户组往来单位权限信息
-------------------------------------------*/
CREATE PROCEDURE [UP_SS_QueryRoleBtypeList]
(
	@RoleID INT=0,
	@PageNo INT=0,
	@PageSize INT=0
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)
SELECT @sql='
;WITH PagingData AS
(
	SELECT t.BtypeID[ID], t.BTypeCode[NO], t.BtypeName[Name] 
	FROM SS_Btype_Jur o 
	INNER JOIN BD_Btype t ON o.BtypeID = t.BtypeID 
	WHERE o.RoleID = @RoleID
)'
DECLARE @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@RoleID','INT',@RoleID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'Name','','',1,0
end

GO






/****** Object:  StoredProcedure [UP_SS_QueryRoleList]    Script Date: 06/05/2014 11:41:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_SS_QueryRoleList]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_SS_QueryRoleList]
GO

/****** Object:  StoredProcedure [UP_SS_QueryRoleList]    Script Date: 06/05/2014 11:41:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-06-05
	描述：查询用户组信息
-------------------------------------------*/
CREATE PROCEDURE [UP_SS_QueryRoleList]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@OperatorID INT=0				--操作员ID
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)
SELECT @sql='
;WITH ElyList AS
(
	SELECT a.RoleID,RoleName,c.ElyName,Describe 
	FROM SS_Role a 
	LEFT JOIN SS_Oper_Role b ON a.RoleID = b.RoleID 
	LEFT JOIN BD_Employee c ON b.OperID=c.ElyID
)
,PagingData AS
(
	SELECT RoleID,RoleName,EmployeeList,Describe 
	FROM (SELECT DISTINCT RoleID,RoleName,DESCRIBE FROM ElyList) a
    OUTER APPLY
    (SELECT EmployeeList=(STUFF((SELECT '',''+ElyName FROM ElyList WHERE RoleID=a.RoleID ORDER BY ElyName FOR XML PATH ('''')),1,1,''''))) b 
    WHERE a.RoleID NOT IN (SELECT RoleID FROM SS_Oper_Role WHERE OperID=@OperatorID)  
)'
/*SELECT sr.RoleID,sr.RoleName,be.ElyName,sr.DESCRIBE
into #temp 
FROM SS_Oper_Role sor
INNER JOIN SS_Role sr on sr.RoleID=sor.RoleID
INNER JOIN BD_Employee be on be.ElyID=sor.OperID
SELECT @sql='
;WITH PagingData AS
(
SELECT RoleID,RoleName,LEFT(EmployeeList,LEN(EmployeeList)-1) as EmployeeList,Describe 
FROM 
	(SELECT RoleID,RoleName,
		(SELECT ElyName + '',''
		FROM #temp
		WHERE RoleID=A.RoleID
		FOR XML PATH('''')) AS EmployeeList,
		Describe
	FROM #temp A
	WHERE RoleID<>@RoleID 
	GROUP BY RoleID,RoleName,DESCRIBE
	) B
)'*/
DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'RoleName','','',1,1
end

--exec UP_SS_QueryRoleList 0,1,10





GO






/****** Object:  StoredProcedure [UP_SS_QueryRoleList_1]    Script Date: 06/05/2014 11:41:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_SS_QueryRoleList_1]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_SS_QueryRoleList_1]
GO

/****** Object:  StoredProcedure [UP_SS_QueryRoleList_1]    Script Date: 06/05/2014 11:41:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-06-05
	描述：用户组信息列表（复制时的）
-------------------------------------------*/
CREATE PROCEDURE [UP_SS_QueryRoleList_1]
(
	@PageNo INT=0,
	@PageSize INT=0,
	@RoleID INT=0,				--用户组ID
	@OperatorID INT=0			--操作员ID
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)
SELECT @sql='
;WITH PagingData AS
(
	SELECT RoleID,RoleName FROM SS_Role 
	WHERE RoleID<>@RoleID AND RoleID NOT IN (SELECT RoleID FROM SS_Oper_Role WHERE OperID=@OperatorID)
)'
DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@RoleID','INT',@RoleID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'RoleName','','',1,1
end

GO






/****** Object:  StoredProcedure [UP_SS_QueryRoleWhsList]    Script Date: 06/05/2014 11:41:31 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_SS_QueryRoleWhsList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [UP_SS_QueryRoleWhsList]
GO

/****** Object:  StoredProcedure [UP_SS_QueryRoleWhsList]    Script Date: 06/05/2014 11:41:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：liuke
	日期：2014-4-25
	描述：查询用户组仓库权限信息
-------------------------------------------*/
CREATE PROCEDURE [UP_SS_QueryRoleWhsList]
(
	@RoleID INT=0,
	@PageNo INT=0,
	@PageSize INT=0
)

AS
SET NOCOUNT ON
begin
DECLARE @sql NVARCHAR(max)
SELECT @sql='
;WITH PagingData AS
(
	SELECT t.WhsID[ID], t.WhsNO[NO], t.WhsName[Name] 
	FROM SS_Whs_Jur o 
	INNER JOIN BD_Whs t ON o.WhsID = t.WhsID 
	WHERE o.RoleID = @RoleID
)'
/*SELECT sr.RoleID,sr.RoleName,be.ElyName,sr.DESCRIBE
into #temp 
FROM SS_Oper_Role sor
INNER JOIN SS_Role sr on sr.RoleID=sor.RoleID
INNER JOIN BD_Employee be on be.ElyID=sor.OperID
SELECT @sql='
;WITH PagingData AS
(
SELECT RoleID,RoleName,LEFT(EmployeeList,LEN(EmployeeList)-1) as EmployeeList,Describe 
FROM 
	(SELECT RoleID,RoleName,
		(SELECT ElyName + '',''
		FROM #temp
		WHERE RoleID=A.RoleID
		FOR XML PATH('''')) AS EmployeeList,
		Describe
	FROM #temp A
	WHERE RoleID<>@RoleID 
	GROUP BY RoleID,RoleName,DESCRIBE
	) B
)'*/
DECLARE  @TVP as TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES ('@RoleID','INT',@RoleID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'Name','','',1,0
end

GO






IF  EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'[UP_VS_ImportVipCard]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [UP_VS_ImportVipCard]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李文博
-- Create date:  2015-12-11
-- Description:	 会员卡信息导入[新增]
-- =============================================
CREATE  PROCEDURE [UP_VS_ImportVipCard]
    (
		@VipCardNO VARCHAR(25),
		@VipCardTypeName VARCHAR(50),
		@VipName VARCHAR(50),
		@CardHolder VARCHAR(50),
		@IDNO VARCHAR(30),
		@Sex VARCHAR(10),
		@BirthDay VARCHAR(10),
		@Tel VARCHAR(20),
		@Address VARCHAR(50),
		@Email VARCHAR(30),
		@CreateDate VARCHAR(10),
		@EndDate VARCHAR(10),
		@BTypeCode VARCHAR(50),
		@BeginMoney VARCHAR(50),
		@BeginCent VARCHAR(50),
		@Remark VARCHAR(256),
        @ErrMsg VARCHAR(max)='' OUTPUT
    )
AS 

BEGIN
    SET NOCOUNT ON   
	DECLARE @VipCardTypeID INT = 0, @SexValue TINYINT = 3, @BtypeID INT = 0, @MoneyValue NUMERIC(10,2) = 0
	DECLARE @CentValue NUMERIC(10,0) = 0	
	
	IF @VipCardTypeName = ''
	BEGIN
		SET @ErrMsg ='会员卡类型不能为空'
		RETURN -1
	END
	
	IF NOT EXISTS(SELECT 1 FROM VS_VipCardType WHERE TypeName = @VipCardTypeName)
	BEGIN
		SET @ErrMsg ='会员卡类型不存在或已被删除'
			RETURN -1
	END
	
	
	IF @VipCardNO = ''
	BEGIN
		SET @ErrMsg ='会员卡号不能为空'
		RETURN -1
	END
	
	IF EXISTS(SELECT 1 FROM VS_VipCard WHERE VipCardNO = @VipCardNO)
	BEGIN
		SET @ErrMsg ='会员卡号重复'
		RETURN -1
	END
	
	IF @BTypeCode = ''
	BEGIN
		SET @ErrMsg ='往来单位编号不能为空'
		RETURN -1
	END
	
	IF NOT EXISTS(SELECT 1 FROM BD_Btype WHERE BTypeCode = @BTypeCode)
	BEGIN
		SET @ErrMsg ='往来单位不存在或已被删除'
		RETURN -1
	END
	
	IF @Sex = ''
	BEGIN
		SET @ErrMsg ='性别不能为空'
		RETURN -1
	END
	
	IF @Sex = '男' 
		SET @SexValue = 1 
	ELSE IF @Sex = '女' 
		SET @SexValue = 2 
	ELSE IF @Sex = '保密' 
		SET @SexValue = 3 
	ELSE BEGIN
		SET @ErrMsg = '性别不符合规范，请录入[男]、[女]、[保密]'
		RETURN -1
	END
	
	
	SELECT @VipCardTypeID = VipCardTypeID FROM VS_VipCardType WHERE TypeName = @VipCardTypeName
	
	SELECT @BtypeID = BTypeID FROM BD_Btype WHERE BTypeCode = @BTypeCode
	
	IF @BeginMoney <> '' SET @MoneyValue = CONVERT(NUMERIC(10,2), @BeginMoney) 
	IF @BeginCent <> '' SET @CentValue = CONVERT(NUMERIC(10,0), @BeginCent) 
	
     	
			INSERT INTO [VS_VipCard]
				   (  [VipCardTypeID] ,
					  [VipCardNO] ,
					  [VipName] ,
					  [CardHolder] ,
					  [IDNO] ,
					  [Sex] ,
					  [Birthday] ,
					  [Address] ,
					  [Tel] ,
					  [Email] ,
					  [CreateDate] ,
					  [EndDate] ,
					  [BTypeID] ,
					  [Status] ,
					  [BeginMoney] ,
					  [BeginCent] ,
					  [TotalMoney] ,
					  [TotalCent] ,
					  [CentBalance] ,
					  [Remark])
			 VALUES
				   (@VipCardTypeID,
					@VipCardNO,
					@VipName,
					@CardHolder ,
					@IDNO ,
					@SexValue,
					@BirthDay,
					@Address,
					@Tel,
					@Email,
					@CreateDate,
					@EndDate,
					@BtypeID,
					1,
					@MoneyValue,
					@CentValue,
					@MoneyValue,
					@CentValue,
					@CentValue,
					@Remark) 
			
END
GO





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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
/*------------------------------------------
    作者：雷洋
	日期：2015-12-10
	描述：查询会员卡类型
-------------------------------------------*/
CREATE PROCEDURE [UP_VS_QueryVIPCardTypeList]
(
	@PageNo INT=0,
	@PageSize INT=0
)

AS
SET NOCOUNT ON

DECLARE @sql nvarchar(max)

SELECT @sql =
';WITH PagingData AS 
(select VipCardTypeID,TypeName,Discount,LevelUpMoney,LevelUpCent,BTypeID,
						Remark,case when IsDefault = 0 then '''+'否'+''' else '''+'是'+''' end as IsDefault from VS_VipCardType 
)'

DECLARE  @TVP AS TVP_Paging_Param
EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'TypeName','',''--,1,1 

go




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

/*------------------------------------------
    作者：李文博
	日期：2015-12-14
	描述：会员卡积分明细
-------------------------------------------*/
CREATE PROCEDURE UP_VS_VipCardCentDetail
(
	@PageNo INT=0,	
	@PageSize INT=0,
	@VipCardID INT = 0,		/*会员卡ID*/
	@BeforeCent INT=0,		/*此前积分*/
	@BeginDate DATE,		/*开始日期*/
	@EndDate DATE,			/*结束日期*/
	@IsHistory BIT=0		/*是否包含历史数据*/
)

AS

DECLARE @sql NVARCHAR(MAX) = ''
DECLARE @SellBill NVARCHAR(MAX) = '', @SellRetBill NVARCHAR(MAX)='',@CentExchangeBill NVARCHAR(MAX) = ''
DECLARE @SellCent NVARCHAR(MAX) = '', @SellRetCent NVARCHAR(MAX)='',@CentExchangeCent NVARCHAR(MAX) = ''
DECLARE @CentAdjustCent NVARCHAR(MAX) = ''

/*判断归档*/
DECLARE @re INT 
execute @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BeginDate,@isHistory=@IsHistory
IF( @re=1 )return @re;


SET @SellBill = ' 
SELECT BillNo, BillCode, BillDate, CreateTime, Red, VipCardID, [Description] 
FROM PD_SellBill WHERE IsDraft = 0 AND BillDate BETWEEN @BeginDate AND @EndDate 
'

SET @SellRetBill = ' 
SELECT BillNo, BillCode, BillDate, CreateTime, Red, VipCardID, [Description] 
FROM PD_SellRetBill WHERE IsDraft = 0 AND BillDate BETWEEN @BeginDate AND @EndDate 
'

SET @CentExchangeBill = '
SELECT BillNo, BillCode, BillDate, CreateTime, Red, VipCardID, [Description], BillTypeID 
FROM PD_InOutWhsBill WHERE IsDraft = 0 AND BillDate BETWEEN @BeginDate AND @EndDate 
'

IF @IsHistory = 1
BEGIN
	SET @SellBill += '
	UNION ALL
	SELECT BillNo, BillCode, BillDate, CreateTime, Red, VipCardID, [Description] 
	FROM PD_SellBill_His WHERE BillDate BETWEEN @BeginDate AND @EndDate
	'
	
	SET @SellRetBill += ' 
	UNION ALL
	SELECT BillNo, BillCode, BillDate, CreateTime, Red, VipCardID, [Description] 
	FROM PD_SellRetBill_His WHERE BillDate BETWEEN @BeginDate AND @EndDate 
	'
	
	SET @CentExchangeBill += '
	UNION ALL
	SELECT BillNo, BillCode, BillDate, CreateTime, Red, VipCardID, [Description], BillTypeID  
	FROM PD_InOutWhsBill_His WHERE BillDate BETWEEN @BeginDate AND @EndDate 
	'
END


SET @SellCent = '
SELECT VBS.BillTypeID, VBS.BillNo, VBS.GoodsID, ScoreRemark ,BillCode, 
VBS.BillDate, CreateTime, Red, [Description], VipCardID, VBS.Cent, VBS.Total,
CASE [Type] WHEN 2 THEN BG.GoodsNo WHEN 3 THEN BGT.TypeCode ELSE '''' END AS GoodsNo,
CASE [Type] WHEN 2 THEN BG.GoodsName WHEN 3 THEN BGT.TypeName ELSE '''' END AS GoodsName,
CASE WHEN VBS.Cent > 0 THEN VBS.Cent ELSE 0 END AS AddCent,
CASE WHEN VBS.Cent < 0 THEN VBS.Cent*(-1) ELSE 0 END AS SubCent
FROM PD_VipCardBillScore VBS
INNER JOIN ('+ @SellBill +') SB ON VBS.BillNo = SB.BillNo
LEFT JOIN BD_Goods BG ON VBS.GoodsID = BG.GoodsID
LEFT JOIN BD_Goods_Type BGT ON VBS.GoodsID = BGT.GoodsTypeID
WHERE VBS.BillTypeID = 201 AND SB.VipCardID = @VipCardID
'


SET @SellRetCent = '
SELECT VBS.BillTypeID, VBS.BillNo, VBS.GoodsID, ScoreRemark ,BillCode, 
VBS.BillDate, CreateTime, Red, [Description], VipCardID, VBS.Cent, VBS.Total,
CASE [Type] WHEN 2 THEN BG.GoodsNo WHEN 3 THEN BGT.TypeCode ELSE '''' END AS GoodsNo,
CASE [Type] WHEN 2 THEN BG.GoodsName WHEN 3 THEN BGT.TypeName ELSE '''' END AS GoodsName,
CASE WHEN VBS.Cent > 0 THEN VBS.Cent ELSE 0 END AS AddCent,
CASE WHEN VBS.Cent < 0 THEN VBS.Cent*(-1) ELSE 0 END AS SubCent
FROM PD_VipCardBillScore VBS
INNER JOIN ('+ @SellRetBill +') SB ON VBS.BillNo = SB.BillNo
LEFT JOIN BD_Goods BG ON VBS.GoodsID = BG.GoodsID
LEFT JOIN BD_Goods_Type BGT ON VBS.GoodsID = BGT.GoodsTypeID
WHERE VBS.BillTypeID = 202 AND SB.VipCardID = @VipCardID
'

SET @CentExchangeCent ='
SELECT VBS.BillTypeID, VBS.BillNo, VBS.GoodsID, ''积分兑换扣减'' ScoreRemark ,BillCode, 
VBS.BillDate, CreateTime, Red, [Description], VipCardID, VBS.Cent, VBS.Total,
'''' AS GoodsNo, '''' AS GoodsName, 0 AS AddCent, VBS.Cent*(-1) AS SubCent
FROM PD_VipCardBillScore VBS
INNER JOIN ('+ @CentExchangeBill +') SB ON VBS.BillNo = SB.BillNo
WHERE VBS.BillTypeID = 600 AND VBS.BillTypeID = SB.BillTypeID AND SB.VipCardID = @VipCardID
'

SET @CentAdjustCent ='
SELECT VBS.BillTypeID, VBS.BillNo, VBS.GoodsID, ScoreRemark , CONVERT(VARCHAR(50), VBS.BillNo) AS BillCode, 
VBS.BillDate, CreateTime,0 AS Red, '''' AS [Description], VipCardID, VBS.Cent, VBS.Total,
'''' AS GoodsNo, '''' AS GoodsName, 
CASE WHEN VBS.Cent > 0 THEN VBS.Cent ELSE 0 END AS AddCent,
CASE WHEN VBS.Cent < 0 THEN VBS.Cent*(-1) ELSE 0 END AS SubCent
FROM PD_VipCardBillScore VBS
INNER JOIN VS_CentAdjust SB ON VBS.BillNo = SB.BillNo
WHERE VBS.BillTypeID = 601 AND BillDate BETWEEN @BeginDate AND @EndDate AND SB.VipCardID = @VipCardID
'

SET @Sql = '
DECLARE @SourceData TABLE (RID INT,
BillNo INT, AddCent INT, SubCent INT, GoodsID INT, GoodsName VARCHAR(100),
GoodsNo VARCHAR(50), [Description] VARCHAR(100), BillCode VARCHAR(50),
BillDate DATE, CreateTime DATETIME, Red TINYINT, VipCardID INT, Cent INT,
Total DECIMAL(20,8), BillTypeID INT, ScoreRemark VARCHAR(256), BillName VARCHAR(50)
)

INSERT INTO @SourceData 
SELECT		RID = ROW_NUMBER()OVER(ORDER BY  CreateTime),
			BillNo,
			CASE Red WHEN 2 THEN SubCent*(-1) ELSE AddCent END AS AddCent,
			CASE Red WHEN 2 THEN AddCent*(-1) ELSE SubCent END AS SubCent,
			GoodsID,
			GoodsName,
			GoodsNo,
			[Description],
			A.BillCode,
			BillDate,
			CreateTime,
			Red,
			VipCardID,
			Cent,
			Total,
			A.BillTypeID,
			ScoreRemark,
			CASE A.BillTypeID WHEN 601 THEN ''积分调整单'' ELSE BT.BillName END AS BillName
FROM
(
	'+ @SellCent +'
	UNION ALL 
	'+ @SellRetCent +'
	UNION ALL 
	'+ @CentExchangeCent +'
	UNION ALL
	'+ @CentAdjustCent+'
) A 
LEFT JOIN PD_BillType BT ON A.BillTypeID = BT.BillTypeID



;WITH PagingData AS 
(

SELECT *,@BeforeCent + (SELECT SUM(Cent) FROM @SourceData  WHERE RID <= SD.RID )  AS CentBalance 
FROM  @SourceData SD

)
'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipCardID','INT',@VipCardID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeforeCent','INT', @BeforeCent)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@BeginDate','DATE',@BeginDate)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDate','DATE',@EndDate)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'CreateTime ASC', '', 'ROWID ASC',1,1
          

GO






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

/*------------------------------------------
    作者：李文博
	日期：2015-12-10
	描述：会员卡查询
-------------------------------------------*/
CREATE PROCEDURE UP_VS_VipCardList
(
	@PageNo INT=0,	
	@PageSize INT=0,
	@VipCardNOMatch BIT = 0,	/*会员卡号*/
	@VipCardNo VARCHAR(25),		/*会员卡号匹配方式0-包含，1-等于*/
	@VipCardTypeID NVARCHAR(MAX),/*会员卡类型*/
	@VipNameMatch BIT,			/*会员名称匹配方式0-包含，1-等于*/
	@VipName VARCHAR(50),		/*会员名称*/
	@CardHolderMatch BIT,		/*持卡人匹配方式0-包含，1-等于*/
	@CardHolder VARCHAR(50),	/*持卡人*/
	@IDNOMatch BIT,				/*证件号码匹配方式0-包含，1-等于*/
	@IDNO VARCHAR(30),			/*证件号码*/
	@VipBirthdayBegin VARCHAR(5),/*会员生日起始*/
	@VipBirthdayEnd VARCHAR(5),	/*会员生日结束*/
	@TelMatch BIT,				/*电话匹配方式0-包含，1-等于*/
	@Tel VARCHAR(20),			/*电话*/
	@AddressMatch BIT,			/*地址匹配方式0-包含，1-等于*/	
	@Address VARCHAR(50),		/*地址*/	
	@EmailMatch BIT,			/*邮箱匹配方式0-包含，1-等于*/
	@Email VARCHAR(30),			/*邮箱*/
	@CreateDateBegin DATE,		/*发卡日期起始*/	
	@CreateDateEnd DATE,		/*发卡日期结束*/
	@EndDateBegin DATE,			/*有效截止日期起始*/
	@EndDateEnd DATE,			/*有效截止日期结束*/
	@Status TINYINT,			/*会员卡状态0-全部，1-正常，2-已停用，3-已挂失*/
	@IsOverdue TINYINT,			/*是否过期0-全部，1-未过期，2-已过期*/
	@RemarkMatch BIT,			/*备注匹配方式0-包含，1-等于*/
	@Remark VARCHAR(256),		/*备注*/
	@OperatorID INT =1
	
)

AS

DECLARE @Sql NVARCHAR(MAX) = '', @CreateTableSql NVARCHAR(MAX) = '', @IndexTableSql NVARCHAR(MAX) = ''
DECLARE @WhereSql NVARCHAR(MAX) = ''

IF @VipCardNo <> ''
BEGIN
	IF @VipCardNOMatch = 1
		SET @WhereSql += ' AND VipCardNO = @VipCardNO'
	ELSE
		SET @WhereSql += ' AND VipCardNO Like ''%''+@VipCardNO+''%'' '
END

IF @VipCardTypeID <> ''
BEGIN
	SET @CreateTableSql += ' DECLARE @VipCardType Table(VipCardTypeID INT)   
     INSERT  INTO @VipCardType SELECT typeid AS VipCardTypeID  FROM dbo.UF_OT_Split_Int(@VipCardTypeID,'','')   
     '
     SET @IndexTableSql += ' INNER JOIN @VipCardType VT ON I.VipCardTypeID=VT.VipCardTypeID '
END

IF @VipName <> ''
BEGIN
	IF @VipNameMatch = 1
		SET @WhereSql += ' AND VipName = @VipName'
	ELSE
		SET @WhereSql += ' AND VipName Like ''%''+@VipName+''%'' '
END

IF @CardHolder <> ''
BEGIN
	IF @CardHolderMatch = 1
		SET @WhereSql += ' AND CardHolder = @CardHolder'
	ELSE
		SET @WhereSql += ' AND CardHolder Like ''%''+@CardHolder+''%'' '
END

IF @IDNO <> ''
BEGIN
	IF @IDNOMatch = 1
		SET @WhereSql += ' AND IDNO = @IDNO'
	ELSE
		SET @WhereSql += ' AND IDNO Like ''%''+@IDNO+''%'' '
END

IF @Tel <> ''
BEGIN
	IF @TelMatch = 1
		SET @WhereSql += ' AND I.Tel = @Tel'
	ELSE
		SET @WhereSql += ' AND I.Tel Like ''%''+@Tel+''%'' '
END

IF @Address <> ''
BEGIN
	IF @AddressMatch = 1
		SET @WhereSql += ' AND I.Address = @Address'
	ELSE
		SET @WhereSql += ' AND I.Address Like ''%''+@Address+''%'' '
END

IF @Email <> ''
BEGIN
	IF @EmailMatch = 1
		SET @WhereSql += ' AND I.Email = @Email'
	ELSE
		SET @WhereSql += ' AND I.Email Like ''%''+@Email+''%'' '
END 

IF @Status <> 0
BEGIN
	SET @WhereSql += ' AND Status = @Status'
END

IF @IsOverdue <> 0
BEGIN
	IF @IsOverdue = 1
		SET @WhereSql += ' AND EndDate >= CONVERT(VARCHAR(10), GETDATE(),120)'
	ELSE
		SET @WhereSql += ' AND EndDate < CONVERT(VARCHAR(10), GETDATE(),120)'
END

IF @Remark <> ''
BEGIN
	IF @RemarkMatch = 1
		SET @WhereSql += ' AND I.Remark = @Remark'
	ELSE
		SET @WhereSql += ' AND I.Remark Like ''%''+@Remark+''%'' '
END

IF @VipBirthdayBegin = '' SET @VipBirthdayBegin = '01-01'
IF @VipBirthdayEnd = '' SET @VipBirthdayEnd = '12-31'

IF @VipBirthdayEnd >= @VipBirthdayBegin
BEGIN
	SET @WhereSql += ' AND SUBSTRING(CONVERT(VARCHAR(10),Birthday), 6,5) BETWEEN @VipBirthdayBegin AND @VipBirthdayEnd'
END ELSE
BEGIN
	SET @WhereSql += ' AND (SUBSTRING(CONVERT(VARCHAR(10),Birthday), 6,5) BETWEEN @VipBirthdayBegin AND ''12-31''  OR 
						SUBSTRING(CONVERT(VARCHAR(10),Birthday), 6,5) BETWEEN ''01-01'' AND @VipBirthdayEnd)'
END

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 1
	SET @IndexTableSql += ' INNER JOIN dbo.UF_BD_BtypeLimit(@OperatorID) bl ON bl.BTypeID =I.BTypeID'

IF dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0
	SET @WhereSql += ' AND 1=2'

SET @Sql = @CreateTableSql + '
;WITH PagingData AS 
(
SELECT	  VipCardID,
		  I.VipCardTypeID ,
		  VCT.TypeName AS VipCardTypeName,
		  VCT.Discount,
          VipCardNO ,
          VipName ,
          CardHolder ,
          IDNO ,
          CASE Sex WHEN 1 THEN ''男'' WHEN 2 THEN ''女'' ELSE ''保密'' END AS Gender,
          Sex,
          Birthday ,
          Address ,
          I.Tel ,
          I.Email ,
          CreateDate ,
          EndDate ,
          I.BTypeID ,
          B.BTypeName,
          Status ,
          CASE Status WHEN 1 THEN ''正常'' WHEN 2 THEN ''已停用'' WHEN 3 THEN ''已挂失'' END AS VipCardStatus,
          CASE WHEN EndDate < CONVERT(VARCHAR(10),GetDate(),120) THEN ''已过期'' ELSE ''未过期'' END AS IsOverdue,
          I.TotalCent ,          
          I.Remark,
          I.BeginMoney,
  		  I.BeginCent,
		  I.TotalMoney,
		  I.CentBalance,		  
		  I.BeginStoreMoney,
		  I.TotalStoreMoney,
		  I.TotalExpenseMoney,
		  I.MoneyBalance
FROM VS_VipCard I
'+ @IndexTableSql + '
LEFT JOIN BD_BType B ON I.BtypeID = B.BTypeID 
LEFT JOIN VS_VipCardType VCT ON I.VipCardTypeID = VCT.VipCardTypeID
          WHERE CreateDate BETWEEN @CreateDateBegin AND @CreateDateEnd
				AND EndDate BETWEEN @EndDateBegin AND @EndDateEnd 
          ' + @WhereSql +
')'

DECLARE  @TVP AS TVP_Paging_Param
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipCardNo','VARCHAR(25)',@VipCardNo)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipCardTypeID','NVARCHAR(MAX)',@VipCardTypeID)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipName','VARCHAR(50)',@VipName)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@CardHolder','VARCHAR(50)',@CardHolder)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@IDNO','VARCHAR(30)',@IDNO)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipBirthdayBegin','VARCHAR(5)',@VipBirthdayBegin)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@VipBirthdayEnd','VARCHAR(5)',@VipBirthdayEnd)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Tel','VARCHAR(20)',@Tel)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Address','VARCHAR(50)',@Address)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Email','VARCHAR(30)',@Email)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@CreateDateBegin','DATE',@CreateDateBegin)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@CreateDateEnd','DATE',@CreateDateEnd)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDateBegin','DATE',@EndDateBegin)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@EndDateEnd','DATE',@EndDateEnd)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Status','TINYINT',@Status)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@Remark','VARCHAR(256)',@Remark)
INSERT INTO @TVP([ParaName],[DataType],[ParaValue]) VALUES('@OperatorID','INT',@OperatorID)

EXEC UP_OT_Paging @sql,@TVP,@PageNo,@PageSize,'VipCardNO ASC', '', 'ROWID ASC',1,1
          

GO






/****** Object:  StoredProcedure [UP_VS_VipChargeQuery]    Script Date: 06/23/2014 15:42:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[UP_VS_VipChargeQuery]') AND TYPE in (N'P', N'PC'))
DROP PROCEDURE [UP_VS_VipChargeQuery]
GO

/****** Object:  StoredProcedure [UP_VS_VipChargeQuery]    Script Date: 06/23/2014 15:42:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*------------------------------------------
    作者：hlin
	日期：2016-3-11
	描述：会员充值查询
-------------------------------------------*/
CREATE PROCEDURE [UP_VS_VipChargeQuery]
(			   
	@pageNo INT=1,					--页码
	@pageSize INT=10,				--分页数
	@BillStartDate DATETIME,		--单据开始日期
	@BillEndDate DATETIME,			--单据结束日期
	@VipCardNo VARCHAR(30) = '',   
	@VipCardMatch INT = 0,          
	@VipCardTypeID VARCHAR(1000) = '',
	@VipName VARCHAR(50) = '',   
	@VipNameMatch INT = 0,       
	@CardHolder VARCHAR(50) = '',   
	@CardHolderMatch INT = 0,       
	@Tel VARCHAR(20) = '',   
	@TelMatch INT = 0,       
	@DeptID VARCHAR(1000) = '',		--部门
	@ElyID VARCHAR(1000) = '',		--经手人
	@CreatorID VARCHAR(1000)='',    --制单人
	@IsHistory INT=0,				--是否包含历史数据
	@OperatorID INT=0				--操作员ID
)
AS
SET NOCOUNT ON
BEGIN

-- 当日期类型为业务日期的场合，做归档日期的范围判断
DECLARE @Re INT 
EXECUTE @Re=[UP_OT_CheckHistoryTime] @BillStartDate=@BillStartDate,@IsHistory=@IsHistory
IF( @Re=1 )RETURN @Re;

DECLARE @Sql NVARCHAR(MAX)='',@SqlJoin VARCHAR(max)='',@SqlWhere VARCHAR(max)='',@VipTableStr NVARCHAR(max)=''
--INNER JOIN BEGIN

IF @DeptID <> ''
BEGIN
	SET @SqlJoin +='
	INNER JOIN (SELECT d2.DeptID[typeid] from BD_Dept d INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') d1 ON d1.typeid=d.DeptID INNER JOIN BD_Dept d2 ON d2.[Path] LIKE d.[Path]+''%'') _Dept ON _Dept.typeid=p.DeptID '
END
IF @ElyID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@ElyID, '','') _Ely ON _Ely.typeid = p.ElyID '
IF @CreatorID <> ''
	SET @SqlJoin +='
	INNER JOIN dbo.UF_OT_Split_Int(@CreatorID, '','') _PEly ON _PEly.typeid = p.Creator '

IF @VipCardNo<>'' OR @VipCardTypeID<> '' OR @VipName <>'' OR  @CardHolder<>'' OR @Tel<>''       
  SET @SqlJoin += ' 
  INNER JOIN Vs_VipCard V ON V.VipCardID = D.VipCardID '
IF @VipCardTypeID<> ''
	SET @SqlJoin += ' 
	INNER JOIN Vs_VipCardType Vt ON V.VipCardTypeID = vt.VipCardTypeID
	INNER JOIN dbo.UF_OT_Split_Int(@VipCardTypeID, '','') vtype ON vtype.typeid=vt.VipCardTypeID  '

IF @VipCardNo<>''
BEGIN
	IF @VipCardMatch=0 SET @SqlWhere += 'AND v.VipCardNO LIKE ''%''+@VipCardNO+''%'' '  
	IF @VipCardMatch=1 SET @SqlWhere += 'AND v.VipCardNO=@VipCardNO ' 
END
IF @VipName<>''
BEGIN
	IF @VipNameMatch=0 SET @SqlWhere += 'AND v.VipName LIKE ''%''+@VipName+''%'' '  
	IF @VipNameMatch=1 SET @SqlWhere += 'AND v.VipName=@VipName ' 
END
IF @CardHolder<>''
BEGIN
	IF @CardHolderMatch=0 SET @SqlWhere += 'AND v.CardHolder LIKE ''%''+@CardHolder+''%'' '  
	IF @CardHolderMatch=1 SET @SqlWhere += 'AND v.CardHolder=@CardHolder ' 
END
IF @Tel<>''
BEGIN
	IF @TelMatch=0 SET @SqlWhere += 'AND v.Tel LIKE ''%''+@Tel+''%'' '  
	IF @TelMatch=1 SET @SqlWhere += 'AND v.Tel=@Tel ' 
END
  
SET @Sql ='
WITH BillData AS(
SELECT  BillCode,
		p.BillNo,
		BillDate,
		ElyID,
		Creator,
		DeptID,
		d.VipCardID,
		d.Total,
		d.Total-d.Privilege AfterPrivilege,
		d.Privilege,
		TotalBanlance,
		TotalBanlance+d.Total AS AfterBalance
FROM dbo.VS_VipChargeBill p
INNER JOIN dbo.VS_VipChargeDetail d ON p.BillNo = d.BillNo'
+@SqlJoin+'
WHERE BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft=0 AND red=0 '
+@Sqlwhere

IF @IsHistory=1
	SET @Sql+='
UNION ALL
SELECT  BillCode,
		p.BillNo,
		BillDate,
		ElyID,
		Creator,
		DeptID,
		d.VipCardID,
		d.Total,
		d.Total-d.Privilege AfterPrivilege,
		d.Privilege,
		D.TotalBanlance,
		d.TotalBanlance+d.Total AS AfterBalance
FROM dbo.VS_VipChargeBill_His p
INNER JOIN dbo.VS_VipChargeDetail_His d ON p.BillNo = d.BillNo'
+@SqlJoin+'
WHERE BillDate BETWEEN @BillStartDate AND @BillEndDate AND IsDraft=0 AND red=0 '
+@Sqlwhere

SET @sql+='
), 
PageData AS(
SELECT * FROM (SELECT COUNT(1) AS ''ROWCOUNT'' FROM BillData) A
CROSS JOIN
(
SELECT	ROW_NUMBER() OVER( ORDER BY BillCode DESC ) AS ROWID,
*
FROM BillData
) B
WHERE B.ROWID>(@PageNo-1)*@PageSize
AND B.ROWID<=@PageNo*@PageSize
)
SELECT	p.* ,
		e1.ElyName,
		e2.ElyName AS CreatorName,
		DeptName,
		VipCardNO,
		TypeName,
		VipName,
		CardHolder,
		v.Tel			
FROM PageData p 
INNER JOIN dbo.BD_Employee e1 ON e1.ElyID=p.ElyID
INNER JOIN dbo.BD_Employee e2 ON e2.ElyID=p.Creator
INNER JOIN dbo.BD_Dept d ON p.DeptID = d.DeptID
INNER JOIN dbo.VS_VipCard v ON p.VipCardID=v.VipCardID
INNER JOIN dbo.VS_VipCardType vt ON v.VipCardTypeID = vt.VipCardTypeID'

EXEC SP_EXECUTESQL @Sql,N'@pageNo INT,@pageSize INT,@BillStartDate DATETIME,@BillEndDate DATETIME
,@DeptID VARCHAR(1000),@ElyID VARCHAR(1000),@CreatorID VARCHAR(1000)
,@VipCardNo VARCHAR(30),@VipCardTypeID VARCHAR(1000),@VipName VARCHAR(50),@CardHolder VARCHAR(50),@Tel VARCHAR(20)'
,@pageNo,@pageSize,@BillStartDate,@BillEndDate
,@DeptID,@ElyID,@CreatorID
,@VipCardNo ,@VipCardTypeID,@VipName ,@CardHolder ,@Tel   

END


GO






IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_AtypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_AtypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-12-10
	描述：操作员项目授权
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_AtypeLimit]
(
	@OperatorID INT		
)
RETURNS @BD_AtypeLimit TABLE(FinanceID INT)
AS
BEGIN
	/*无权限和全部权限返回空数据集*/
	IF (dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 0) OR (dbo.UF_BD_IsAllAtypeLimit(@OperatorID) = 2) RETURN 

	INSERT INTO @BD_AtypeLimit
	SELECT DISTINCT FinanceID FROM SS_Finance_Jur sfj 
	INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON sfj.RoleID = sor.RoleID
	UNION ALL
	SELECT 0 AS FinanceID
	
	RETURN 
END	

GO




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_BaseSummary]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_BaseSummary]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-07-28
	描述：基本信息汇总
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_BaseSummary]
(
	@BaseType VARCHAR(5), --基本信息类型
	@SumLayer INT		  --汇总层级
)
RETURNS @BD_Base TABLE(BaseID INT, ParID INT)
AS
BEGIN
	IF @BaseType = 'PTYPE' --商品
	BEGIN
		INSERT INTO @BD_Base
		SELECT GT.GoodsTypeID AS BaseID, T.GoodsTypeID AS ParID FROM BD_Goods_Type GT 
		INNER JOIN BD_Goods_Type T
		ON T.[Path] LIKE GT.[Path]+'%'
		WHERE (GT.Lvl = @SumLayer OR (GT.Lvl < @SumLayer AND GT.SonNum =0))
        AND T.SonNum = 0
	END ELSE
	IF @BaseType = 'BTYPE' --往来单位
	BEGIN
		INSERT INTO @BD_Base
		SELECT GT.BtypeTypeID AS BaseID, T.BtypeTypeID AS ParID FROM BD_Btype_Type GT 
		INNER JOIN BD_Btype_Type T
		ON T.[Path] LIKE GT.[Path]+'%'
		WHERE (GT.Lvl = @SumLayer OR (GT.Lvl < @SumLayer AND GT.SonNum =0))
        AND T.SonNum = 0
        UNION ALL
        SELECT 0 AS BaseID, 0 AS ParID 
	END ELSE
	IF @BaseType = 'KTYPE' --仓库
	BEGIN
		INSERT INTO @BD_Base
		SELECT GT.WhsTypeID AS BaseID, T.WhsTypeID AS ParID FROM BD_Whs_Type GT 
		INNER JOIN BD_Whs_Type T
		ON T.[Path] LIKE GT.[Path]+'%'
		WHERE (GT.Lvl = @SumLayer OR (GT.Lvl < @SumLayer AND GT.SonNum =0))
        AND T.SonNum = 0
	END ELSE 
	IF @BaseType = 'AREA' --地区
	BEGIN
		INSERT INTO @BD_Base
		SELECT GT.AreaID AS BaseID, T.AreaID AS ParID FROM BD_Area GT 
		INNER JOIN BD_Area T
		ON T.[Path] LIKE GT.[Path]+'%'
		WHERE (GT.Lvl = @SumLayer OR (GT.Lvl < @SumLayer AND GT.SonNum =0))
        AND T.SonNum = 0
        UNION ALL
        SELECT 0 AS BaseID, 0 AS ParID
	END ELSE
	IF @BaseType = 'DTYPE' --部门
	BEGIN
		INSERT INTO @BD_Base
		SELECT GT.DeptID AS BaseID, T.DeptID AS ParID FROM BD_Dept GT 
		INNER JOIN BD_Dept T
		ON T.[Path] LIKE GT.[Path]+'%'
		WHERE (GT.Lvl = @SumLayer OR (GT.Lvl < @SumLayer AND GT.SonNum =0))
        AND T.SonNum = 0
	END

	RETURN 
END	

GO




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_BtypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_BtypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-12-10
	描述：操作员往来单位授权
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_BtypeLimit]
(
	@OperatorID INT		
)
RETURNS @BD_BtypeLimit TABLE(BTypeID INT)
AS
BEGIN
	/*无权限和全部权限返回空数据集*/
	IF (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0) OR (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 2) RETURN 

	INSERT INTO @BD_BtypeLimit
	SELECT DISTINCT BTypeID  FROM
	(
		SELECT BTypeID FROM SS_Btype_Jur sbj 
		INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON sbj.RoleID = sor.RoleID
		UNION ALL
		SELECT bb.BTypeID FROM BD_Btype_Type bbt
		INNER JOIN
		(
			SELECT bt.Path FROM SS_BtypeType_Jur btj
			INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON btj.RoleID = sor.RoleID
			INNER JOIN BD_Btype_Type bt ON btj.BtypeTypeID = bt.BtypeTypeID
			WHERE btj.LimitTag = 1
		) sbt ON bbt.Path LIKE sbt.Path+'%' 
		INNER JOIN BD_Btype bb ON bbt.BtypeTypeID = bb.BtypeTypeID
		WHERE bbt.SonNum = 0
	) BtypeLimit
	UNION ALL
	SELECT 0 AS BTypeID
	
	RETURN 
END	

GO




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_BtypeTypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_BtypeTypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-01-06
	描述：操作员往来单位分类授权
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_BtypeTypeLimit]
(
	@OperatorID INT		
)
RETURNS @BD_BtypeTypeLimit TABLE(BtypeTypeID INT, LimitTag INT)
AS
BEGIN
	/*无权限和全部权限返回空数据集*/
	IF (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 0) OR (dbo.UF_BD_IsAllBtypeLimit(@OperatorID) = 2) RETURN 	

	declare @BD_HasBhsTypeLimit TABLE(BtypeTypeID INT, LimitTag INT)
	INSERT INTO @BD_HasBhsTypeLimit SELECT bbt.BtypeTypeID, sbt.LimitTag FROM BD_Btype_Type bbt
		INNER JOIN
		(
			SELECT bt.Path, btj.LimitTag FROM SS_BtypeType_Jur btj
			INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON btj.RoleID = sor.RoleID
			INNER JOIN BD_Btype_Type bt ON btj.BtypeTypeID = bt.BtypeTypeID
			WHERE btj.LimitTag = 1
		) sbt ON bbt.Path LIKE sbt.Path+'%' 
		
	INSERT INTO @BD_BtypeTypeLimit
	SELECT DISTINCT BtypeTypeID, LimitTag  FROM
	(
		SELECT BtypeTypeID, LimitTag FROM @BD_HasBhsTypeLimit 
		UNION ALL
		SELECT bt.BtypeTypeID, btj.LimitTag FROM SS_BtypeType_Jur btj
		INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON btj.RoleID = sor.RoleID
		INNER JOIN BD_Btype_Type bt ON btj.BtypeTypeID = bt.BtypeTypeID
		WHERE btj.LimitTag = 2 and not exists(select 1 from @BD_HasBhsTypeLimit HBL where btj.BtypeTypeID = HBL.BtypeTypeID)
	) WhsLimit
		
	
	
	--INSERT INTO @BD_BtypeTypeLimit
	--SELECT DISTINCT BtypeTypeID, LimitTag  FROM
	--(
	--	SELECT bbt.BtypeTypeID, sbt.LimitTag FROM BD_Btype_Type bbt
	--	INNER JOIN
	--	(
	--		SELECT bt.Path, btj.LimitTag FROM SS_BtypeType_Jur btj
	--		INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON btj.RoleID = sor.RoleID
	--		INNER JOIN BD_Btype_Type bt ON btj.BtypeTypeID = bt.BtypeTypeID
	--		WHERE btj.LimitTag = 1
	--	) sbt ON bbt.Path LIKE sbt.Path+'%' 
	--	UNION ALL
	--	SELECT bt.BtypeTypeID, btj.LimitTag FROM SS_BtypeType_Jur btj
	--	INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON btj.RoleID = sor.RoleID
	--	INNER JOIN BD_Btype_Type bt ON btj.BtypeTypeID = bt.BtypeTypeID
	--	WHERE btj.LimitTag = 2
	--) WhsLimit
		
	RETURN 
END	

GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_GetAreaID_Str]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_GetAreaID_Str]

GO


--根据分类获取部门相应的ID，执行时，必须传@BtypeTypeID的参数
--date    :20014-08-12
CREATE FUNCTION [dbo].[UF_BD_GetAreaID_Str]
(
	@AreaID NVARCHAR(MAX)	
)
RETURNS Nvarchar(Max)
AS 
BEGIN
	DECLARE @sql NVarchar(Max)
	SET @sql=''
	SET @sql+='							SELECT	t1.AreaID 
										FROM	BD_Area  t'
	SET @sql+='									INNER JOIN BD_Area  t1  ON  t1.[Path] like t.[Path]+''%'''
IF @AreaID<>''
	SET @sql+='									INNER JOIN dbo.UF_OT_Split_Int('''+@AreaID+''','','') sp ON t.AreaID= sp.typeid '	
		
	SET @sql+='							WHERE	t.AreaID=@AreaTypeID and t1.SonNum=0 '
	
		return @sql
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_GetBtypeID_Str]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_GetBtypeID_Str]

GO


--根据分类获取往来单位相应的ID，执行时，必须传@BtypeTypeID的参数
--date    :20014-08-12
CREATE FUNCTION [dbo].[UF_BD_GetBtypeID_Str]
(
	@BtypeID NVarchar(MAX)
)
RETURNS Nvarchar(Max)
AS 
BEGIN
	DECLARE @sql NVarchar(Max)
	SET @sql=''
	SET @sql='
				SELECT	b.BTypeID as typeid 
				FROM  BD_Btype b'
	if(@BtypeID<>'')
		SET @sql+='			INNER JOIN dbo.UF_OT_Split_Int('''+@BtypeID+''','','') sp ON b.BTypeID= sp.typeid'			
		SET @sql+='			INNER JOIN (
										SELECT	t1.BtypeTypeID 
										FROM	BD_Btype_Type  t
												 INNER JOIN BD_Btype_Type  t1  ON  t1.[Path] like t.[Path]+''%''
										WHERE	t.BtypeTypeID=@BtypeTypeID and t1.SonNum=0
									) a ON b.BtypeTYpeID=a.BtypeTypeID '
		return @sql
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_GetDeptID_Str]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_GetDeptID_Str]

GO


--根据分类获取部门相应的ID
--date    :20014-08-12
CREATE FUNCTION [dbo].[UF_BD_GetDeptID_Str]
(
)
RETURNS Nvarchar(Max)
AS 
BEGIN
	DECLARE @sql NVarchar(Max)
	SET @sql=''
	SET @sql+='							SELECT	t1.DeptID 
										FROM	BD_Dept  t'
	SET @sql+='									INNER JOIN BD_Dept  t1  ON  t1.[Path] like t.[Path]+''%'''
	SET @sql+='									INNER JOIN dbo.UF_OT_Split_Int(@DeptID,'','') sp ON t.DeptID= sp.typeid '			
	SET @sql+='							WHERE	 t1.SonNum=0 '
	
		return @sql
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_GetGoodsID_Str]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_GetGoodsID_Str]

GO


--根据分类获取商品相应的ID，执行时，必须传@GoodsTypeID的参数
--date    :20014-08-12
CREATE FUNCTION [dbo].[UF_BD_GetGoodsID_Str]
(
@GoodsID Nvarchar(Max)
)
RETURNS Nvarchar(Max)
AS 
BEGIN
	DECLARE @sql NVarchar(Max)
	SET @sql=''
	SET @sql+='
				SELECT	b.GoodsID 
				FROM  BD_Goods b'
if(@GoodsID<>'')			
	SET @sql+='				INNER JOIN dbo.UF_OT_Split_Int('''+@GoodsID+''','','') sp ON b.GoodsID= sp.typeid '

					
	SET @sql+='				INNER JOIN (
										SELECT	t1.GoodsTypeID 
										FROM	BD_Goods_Type  t
												 INNER JOIN BD_Goods_Type  t1  ON  t1.[Path] like t.[Path]+''%''
										WHERE	t.GoodsTypeID=@GoodsTypeID and t1.SonNum=0
									) a ON b.GoodsTypeID=a.GoodsTypeID '
		return @sql
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



if object_id ('[dbo].[UF_BD_GetPptName]') is not null
    drop function [dbo].[UF_BD_GetPptName]
go


CREATE function [dbo].[UF_BD_GetPptName]
(	@PptGroupID int,
	@Flag int
	)
returns  varchar(8000)
as 
begin
	declare @Name varchar(8000)
	set @name= ''
	if @Flag=1 
	Begin
		select @name = @name + ',' +a.value 
		from BD_Goods_Ppt1 a,BD_Goods_PptGroup b 
		where a.Ppt1ID = b.Ppt1ID and b.PptGroupID = @PptGroupID 
		group by a.value
	End
	Else If @Flag = 2
	Begin
		select @name = @name + ',' +a.value 
		from BD_Goods_Ppt2 a,BD_Goods_PptGroup b 
		where a.Ppt2ID = b.Ppt2ID and b.PptGroupID = @PptGroupID 
		group by a.value
	END
	select @name=substring(@name,2,len(@name))
	return @Name
end
go



if object_id ('[dbo].[UF_BD_GetRoleName]') is not null
    drop function [dbo].[UF_BD_GetRoleName]
go


CREATE function [dbo].[UF_BD_GetRoleName]
(	@OperID int
	)
returns  varchar(8000)
as 
begin
	declare @Name varchar(8000)
	set @name= ''
	select @name = @name + ',' +a.RoleName 
	from SS_Role a,SS_Oper_Role b 
	where a.roleid = b.roleid and b.OperID = 1 
	group by a.RoleName
	select @name=substring(@name,2,len(@name))
	return @Name
end
go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_GetWhsID_Str]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_GetWhsID_Str]

GO


--根据分类获取仓库相应的ID，执行时，必须传@GoodsTypeID的参数
--date    :20014-08-12
CREATE FUNCTION [dbo].[UF_BD_GetWhsID_Str]
(
@WhsID Nvarchar(Max)
)
RETURNS Nvarchar(Max)
AS 
BEGIN
	DECLARE @sql NVarchar(Max)
	SET @sql=''
	SET @sql+='
				SELECT	b.WhsID 
				FROM  BD_Whs b'
if(@WhsID<>'')			
	SET @sql+='				INNER JOIN dbo.UF_OT_Split_Int('''+@WhsID+''','','') sp ON b.WhsID= sp.typeid '
					
	SET @sql+='				INNER JOIN (
										SELECT	t1.WhsTypeID 
										FROM	BD_Whs_Type  t
												 INNER JOIN BD_Whs_Type  t1  ON  t1.[Path] like t.[Path]+''%''
										WHERE	t.WhsTypeID=@WhsTypeID and t1.SonNum=0
									) a ON b.WhsTypeID=a.WhsTypeID '
		return @sql
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_IsAllAtypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_IsAllAtypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-12-23
	描述：操作员项目权限范围[0-无权限，1-部分权限，2-全部权限]
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_IsAllAtypeLimit]
(
	@OperatorID INT		
)
RETURNS INT 
AS
BEGIN
	
	IF @OperatorID = 1 
	BEGIN
		RETURN 2
	END
	
	
	/*操作员有角色是全部权限，则返回全部权限*/
	IF EXISTS (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID 
						AND RoleID IN (SELECT RoleID FROM SS_Role WHERE FinanceLimitTag = 2))
	BEGIN
		RETURN 2
	END
	
	/*操作员没有角色设置为全部权限，且有角色设置为部分权限，返回部分权限*/
	IF EXISTS (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID 
						AND RoleID NOT IN (SELECT RoleID FROM SS_Role WHERE FinanceLimitTag = 2)
						AND RoleID IN (SELECT RoleID FROM SS_Role WHERE FinanceLimitTag = 1))
	BEGIN
		RETURN 1
	END
	
	/*操作员没有角色设置为全部权限，且没有角色设置为部分权限，返回无权限*/
	
	RETURN 0
END	

GO




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_IsAllBtypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_IsAllBtypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-12-23
	描述：操作员往来单位权限范围[0-无权限，1-部分权限，2-全部权限]
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_IsAllBtypeLimit]
(
	@OperatorID INT		
)
RETURNS INT 
AS
BEGIN
	
	IF @OperatorID = 1 
	BEGIN
		RETURN 2
	END
	
	
	/*操作员有角色是全部权限，则返回全部权限*/
	IF EXISTS (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID 
						AND RoleID IN (SELECT RoleID FROM SS_Role WHERE BtypeLimitTag = 2))
	BEGIN
		RETURN 2
	END
	
	/*操作员没有角色设置为全部权限，且有角色设置为部分权限，返回部分权限*/
	IF EXISTS (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID 
						AND RoleID NOT IN (SELECT RoleID FROM SS_Role WHERE BtypeLimitTag = 2)
						AND RoleID IN (SELECT RoleID FROM SS_Role WHERE BtypeLimitTag = 1))
	BEGIN
		RETURN 1
	END
	
	/*操作员没有角色设置为全部权限，且没有角色设置为部分权限，返回无权限*/
	
	RETURN 0
END	

GO




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_IsAllKtypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_IsAllKtypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-07-23
	描述：操作员仓库权限范围[0-无权限，1-部分权限，2-全部权限]
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_IsAllKtypeLimit]
(
	@OperatorID INT		
)
RETURNS INT
AS
BEGIN
	IF @OperatorID = 1 
	BEGIN
		RETURN 2
	END
	
	
	/*操作员有角色是全部权限，则返回全部权限*/
	IF EXISTS (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID 
						AND RoleID IN (SELECT RoleID FROM SS_Role WHERE WhsLimitTag = 2))
	BEGIN
		RETURN 2
	END
	
	/*操作员没有角色设置为全部权限，且有角色设置为部分权限，返回部分权限*/
	IF EXISTS (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID 
						AND RoleID NOT IN (SELECT RoleID FROM SS_Role WHERE WhsLimitTag = 2)
						AND RoleID IN (SELECT RoleID FROM SS_Role WHERE WhsLimitTag = 1))
	BEGIN
		RETURN 1
	END
	
	/*操作员没有角色设置为全部权限，且没有角色设置为部分权限，返回无权限*/
	
	RETURN 0
END	

GO




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_KtypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_KtypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-07-23
	描述：操作员仓库授权
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_KtypeLimit]
(
	@OperatorID INT		
)
RETURNS @BD_WhsLimit TABLE(WhsID INT)
AS
BEGIN
	/*无权限和全部权限返回空数据集*/
	IF (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0) OR (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 2) RETURN 
	

	INSERT INTO @BD_WhsLimit
	SELECT DISTINCT WhsID  FROM
	(
		SELECT WhsID FROM SS_Whs_Jur swj 
		INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON swj.RoleID = sor.RoleID
		UNION ALL
		SELECT bw.WhsID FROM BD_Whs_Type bwt
		INNER JOIN
		(
			SELECT wt.Path FROM SS_WhsType_Jur wtj
			INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON wtj.RoleID = sor.RoleID
			INNER JOIN BD_Whs_Type wt ON wtj.WhsTypeID = wt.WhsTypeID
			WHERE wtj.LimitTag = 1
		) swt ON bwt.Path LIKE swt.Path+'%' 
		INNER JOIN BD_Whs bw ON bwt.WhsTypeID = bw.WhsTypeID
		WHERE bwt.SonNum = 0
	) WhsLimit
		
	RETURN 
END	

GO




IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_BD_KtypeTypeLimit]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_BD_KtypeTypeLimit]

GO


/*------------------------------------------
    作者：李文博
	日期：2014-01-06
	描述：操作员仓库分类授权
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_BD_KtypeTypeLimit]
(
	@OperatorID INT		
)
RETURNS @BD_WhsTypeLimit TABLE(WhsTypeID INT, LimitTag INT)
AS
BEGIN
	/*无权限和全部权限返回空数据集*/
	IF (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 0) OR (dbo.UF_BD_IsAllKtypeLimit(@OperatorID) = 2) RETURN 
	
	DECLARE @BD_HasWhsTypeLimit TABLE(WhsTypeID INT, LimitTag INT)
	INSERT INTO @BD_HasWhsTypeLimit SELECT bwt.WhsTypeID, swt.LimitTag FROM BD_Whs_Type bwt
		INNER JOIN
		(
			SELECT wt.Path, wtj.LimitTag FROM SS_WhsType_Jur wtj
			INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON wtj.RoleID = sor.RoleID
			INNER JOIN BD_Whs_Type wt ON wtj.WhsTypeID = wt.WhsTypeID
			WHERE wtj.LimitTag = 1
		) swt ON bwt.Path LIKE swt.Path+'%' 

	INSERT INTO @BD_WhsTypeLimit
	SELECT DISTINCT WhsTypeID, LimitTag  FROM
	(
		SELECT WhsTypeID, LimitTag FROM @BD_HasWhsTypeLimit
		UNION ALL
		SELECT wt.WhsTypeID, wtj.LimitTag FROM SS_WhsType_Jur wtj
		INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON wtj.RoleID = sor.RoleID
		INNER JOIN BD_Whs_Type wt ON wtj.WhsTypeID = wt.WhsTypeID
		WHERE wtj.LimitTag = 2 and not exists(select 1 from @BD_HasWhsTypeLimit HWL where wtj.WhsTypeID = HWL.WhsTypeID)
	) WhsLimit
	

	--INSERT INTO @BD_WhsTypeLimit
	--SELECT DISTINCT WhsTypeID, LimitTag  FROM
	--(
	--	SELECT bwt.WhsTypeID, swt.LimitTag FROM BD_Whs_Type bwt
	--	INNER JOIN
	--	(
	--		SELECT wt.Path, wtj.LimitTag FROM SS_WhsType_Jur wtj
	--		INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON wtj.RoleID = sor.RoleID
	--		INNER JOIN BD_Whs_Type wt ON wtj.WhsTypeID = wt.WhsTypeID
	--		WHERE wtj.LimitTag = 1
	--	) swt ON bwt.Path LIKE swt.Path+'%' 
	--	UNION ALL
	--	SELECT wt.WhsTypeID, wtj.LimitTag FROM SS_WhsType_Jur wtj
	--	INNER JOIN (SELECT RoleID FROM SS_Oper_Role WHERE OperID = @OperatorID) sor ON wtj.RoleID = sor.RoleID
	--	INNER JOIN BD_Whs_Type wt ON wtj.WhsTypeID = wt.WhsTypeID
	--	WHERE wtj.LimitTag = 2
	--) WhsLimit
		
	RETURN 
END	

GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


--实现用户单据权限判断功能 的函数
--date    :2014-08-14
CREATE FUNCTION [dbo].[UF_OT_BillTypeLimit]
(
	@UserID Int = 0
)
returns @temp TABLE(typeid INT)
AS 
BEGIN
if(@UserID <> 1)
begin
    INSERT @temp SELECT case sj.jurID when 1210110 then 101 
					  when 1210210 then 102
					  when 1310110 then 201
					  when 1310210 then 202
					  when 1410010 then 301
					  when 1410110 then 302
					  when 1410210 then 303
					  when 1410310 then 304
					  when 1410410 then 305
					  when 1410510 then 306
					  when 1410610 then 309
					  when 1410810 then 310
					  when 1610010 then 401
					  when 1610110 then 402
					  when 1610210 then 403
					  when 1610310 then 404
					  when 1610410 then 405
					  when 1610510 then 406
					  when 1610610 then 501
					  when 1610710 then 502
					  when 1610810 then 503
					  when 1610910 then 504					  
					  when 2010010 then 600	
					  when 2010110 then 602					  
					  end as BillTypeID
 FROM SS_Role_Jur  sj
	  INNER JOIN  SS_Oper_Role so ON sj.RoleID=so.RoleID
 WHERE so.OperID=@UserID AND so.Stt=1 AND sj.opp=1 
		and jurID in (1210110,1210210,1310110,1310210,1410010,1410110,
					  1410210,1410310,1410410,1410510,1410610,1410810,1610010,1610110,
					  1610210,1610310,1610410,1610510,1610610,1610710,
					  1610810,1610910,2010010,2010110) GROUP by sj.JurID
End					  
else
begin
	 INSERT @temp SELECT BillTypeID  FROM PD_BillType where CanPost = 1
end	
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


--实现查询表的所有列功能 的函数
--date    :2014-6-20
CREATE FUNCTION [dbo].[UF_OT_GetColumns]
(
	@tablename varchar(500),
	@OtherName VARCHAR(10)='',
	@excludeColumns VARCHAR(max) --排除的列，多列用','分割
)
returns nvarchar(max) 
AS 
BEGIN
    DECLARE @a VARCHAR(MAX)=''
	SELECT @a=@a+@OtherName+a.name+',' FROM syscolumns a INNER JOIN sysobjects	b ON a.ID=b.ID 
	WHERE b.Name=@tablename AND  NOT EXISTS(SELECT a  FROM dbo.UF_OT_Split(@excludeColumns,',') WHERE a=a.name)
	SET @a=SUBSTRING(@a,1,LEN(@a)-1)
    RETURN @a
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


--实现获取往来单位截止检测时间范围的函数
--date    :2015-03-19
CREATE FUNCTION [dbo].[UF_OT_GetLastDate]
(
	@PaidCircle	INT = 0,      --结算周期
	@StatementPeriod Int = 0,  --对账期
	@PaidDeadline Int = 0 --结算截止日
)
returns VARCHAR(max)
AS 
BEGIN
    DECLARE @LastDate VARCHAR(max)=''
    DECLARE @RecBeforeDay varchar(Max)=convert(nvarchar(10),dateadd(d,@StatementPeriod*-1,getdate()),120)
    DECLARE @Day Int = DateName(day,@RecBeforeDay)
    DECLARE @LastDateNew datetime --截止点
    DECLARE @MonthAdd2 Int = MONTH(GETDATE())%2
    DECLARE @MonthAdd3 Int = MONTH(GETDATE())%3
    --====================具体实现================================
    IF(@PaidCircle <> 0) 
    BEGIN
		-- 选择半月的情况
		IF @PaidCircle = 2
		BEGIN
			IF @Day < 15
			BEGIN
				SELECT @LastDate = convert(nvarchar(10),DATEADD(d,(@Day*-1),@RecBeforeDay),120)
			END
			ELSE
			BEGIN
				SELECT @LastDate = convert(nvarchar(10),DATEADD(d,(@Day*-1)+15,@RecBeforeDay),120)
			END
		END
		ELSE
		BEGIN
			--====================选择月底的情况================================
			IF @PaidDeadline = 0
			BEGIN
				IF @PaidCircle = 3
				BEGIN
					SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,3-@PaidCircle,@RecBeforeDay),120)
					SELECT @LastDate = convert(nvarchar(10),DATEADD(D,(@Day*-1),@RecBeforeDay),120)
				END
				-- 结算周期为两个月的情况
				IF @PaidCircle = 4
				BEGIN
					IF @MonthAdd2 = 1 AND @StatementPeriod >= DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,-1,@RecBeforeDay),120)
					END
					ELSE IF @MonthAdd2 = 1 AND @StatementPeriod < DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,0,@RecBeforeDay),120)
					END
					IF @MonthAdd2 = 0 AND @StatementPeriod >= DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,0,@RecBeforeDay),120)
					END
					ELSE IF @MonthAdd2 = 0 AND @StatementPeriod < DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,-1,@RecBeforeDay),120)
					END
					SELECT @LastDate = convert(nvarchar(10),DATEADD(D,(@Day*-1),@RecBeforeDay),120)
				END
				-- 结算周期为三个月的情况
				ELSE IF @PaidCircle = 5
				BEGIN
					IF @MonthAdd3 = 1 AND @StatementPeriod >= DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,-2,@RecBeforeDay),120)
					END
					ELSE IF @MonthAdd3 = 1 AND @StatementPeriod < DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,0,@RecBeforeDay),120)
					END
								
					IF @MonthAdd3 = 0 AND @StatementPeriod < DAY(GETDATE())	
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,-2,@RecBeforeDay),120)
					END
					ELSE IF  @MonthAdd3 = 0 AND @StatementPeriod >= DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,-1,@RecBeforeDay),120)
					END
					
					IF @MonthAdd3 = 2 AND @StatementPeriod < DAY(GETDATE())	
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,-1,@RecBeforeDay),120)
					END
					ELSE IF  @MonthAdd3 = 2 AND @StatementPeriod >= DAY(GETDATE())
					BEGIN
						SELECT @RecBeforeDay=convert(nvarchar(10),DATEADD(M,0,@RecBeforeDay),120)
					END
					
					SELECT @LastDate = convert(nvarchar(10),DATEADD(D,(@Day*-1),@RecBeforeDay),120)
				END
			END
			--====================选择1~28日的情况================================
			ELSE
			BEGIN
				-- 结算周期为一个月的情况
				IF @PaidCircle = 3
				BEGIN				
					-- 截止点
					SELECT @LastDateNew = DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline + @StatementPeriod,DATEADD(m,3-@PaidCircle,GETDATE()))
					-- 截止点大于当前日期场合 则将结算日期提前一个月，否则则比对当前范围结算日期
					IF @LastDateNew > GETDATE()
					BEGIN
						SELECT @LastDate = CONVERT(NVARCHAR(10),DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline,DATEADD(m,3-@PaidCircle-1,GETDATE())),120)
					END
					ELSE
					BEGIN
						SELECT @LastDate = CONVERT(NVARCHAR(10),DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline,DATEADD(m,3-@PaidCircle,GETDATE())),120)
					END 
				END
				-- 结算周期为两个月的情况
				ELSE IF @PaidCircle = 4
				BEGIN
					-- 截止点
				    IF @MonthAdd2 = 0
					BEGIN
						SELECT @LastDateNew = DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline + @StatementPeriod,DATEADD(m,0,GETDATE()))
					END
					ELSE IF @MonthAdd2 = 1
					BEGIN
						SELECT @LastDateNew = DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline + @StatementPeriod,DATEADD(m,1,GETDATE()))
					END
					
					IF @LastDateNew > GETDATE()
					BEGIN
						SELECT @LastDate = CONVERT(NVARCHAR(10),DATEADD(d,-@StatementPeriod,DATEADD(m,-2,@LastDateNew)),120)   
					END
					ELSE 
					BEGIN
						SELECT @LastDate = CONVERT(NVARCHAR(10),DATEADD(d,-@StatementPeriod,@LastDateNew),120)
					END
				END
				-- 结算周期为三个月的情况
				ELSE IF @PaidCircle = 5
				BEGIN
					-- 截止点
				    IF @MonthAdd3 = 0
					BEGIN
						SELECT @LastDateNew = DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline + @StatementPeriod,DATEADD(m,0,GETDATE()))
					END
					ELSE IF @MonthAdd3 = 1
					BEGIN
						SELECT @LastDateNew = DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline + @StatementPeriod,DATEADD(m,2,GETDATE()))
					END
					ELSE IF @MonthAdd3 = 2
					BEGIN
						SELECT @LastDateNew = DATEADD(d,-CONVERT(INT,DATENAME(day,GetDate()))+@PaidDeadline + @StatementPeriod,DATEADD(m,1,GETDATE()))
					END
					
					IF @LastDateNew > GETDATE()
					BEGIN
						SELECT @LastDate = CONVERT(NVARCHAR(10),DATEADD(d,-@StatementPeriod,DATEADD(m,-3,@LastDateNew)),120)    
					END
					ELSE 
					BEGIN
						SELECT @LastDate = CONVERT(NVARCHAR(10),DATEADD(d,-@StatementPeriod,@LastDateNew),120)
					END
				END
			END
		END
    
    END
	--====================具体实现 end================================

    RETURN @LastDate
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  StoredProcedure [dbo].[UF_OT_GetLastPath]    Script Date: 12/23/2014 10:04:00 ******/
IF EXISTS (SELECT * FROM sys.sysobjects WHERE id = object_id(N'[dbo].[UF_OT_GetLastPath]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_OT_GetLastPath]
GO

/****** Object:  UserDefinedFunction [dbo].[UF_OT_GetLastPath]    Script Date: 12/23/2014 12:38:33 ******/
SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

/*------------------------------------------
    作者：liuke
	日期：2014-12-23
	描述：获取下一个路径值
-------------------------------------------*/
CREATE FUNCTION [dbo].[UF_OT_GetLastPath]
(
	@Path VARCHAR(50)
)
RETURNS VARCHAR(50)
AS 
BEGIN
    DECLARE @FirstPath VARCHAR(50)='', @SecondPath VARCHAR(50)='', @NumStr VARCHAR(50)='', @Num INT=0, @i INT=0, @ZeroStr VARCHAR(50)=''
    
    SET @FirstPath=SUBSTRING(@Path, 0, LEN(@Path)-4)
    SET @SecondPath=SUBSTRING(@Path, LEN(@Path)-4, 5)
    
    SET @NumStr=(Cast(@SecondPath AS INT)+1);
    SET @Num=5-LEN(@NumStr);
    WHILE @i<@Num
    BEGIN
		SET @ZeroStr+='0'
		SET @i+=1
    END
    SET @SecondPath=@ZeroStr+@NumStr;
    
    SET @Path=@FirstPath+@SecondPath;
    RETURN @Path
END

GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[UF_OT_GetMatchStr]') AND xtype IN (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[UF_OT_GetMatchStr]
GO
-- =============================================
-- Author:		WuBin
-- Create date:  2014/7/8
-- Description:	 匹配字符串
-- =============================================
CREATE FUNCTION [dbo].[UF_OT_GetMatchStr]
(
	@ColumnName VARCHAR(100),  --列名
	@Keyword VARCHAR(100),  --匹配关键字
	@MatchType INT = 1 --1:包含 2:等于
)
RETURNS VARCHAR(100)
AS 
BEGIN
	DECLARE @Str VARCHAR(100)
    IF @MatchType = 1
		SET @Str = ' ' + @ColumnName + ' LIKE ''%' + @Keyword + '%'' '
    ELSE IF @MatchType = 2    
		SET @Str = ' ' + @ColumnName + ' = ''' + @Keyword + ''' '
    RETURN @Str 
END
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


--实现split功能 的函数
--date    :2003-10-14
CREATE FUNCTION dbo.UF_OT_GetPath
(
	@ParID	INT,	
	@Type	INT		--0地区 1部门 其他的自己加上
)
returns VARCHAR(max)
AS 
BEGIN
    DECLARE @pathName VARCHAR(max)=''
    --====================具体实现================================
    IF(@type=0)
    BEGIN
		SELECT @pathName=AreaName FROM BD_Area WHERE AreaID=@ParID
		WHILE EXISTS(SELECT 1 FROM BD_Area WHERE AreaID=@ParID AND ParID<>0)
		BEGIN
			SELECT @ParID=ParID FROM BD_Area WHERE AreaID=@ParID
			SELECT @pathName=AreaName+'\' +@pathName FROM BD_Area WHERE AreaID=@ParID
		END
	END
	
	IF(@type=1)
    BEGIN
		SELECT @pathName=DeptName FROM BD_Dept WHERE DeptID=@ParID
		WHILE EXISTS(SELECT 1 FROM BD_Dept WHERE DeptID=@ParID AND ParID<>0)
		BEGIN
			SELECT @ParID=ParID FROM BD_Dept WHERE DeptID=@ParID
			SELECT @pathName=DeptName+'\' +@pathName FROM BD_Dept WHERE DeptID=@ParID
		END
	END
	--====================具体实现 end================================

    RETURN @pathname
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





/****** Object:  UserDefinedFunction [dbo].[UF_OT_GetPathByID]    Script Date: 05/15/2014 11:38:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UF_OT_GetPathByID]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[UF_OT_GetPathByID]
GO

/****** Object:  UserDefinedFunction [dbo].[UF_OT_GetPathByID]    Script Date: 05/15/2014 11:38:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
	实现获取树路劲的函数
	日期:2014-05-15
	作者:liuke
*/

/*添加其他表的路劲查找功能：
	1、复制IF块
	2、修改Type参数
	3、Ctrl+H：表名【BD_Dept】替换，表ID【DeptId】替换，表显示名称【DeptName】替换即可
*/
CREATE FUNCTION [dbo].[UF_OT_GetPathByID]
(
	@ID		INT,	
	@Type	INT		--1部门 其他的自己加上
) RETURNS VARCHAR(max)
AS
BEGIN
	DECLARE @re_str AS VARCHAR(max)
  
	IF(@Type=1)
	BEGIN
		SET @re_str = ''
		SELECT @re_str = DeptName FROM BD_Dept WHERE DeptId = @ID
		WHILE exists (SELECT 1 FROM BD_Dept WHERE DeptId = @ID and ParID <> 0)
		BEGIN
		  SELECT @ID = b.DeptId , @re_str = b.DeptName + '\' + @re_str 
		  FROM BD_Dept a , BD_Dept b 
		  WHERE a.DeptId = @ID and a.ParID = b.DeptId
		END
	END
	
	RETURN @re_str
END	
	

GO






SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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

/*
	作者：Hanlin
	日期：2014-11-24
	描述：传入参数返回拼音
	实例：
			DECLARE @returnPym varchar(1000)
			EXEC @returnPym = dbo.UF_OT_GetPY '任我行软件'
			SET @returnPym = UPPER(@returnPym)	--小写LOWER
			PRINT(@returnPym)
*/

CREATE FUNCTION [dbo].[UF_OT_GetPY]
 ( 
    @Str nvarchar(4000) 
 ) 
returns nvarchar(4000) 
--@ENCODE$--
AS 
BEGIN 
	DECLARE @word nchar(1),@PY nvarchar(4000) 

	SET @PY='' 

	WHILE len(@STR)>0 
	BEGIN 
		SET @word=LEFT(@STR,1) 
		
		--如果非汉字字符，返回原字符 
		SET @PY=@PY+(CASE WHEN unicode(@word) BETWEEN 19968 AND 19968+20901 
		           THEN (  
		                        SELECT TOP 1 PY  
		                        FROM  
		                        (  
			                         SELECT 'A' AS PY,N'驁' AS word 
			                         UNION ALL SELECT 'B',N'簿' 
			                         UNION ALL SELECT 'C',N'錯' 
					                 UNION ALL SELECT 'D',N'鵽' 
					                 UNION ALL SELECT 'E',N'樲' 
					                 UNION ALL SELECT 'F',N'鰒' 
					                 UNION ALL SELECT 'G',N'腂' 
					                 UNION ALL SELECT 'H',N'夻' 
					                 UNION ALL SELECT 'J',N'攈' 
					                 UNION ALL SELECT 'K',N'穒' 
					                 UNION ALL SELECT 'L',N'鱳' 
					                 UNION ALL SELECT 'M',N'旀' 
					                 UNION ALL SELECT 'N',N'桛' 
					                 UNION ALL SELECT 'O',N'漚' 
					                 UNION ALL SELECT 'P',N'曝' 
					                 UNION ALL SELECT 'Q',N'囕' 
					                 UNION ALL SELECT 'R',N'鶸' 
					                 UNION ALL SELECT 'S',N'蜶' 
					                 UNION ALL SELECT 'T',N'籜' 
					                 UNION ALL SELECT 'W',N'鶩' 
					                 UNION ALL SELECT 'X',N'鑂' 
					                 UNION ALL SELECT 'Y',N'韻' 
					                 UNION ALL SELECT 'Z',N'咗' 
		                  	) T  
		               WHERE word>=@word collate Chinese_PRC_CS_AS_KS_WS  
		               ORDER BY PY ASC 
		                      )  
		                  ELSE @word  
		             END) 
		SET @STR=RIGHT(@STR,len(@STR)-1) 
	END 
	RETURN @PY 
END 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


--实现通过表名得到功能名称 的函数  非单据主表与明细
--date    :2003-10-14
CREATE FUNCTION [dbo].[UF_OT_GetTableName]
(
	@table varchar(50)
)
returns  varchar(100)
AS 
BEGIN
	DECLARE @Name VARCHAR(100)
    SELECT @Name=CASE @table 
			WHEN 'BD_ARAP' THEN '往来账目'
			WHEN 'BD_Funds' THEN '科目余额'
			WHEN 'BD_OpeningStock' THEN '库存期初'
			WHEN 'BD_OpeningStock_Detail' THEN '库存期初'
			WHEN 'PD_GoodsStock' THEN '库存'
			WHEN 'PD_GoodsStock_Detail' THEN '库存'
			WHEN 'PD_PriceTrail' THEN '价格跟踪'
			WHEN 'SS_MonthBalance' THEN '月结账目'
			WHEN 'BD_Goods_DftWhs' THEN '商品默认仓位'
			WHEN 'BD_Employee' THEN '职员信息'
			WHEN 'SS_Operator' THEN '操作员'
			WHEN 'SS_Whs_Jur' THEN '仓库权限'
			WHEN 'PD_InOutWhsBill' THEN '其他出入库单'
			WHEN 'PD_InOutWhsDetail' THEN '其他出入库单'
			WHEN 'PD_LossSpillBill' THEN '报损报溢单'
			WHEN 'PD_LossSpillDetail' THEN '报损报溢单'
			WHEN 'MF_FeeRecDetail' THEN '收入费用单'
			WHEN 'MF_FeeRecBill' THEN '收入费用单'
			WHEN 'MF_ARAPDetail' THEN '往来调账单'
			WHEN 'MF_ARAPBill' THEN '往来调账单'
			WHEN 'MF_PayRecBill' THEN '收付款单'
			WHEN 'MF_PayRecDetail' THEN '收付款单'
			WHEN 'PD_InOutWhsBill_His' THEN '其他出入库单归档数据'
			WHEN 'PD_InOutWhsDetail_His' THEN '其他出入库单归档数据'
			WHEN 'PD_LossSpillBill_His' THEN '报损报溢单归档数据'
			WHEN 'PD_LossSpillDetail_His' THEN '报损报溢单归档数据'
			WHEN 'MF_FeeRecDetail_His' THEN '收入费用单归档数据'
			WHEN 'MF_FeeRecBill_His' THEN '收入费用单归档数据'
			WHEN 'MF_ARAPDetail_His' THEN '往来调账单归档数据'
			WHEN 'MF_ARAPBill_His' THEN '往来调账单归档数据'
			WHEN 'MF_PayRecBill_His' THEN '收付款单归档数据'
			WHEN 'OS_FreightBillAll' THEN '网店订单'
			WHEN 'OS_FreightBill' THEN '网店订单'
			WHEN 'OS_OrderBill' THEN '网店订单'
			WHEN 'OS_OrderBillALL' THEN '网店订单'
			WHEN 'OS_OrderDetail' THEN '网店订单'
			WHEN 'OS_OrderDetailALL' THEN '网店订单'
			WHEN 'OS_GoodsRelation' THEN '网店商品对应关系'
			WHEN 'OS_SyncStockWhs' THEN '网店配置-库存同步配置'
			WHEN 'SS_AuditSet' THEN '单据审核设置'
			WHEN 'SS_AuditSetDetail' THEN '单据审核设置'
			WHEN 'PD_BillAuditStep' THEN '单据审核设置'
			WHEN 'PD_GoodsSerial' THEN '序列号'
			ELSE @table--'未实现'
			END
	RETURN @name
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 sysobjects where id = object_id(N'[dbo].[UF_OT_GoodsPriceLimit]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[UF_OT_GoodsPriceLimit]
GO


--获取商品价格权限
--date    :2014-7-23
CREATE FUNCTION [dbo].[UF_OT_GoodsPriceLimit]
(
	@UserID Int = 0
)
returns @temp TABLE(PriceLvl INT)
AS 
BEGIN
declare @limitTb TABLE (
LimitID  INT
,pricelvl  INT
)


INSERT INTO @limitTb(limitid,pricelvl)
values
(1131010 , 1),
( 1131110 , 2),
( 1131210 , 3),
( 1131310 , 4),
( 1131410 , 5),
( 1132010 , 6),
( 1132110 , 7),
( 1132210 , 8),
( 1132310 , 9),
( 1132410 , 10),
( 1132510 , 11),
( 1132610 , 12),
( 1132710 , 13),
( 1132810 , 14),
( 1132910 , 15),
( 1131510 , 22),
( 1131610 , 23)	

if(@UserID <> 1)
begin

  INSERT @temp 
  SELECT l.pricelvl FROM ( 
	SELECT  sj.jurID 
	 FROM SS_Role_Jur  sj
			INNER JOIN  SS_Oper_Role so ON sj.RoleID=so.RoleID
	WHERE so.OperID=@UserID AND so.Stt=1 AND sj.opp=1  GROUP by sj.JurID
  )a 
 	  INNER JOIN @limitTb l ON l.LimitID=a.JurID
 
 
 
End					  
else
begin
	 INSERT @temp SELECT  pricelvl FROM @limitTb
end	
    RETURN 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


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
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


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
















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		Wangwei
-- Create date: 2014-05-04
-- Description:根据层数处理字符移位的长度
-- =============================================

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


CREATE FUNCTION [dbo].[UF_OT_StringReplace]
(
	@lvl INT,		--当前等级
	@fromlvl INT	--从第几级开始移位	
)
returns varchar(125) 
AS
BEGIN
	
	if(@lvl< @fromlvl) return ''
	 DECLARE @str varchar(125)

	 ,@len int
	  SET @str=''
	 DEClARE @i int 
	 SET @i=@fromlvl-1
	 WHILE @i<(@lvl)
	 begin
		SET @str=@str+' '+' '+' '+' '
		SET @i=@i+1
	 end
	return  @str
END
GO





/****** Object:  UserDefinedFunction [dbo].[UF_PD_GetBillStt]    Script Date: 07/01/2014 16:43:38 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UF_PD_GetBillStt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[UF_PD_GetBillStt]
GO


/****** Object:  UserDefinedFunction [dbo].[UF_PD_GetBillStt]    Script Date: 07/01/2014 16:43:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		liuke
-- Create date:  2014/07/01
-- Description:	 获取完成状态
-- =============================================
CREATE FUNCTION [dbo].[UF_PD_GetBillStt]
(	
	@BillNo INT,   --单据编号
	@Flag INT      --采购订单1，销售订单2，调拨申请单3
)
RETURNS INT
AS 
BEGIN
	DECLARE @Stt INT='' --单据状态
	IF @Flag=1 
	BEGIN
		IF EXISTS (SELECT 1 FROM PD_PchOrdBill b WHERE b.BillNo=@BillNo)
		BEGIN
			--Stt：2=已完成
			SELECT @Stt=CASE WHEN StopTag=1 THEN 2 ELSE 0 END FROM PD_PchOrdbill WHERE BillNo=@BillNo
			IF @Stt=2 RETURN @Stt 
			SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty>=BSQty THEN 1 ELSE 0 END)=COUNT(1) THEN 2 ELSE 0 END FROM PD_PchOrdDetail WHERE StopTag=0 AND BillNo=@BillNo 
			IF @Stt=2 RETURN @Stt 
			--Stt：0=未调用，1=部分调用
			SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty=0 THEN 1 ELSE 0 END)=COUNT(1) THEN 0 ELSE 1 END FROM PD_PchOrdDetail WHERE BillNo=@BillNo 
		END
		ELSE
		BEGIN
			RETURN 2
			----Stt：2=已完成
			--SELECT @Stt=CASE WHEN StopTag=1 THEN 2 ELSE 0 END FROM PD_PchOrdbill_His WHERE BillNo=@BillNo
			--IF @Stt=2 RETURN @Stt 
			--SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty>=BSQty THEN 1 ELSE 0 END)=COUNT(1) THEN 2 ELSE 0 END FROM PD_PchOrdDetail_His WHERE StopTag=0 AND BillNo=@BillNo 
			--IF @Stt=2 RETURN @Stt 
			----Stt：0=未调用，1=部分调用
			--SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty=0 THEN 1 ELSE 0 END)=COUNT(1) THEN 0 ELSE 1 END FROM PD_PchOrdDetail_His WHERE BillNo=@BillNo 
		END
	END
	
	ELSE IF @Flag=2
	BEGIN
		IF EXISTS (SELECT 1 FROM PD_SellOrdbill b WHERE b.BillNo=@BillNo)
		BEGIN
			--Stt：2=已完成
			SELECT @Stt=CASE WHEN StopTag=1 THEN 2 ELSE 0 END FROM PD_SellOrdbill WHERE BillNo=@BillNo
			IF @Stt=2 RETURN @Stt 
			SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty>=BSQty THEN 1 ELSE 0 END)=COUNT(1) THEN 2 ELSE 0 END FROM PD_SellOrdDetail WHERE StopTag=0 AND BillNo=@BillNo 
			IF @Stt=2 RETURN @Stt 
			--Stt：0=未调用，1=部分调用
			SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty=0 THEN 1 ELSE 0 END)=COUNT(1) THEN 0 ELSE 1 END FROM PD_SellOrdDetail WHERE BillNo=@BillNo 
		END
		ELSE
		BEGIN
			RETURN 2
			----Stt：2=已完成
			--SELECT @Stt=CASE WHEN StopTag=1 THEN 2 ELSE 0 END FROM PD_SellOrdbill_His WHERE BillNo=@BillNo
			--IF @Stt=2 RETURN @Stt 
			--SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty>=BSQty THEN 1 ELSE 0 END)=COUNT(1) THEN 2 ELSE 0 END FROM PD_SellOrdDetail_His WHERE StopTag=0 AND BillNo=@BillNo 
			--IF @Stt=2 RETURN @Stt 
			----Stt：0=未调用，1=部分调用
			--SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty=0 THEN 1 ELSE 0 END)=COUNT(1) THEN 0 ELSE 1 END FROM PD_SellOrdDetail_His WHERE BillNo=@BillNo 
		END
	END
	
	ELSE IF @Flag=3
	BEGIN
		IF EXISTS (SELECT 1 FROM PD_AllotReqBill b WHERE b.BillNo=@BillNo)
		BEGIN
			--Stt：2=已完成
			SELECT @Stt=CASE WHEN StopTag=1 THEN 2 ELSE 0 END FROM PD_AllotReqBill WHERE BillNo=@BillNo
			IF @Stt=2 RETURN @Stt 
			SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty>=BSQty THEN 1 ELSE 0 END)=COUNT(1) THEN 2 ELSE 0 END FROM PD_AllotReqDetail WHERE StopTag=0 AND BillNo=@BillNo 
			IF @Stt=2 RETURN @Stt 
			--Stt：0=未调用，1=部分调用
			SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty=0 THEN 1 ELSE 0 END)=COUNT(1) THEN 0 ELSE 1 END FROM PD_AllotReqDetail WHERE BillNo=@BillNo 
		END
		ELSE
		BEGIN
			RETURN 2
			----Stt：2=已完成
			--SELECT @Stt=CASE WHEN StopTag=1 THEN 2 ELSE 0 END FROM PD_AllotReqBill_His WHERE BillNo=@BillNo
			--IF @Stt=2 RETURN @Stt 
			--SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty>=BSQty THEN 1 ELSE 0 END)=COUNT(1) THEN 2 ELSE 0 END FROM PD_AllotReqDetail_His WHERE StopTag=0 AND BillNo=@BillNo 
			--IF @Stt=2 RETURN @Stt 
			----Stt：0=未调用，1=部分调用
			--SELECT @Stt=CASE WHEN SUM(CASE WHEN ComQty=0 THEN 1 ELSE 0 END)=COUNT(1) THEN 0 ELSE 1 END FROM PD_AllotReqDetail_His WHERE BillNo=@BillNo 
		END
	END
	RETURN @Stt 
END
GO






SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

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


--基础资料自定义字段配置
--date    :20015-6-24
CREATE PROCEDURE [dbo].[UP_BD_BaseInfoCustomItemQuery]
(
	@Type INT --类型 0=商品 1=往来单位
)

AS 
BEGIN
	DECLARE @CustomID INT=1
	CREATE TABLE #Used(CustomID INT,IfUsed INT)
	DECLARE @TableName VARCHAR(100),@sql NVARCHAR(4000)='',@ifUse INT=0
	IF @Type=0
		SET @TableName='BD_Goods_CustomVal'
	ELSE
		SET @TableName='BD_Btype_CustomVal'
	WHILE @CustomID<=5
	BEGIN
		SET @sql='IF EXISTS(SELECT 1 FROM '+@TableName+' WHERE CustVal'+CAST(@CustomID AS VARCHAR)+' <> '''') SELECT '+CAST(@CustomID AS VARCHAR)+', 1 ELSE SELECT '+CAST(@CustomID AS VARCHAR)+',0'
		--PRINT @sql
		INSERT INTO #Used
		EXEC(@sql)
		SET @CustomID+=1
	END
	
CREATE TABLE #Source(CustTypeID INT,TypeName VARCHAR(100) )
INSERT INTO #Source( CustTypeID, TypeName )
VALUES  ( 1, '商品信息' ),( 2,'往来单位' ),( 3, '仓库'  ),( 4, '部门' ),( 5,'职员' )

IF @Type=0
	SELECT CustItemID,'自定义字段'+CAST(CustItemID AS VARCHAR) CustItem ,CustItemName,IsShow,SourceType ,Source
	,CASE WHEN SourceType=2 then(SELECT TypeName FROM #Source s WHERE s.CustTypeID=c.Source)
		WHEN SourceType=3 then(SELECT TypeName FROM dbo.BD_Custom_Type s WHERE s.CustTypeID=c.Source)
	end as SourceName,IfUsed
	FROM dbo.BD_Goods_CustomItem c
	INNER JOIN #Used u ON u.CustomID=c.CustItemID 
ELSE
	SELECT CustItemID,'自定义字段'+CAST(CustItemID AS VARCHAR) CustItem ,CustItemName,IsShow,SourceType ,Source
	,CASE WHEN SourceType=2 then(SELECT TypeName FROM #Source s WHERE s.CustTypeID=c.Source)
		WHEN SourceType=3 then(SELECT TypeName FROM dbo.BD_Custom_Type s WHERE s.CustTypeID=c.Source)
	end as SourceName,IfUsed
	FROM dbo.BD_Btype_CustomItem c
	INNER JOIN #Used u ON u.CustomID=c.CustItemID 

DROP TABLE #Source,#Used

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 sysobjects where id = object_id(N'[dbo].[UP_BD_CheckUsed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop PROCEDURE [dbo].[UP_BD_CheckUsed]
GO


--实现检测基本信息是否被使用功能 的存储过程   函数中不能使用EXEC sp_executesql
--date    :20014-6-24
-- update 20150520商品删除检查排除OS_GoodsRelation的检查
CREATE PROCEDURE [dbo].[UP_BD_CheckUsed]
(
	@TypeID	INT,	
	@GoodsID INT=0,			--商品单位的判断才需要此字段
	@Type	varchar(2)		--B=往来单位 K=仓库  P=商品  PT=货位 E=职员 D=部门 F=科目 U=商品单位
)

AS 
BEGIN

DECLARE @BName VARCHAR(50)='',--基本信息字段名称 可以有多个，用','分割
		@RemoveTable VARCHAR(max)='',--需要排除的表 可以有多个，用','分割
		@Sql NVARCHAR(Max)='',
		@TableName VARCHAR(50)='' ,--使用到的表
		@UseName VARCHAR(100)='' --表对应的功能
IF @Type='B'
BEGIN
	SET @BName='BTypeID'
	SET @RemoveTable='BD_Btype,BD_Goods_NO,SS_Btype_Jur'
END
ELSE IF @Type='K'
BEGIN
	SET @BName='WhsID'
	SET @RemoveTable='BD_Whs,BD_Whs_Position,SS_Whs_Jur,PD_GoodsStock_Bound,OS_SyncStockWhs'
END
ELSE IF @Type='P'
BEGIN
	SET @BName='GoodsID'
	SET @RemoveTable='BD_Goods,BD_Goods_Graph,BD_Goods_Price,BD_Goods_NO,BD_Goods_DftWhs,PD_GoodsStock_Bound,OS_GoodsRelation'
END
ELSE IF @Type='PT'
BEGIN
	SET @BName='WhsPtID'
	SET @RemoveTable='BD_Whs_Position'
END
ELSE IF @Type='E'
BEGIN
	SET @BName='ElyID,Creator'
	SET @RemoveTable='BD_Employee,OT_GridColumnConfig,OT_GridColumnNewName'
END
ELSE IF @Type='D'
BEGIN
	SET @BName='DeptID'
	SET @RemoveTable='BD_Dept'
END
ELSE IF @Type='F'
BEGIN
	SET @BName='FinanceID'
	SET @RemoveTable='BD_Finance,SS_Finance_Jur'
END
ELSE IF @Type='U'
BEGIN
	SET @BName='UnitID'
	SET @RemoveTable='BD_Goods_Price,OS_GoodsRelation'
END
ElSE IF @Type='P1'
BEGIN
	SET @BName='PPT1ID'
	SET @RemoveTable='BD_Goods_Ppt1'
END
ElSE IF @Type='P2'
BEGIN
	SET @BName='PPT2ID'
	SET @RemoveTable='BD_Goods_Ppt2'
END

	

SELECT @Sql +=' IF Exists(Select top 1 1 from '+ o.[name]+' where @TypeID IN(SELECT typeid FROM dbo.UF_OT_Split_Int('+c.name+','','')a) '+CASE WHEN @Type='U' THEN ' AND GoodsID=@GoodsID' ELSE '' END+') BEGIN SELECT @TableName='''+o.[name] +''' RETURN END ' 
from sys.columns c  
INNER JOIN sys.objects o on(c.object_id=o.object_id) 
INNER JOIN dbo.UF_OT_Split(@BName,',') bc ON c.name LIKE '%'+bc.a
where o.type='u' AND NOT EXISTS(SELECT 1 FROM dbo.UF_OT_Split(@RemoveTable,',') r WHERE r.a=o.name) 
	and o.name<>'PD_ListTable'
	and o.name not like 'Woolinte%'
	
--SET @sql='IF '+STUFF(@sql,1,3,'')
--PRINT @Sql
EXEC sp_executesql @Sql,N'@TableName varchar(50) out,@TypeID int,@GoodsID int',@TableName OUT,@TypeID,@GoodsID

IF @TableName=''
BEGIN
	IF  EXISTS(SELECT 1 FROM OS_PostConfig p INNER JOIN dbo.UF_OT_Split(@BName,',') bc ON p.ConfigName LIKE '%'+bc.a WHERE ConfigValue=@TypeID)
		SELECT '网店配置'
	ELSE
		SELECT ''
	return 
END

IF @TableName NOT LIKE 'PD_InOutWhs%' AND @TableName NOT LIKE 'PD_LossSpill%' AND @TableName NOT LIKE 'MF_FeeRec%' AND @TableName NOT LIKE 'MF_ARAP%' AND  @TableName NOT LIKE 'MF_PayRec%'
begin
	SELECT @UseName=BillName FROM PD_BillType WHERE BillTable=@TableName OR BillDetail=@TableName --单据中使用
	IF @UseName<>''  
	BEGIN
		SELECT @UseName
		return 
	END

	SELECT @UseName=BillName FROM PD_BillType WHERE BillTable+'_His'=@TableName OR BillDetail+'_His'=@TableName --单据历史数据中使用	
	IF @UseName<>''  
	begin
		SELECT @UseName+'归档数据'
		return 
	end	
END
--在非单据中使用已经多单据共用一张表
SELECT  dbo.UF_OT_GetTableName(@TableName) 
--SELECT @TableName


			
	

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 sysobjects where id = object_id(N'[dbo].[UP_PD_QueryGoodsCustInfo]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop PROCEDURE [dbo].UP_PD_QueryGoodsCustInfo
GO


--基础资料自定义字段配置
--date    :20015-6-24
CREATE PROCEDURE [dbo].UP_PD_QueryGoodsCustInfo
(
	@GoodsIDStr VARCHAR(max) 
)

AS 
BEGIN
	DECLARE @sql VARCHAR(max)='',@feildsql VARCHAR(max)='',@joinsql VARCHAR(max)=''
	SELECT @joinsql+= CASE WHEN SourceType=1 THEN ' ' 
		WHEN SourceType=2 AND SOURCE=1 THEN ' LEFT JOIN BD_Goods G'+CAST(CustItemID AS VARCHAR)+' ON G'+CAST(CustItemID AS VARCHAR)+'.GoodsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=2 THEN ' LEFT JOIN BD_BType B'+CAST(CustItemID AS VARCHAR)+' ON B'+CAST(CustItemID AS VARCHAR)+'.BTypeID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=2 AND SOURCE=3 THEN ' LEFT JOIN BD_Whs W'+CAST(CustItemID AS VARCHAR)+' ON W'+CAST(CustItemID AS VARCHAR)+'.WhsID=C.CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=4 THEN ' LEFT JOIN BD_Dept D'+CAST(CustItemID AS VARCHAR)+' ON D'+CAST(CustItemID AS VARCHAR)+'.DeptID=C.CustVal'+CAST(CustItemID AS VARCHAR)  
		WHEN SourceType=2 AND SOURCE=5 THEN ' LEFT JOIN BD_Employee E'+CAST(CustItemID AS VARCHAR)+' ON E'+CAST(CustItemID AS VARCHAR)+'.ElyID=C.CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=3 THEN ' LEFT JOIN BD_Custom C'+CAST(CustItemID AS VARCHAR) +' ON C'+CAST(CustItemID AS VARCHAR) +'.CustID=C.CustVal'+CAST(CustItemID AS VARCHAR)     
		END,
		@feildsql += CASE WHEN SourceType=1 THEN ' ,C.CustVal'+CAST(CustItemID AS VARCHAR)     
		WHEN SourceType=2 AND SOURCE=1 THEN ' ,G'+CAST(CustItemID AS VARCHAR)+'.GoodsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=2 THEN ' ,B'+CAST(CustItemID AS VARCHAR)+'.BTypeName AS CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=2 AND SOURCE=3 THEN ' ,W'+CAST(CustItemID AS VARCHAR)+'.WhsName AS CustVal'+CAST(CustItemID AS VARCHAR)    
		WHEN SourceType=2 AND SOURCE=4 THEN ' ,D'+CAST(CustItemID AS VARCHAR)+'.DeptName AS CustVal'+CAST(CustItemID AS VARCHAR)  
		WHEN SourceType=2 AND SOURCE=5 THEN ' ,E'+CAST(CustItemID AS VARCHAR)+'.ElyName AS CustVal'+CAST(CustItemID AS VARCHAR)   
		WHEN SourceType=3 THEN ',C'+CAST(CustItemID AS VARCHAR) +'.CustName AS CustVal'+CAST(CustItemID AS VARCHAR)     
		END
FROM dbo.BD_Goods_CustomItem WHERE IsShow=1
SET @sql= 'SELECT C.BaseID GoodsID'+@feildsql+' FROM BD_Goods_CustomVal C ' + @joinsql+
		  ' WHERE C.BaseID IN('+@GoodsIDStr+')'

EXEC(@sql)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

 



GO
/*
升级数据处理

3.1

*/

--处理从3.1之前处理数据
IF EXISTS(SELECT 1 FROM D9ZTinfo WHERE CAST(RIGHT(LEFT(Version,4),3) AS DECIMAL(4,1))<3.1)
BEGIN 
	UPDATE PD_AllotBill SET InspectTag=1
	UPDATE PD_AllotBill_His SET InspectTag=1
	UPDATE PD_AllotDetail SET InspectQty=BSQty
	UPDATE PD_AllotDetail_his SET InspectQty=BSQty
	UPDATE PD_PchDetail SET InPrice=DiscPrice,InTotal=DiscTotal
	UPDATE PD_PchDetail_His SET InPrice=DiscPrice,InTotal=DiscTotal
END

/*===================================版本升级 3.0.0 - 3.1.0 Start============================================*/
 
--采购入库单删除字段FreightAmount
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill' AND a.Name='FreightAmount' AND c.name = 'decimal')
   AND EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill' AND a.Name='Freight' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchBill' AND so.xtype = 'D' AND so.name = 'DF_PD_PchBill_FreightAmount')
			ALTER TABLE PD_PchBill DROP CONSTRAINT [DF_PD_PchBill_FreightAmount]
		EXEC sp_executesql N'UPDATE PD_PchBill SET Freight = FreightAmount'
		ALTER TABLE PD_PchBill DROP COLUMN FreightAmount;
    END

--采购入库单历史表删除字段FreightAmount
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill_His' AND a.Name='FreightAmount' AND c.name = 'decimal')
   AND EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill_His' AND a.Name='Freight' AND c.name = 'decimal')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_PchBill_His_FreightAmount')
			ALTER TABLE PD_PchBill_His DROP CONSTRAINT [DF_PD_PchBill_His_FreightAmount]
		EXEC sp_executesql N'UPDATE PD_PchBill_His SET Freight = FreightAmount'
		ALTER TABLE PD_PchBill_His DROP COLUMN FreightAmount
    END
 
--采购入库单删除字段FreightSltTag
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill' AND a.Name='FreightSltTag' AND c.name = 'tinyint')
   AND EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill' AND a.Name='FreightStlTag' AND c.name = 'tinyint')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchBill' AND so.xtype = 'D' AND so.name = 'DF_PD_PchBill_FreightSltTag')
			ALTER TABLE PD_PchBill DROP CONSTRAINT [DF_PD_PchBill_FreightSltTag]
		EXEC sp_executesql N'UPDATE PD_PchBill SET FreightStlTag = FreightSltTag'
		ALTER TABLE PD_PchBill DROP COLUMN FreightSltTag;
    END

--采购入库单历史表删除字段FreightSltTag
IF EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill_His' AND a.Name='FreightSltTag' AND c.name = 'tinyint')
   AND EXISTS (SELECT a.Name FROM sys.columns a	INNER JOIN sys.objects	b ON a.object_id = b.object_id 
          INNER JOIN sys.types c ON a.system_type_id = c.system_type_id WHERE b.Name='PD_PchBill_His' AND a.Name='FreightStlTag' AND c.name = 'tinyint')
    BEGIN
		IF EXISTS (SELECT 1 FROM sysobjects so INNER JOIN sysconstraints sc ON so.id = sc.constid WHERE OBJECT_NAME(so.parent_obj) = 'PD_PchBill_His' AND so.xtype = 'D' AND so.name = 'DF_PD_PchBill_His_FreightSltTag')
			ALTER TABLE PD_PchBill_His DROP CONSTRAINT [DF_PD_PchBill_His_FreightSltTag]
		EXEC sp_executesql N'UPDATE PD_PchBill_His SET FreightStlTag = FreightSltTag'
		ALTER TABLE PD_PchBill_His DROP COLUMN FreightSltTag
    END

--预置业务草稿、经历历程 业务日期范围
DECLARE @CfgID INT = 4001
INSERT INTO SS_Role_Jur_Cfg(RoleID, CfgID, CfgValue )
SELECT r.RoleID, @CfgID, 0 
FROM SS_Role r WHERE NOT EXISTS(SELECT 1 FROM SS_Role_Jur_Cfg c 
WHERE c.CfgID = @CfgID AND c.RoleID = r.RoleID)

SET @CfgID = 4002
INSERT INTO SS_Role_Jur_Cfg( RoleID, CfgID, CfgValue ) 
SELECT r.RoleID, @CfgID, 0
FROM SS_Role r WHERE NOT EXISTS(SELECT 1 FROM SS_Role_Jur_Cfg c 
WHERE c.CfgID = @CfgID AND c.RoleID = r.RoleID)
/*===================================版本升级 3.0.0 - 3.1.0 End============================================*/




/*===================================版本升级 x - 3.2.0 Start============================================*/
IF EXISTS(SELECT 1 FROM D9ZTinfo WHERE CAST(RIGHT(LEFT(Version,4),3) AS DECIMAL(4,1))<3.2)
BEGIN
--商家编码生成规则为商品ID+属性ID+计量单位ID
UPDATE OS_OtherConfig SET ConfigValue = 2 WHERE ConfigID = 12
END
/*===================================版本升级 x - 3.2.0 End============================================*/

/*===================================版本升级 x - 3.3.0 Start============================================*/
IF EXISTS(SELECT 1 FROM D9ZTinfo WHERE CAST(RIGHT(LEFT(Version,4),3) AS DECIMAL(4,1))<3.3)
BEGIN
--已上传的商品，标记为网店商品
UPDATE BD_Goods SET IsOS = 1 WHERE IsUpload = 1
END
/*===================================版本升级 x - 3.3.0 End============================================*/

/*===================================版本升级 x - 3.5.0 Start============================================*/
IF EXISTS(SELECT 1 FROM D9ZTinfo WHERE CAST(RIGHT(LEFT(Version,4),3) AS DECIMAL(4,1))<3.5)
BEGIN
-- 处理原有订单生效状态为已生效
-- 采购订单/历史表
UPDATE PD_PchOrdBill SET IsDraft = 0
UPDATE PD_PchOrdBill_His SET IsDraft = 0
-- 销售订单/历史表
UPDATE PD_SellOrdBill SET IsDraft = 0
UPDATE PD_SellOrdBill_His SET IsDraft = 0
-- 调拨申请单/历史表
UPDATE PD_AllotReqBill SET IsDraft = 0
UPDATE PD_AllotReqBill_His SET IsDraft = 0 
END
/*===================================版本升级 x - 3.5.0 End============================================*/


/*===================================版本升级 x - 4.0.0 Start============================================*/
IF EXISTS(SELECT 1 FROM D9ZTinfo WHERE CAST(RIGHT(LEFT(Version,4),3) AS DECIMAL(4,1))<4.0)
BEGIN
ALTER TABLE dbo.OS_Company ALTER COLUMN AppKey			DECIMAL(20,0) NOT NULL
END
/*===================================版本升级 x - 4.0.0 End============================================*/

/*===================================版本升级 x - 4.1.0 Start============================================*/
IF EXISTS(SELECT 1 FROM D9ZTinfo WHERE CAST(RIGHT(LEFT(Version,4),3) AS DECIMAL(4,1))<4.1)
BEGIN
-- 单据明细右键功能权限设置默认勾选(往来单位详情、商品详情、库存分布、月度销售情况、历史售价)
INSERT INTO SS_Role_Jur (RoleID,JurID,opp) SELECT roleid,1810010,1 FROM SS_Role 
INSERT INTO SS_Role_Jur (RoleID,JurID,opp) SELECT roleid,1810110,1 FROM SS_Role 
INSERT INTO SS_Role_Jur (RoleID,JurID,opp) SELECT roleid,1810210,1 FROM SS_Role 
INSERT INTO SS_Role_Jur (RoleID,JurID,opp) SELECT roleid,1810310,1 FROM SS_Role 
INSERT INTO SS_Role_Jur (RoleID,JurID,opp) SELECT roleid,1810410,1 FROM SS_Role
END
/*===================================版本升级 x - 4.1.0 End============================================*/

if EXISTS(SELECT  1 FROM D9ZTInfo where ztSecret Is null)
BEGIN
	UPDATE d9ztinfo SET ztSecret=NEWID()
END


/*===================================版本升级 x - 4.3.0 End============================================*/
IF EXISTS(SELECT 1 FROM D9ZTinfo WHERE CAST(RIGHT(LEFT(Version,4),3) AS DECIMAL(4,1))<4.3)
BEGIN
	UPDATE dbo.BD_Finance SET Stt=1 WHERE Stt=2

	DECLARE @sql NVARCHAR(max)=''
	SELECT @sql+=
	'ALTER TABLE '+o.name+' DROP CONSTRAINT DF_'+o.name+'_InPutPrice
	ALTER TABLE '+o.name+'  ALTER COLUMN InPutPrice TINYINT NOT NULL
	ALTER TABLE '+o.name+' ADD CONSTRAINT DF_'+o.name+'_InPutPrice  DEFAULT (1) FOR InPutPrice
	' 
	FROM sys.columns c INNER JOIN sys.objects o ON c.object_id=o.object_id WHERE c.name='InPutPrice' 
	BEGIN TRANSACTION t1
	BEGIN TRY
		EXEC(@sql)
		COMMIT TRANSACTION t1
	END TRY 
	BEGIN CATCH
		ROLLBACK TRANSACTION t1
	END CATCH 
END
/*===================================版本升级 x - 4.3.0 End============================================*/

go
update OT_OtherConfig set [ConfigValue] = 'wx414b3a630bf6de4f' where [ConfigID] = 101
update OT_OtherConfig set [ConfigValue] = '1315483801' where [ConfigID] = 103

go



--版本号处理(放在最后)
UPDATE d9ztinfo SET [Version]='4.4.0_2016.04.18' ,ZTNumber=440

GO





---该脚本只支持440版本升级到500; 5.0版本之后将不在支持单独客户升级包
GO

--版本号处理(放在最后)
UPDATE d9ztinfo SET [Version]='V50020161001' ,ZTNumber=500

GO






---该脚本只支持500版本升级到510; 5.0版本之后将不在支持单独客户升级包
GO



--版本号处理(放在最后)
UPDATE d9ztinfo SET [Version]='V51020170601' ,ZTNumber=510

GO






---该脚本只支持500版本升级到510; 5.0版本之后将不在支持单独客户升级包
GO



--版本号处理(放在最后)
--UPDATE OT_otherConfig SET ConfigValue='V51020170601' where ConfigID=200 AND ConfigBelong=5
--UPDATE OT_otherConfig SET ConfigValue=510 where ConfigID=201 AND ConfigBelong=5
--UPDATE d9ztinfo SET [Version]='V51020170601' ,ZTNumber=510
--- 
UPDATE OT_otherConfig SET ConfigValue='V60020190624' where ConfigID=200 AND ConfigBelong=5
UPDATE OT_otherConfig SET ConfigValue=600 where ConfigID=201 AND ConfigBelong=5
UPDATE d9ztinfo SET [Version]='V60020190624' ,ZTNumber=600

GO




---该脚本只支持500版本升级到510; 5.0版本之后将不在支持单独客户升级包
GO



--版本号处理(放在最后)
--UPDATE OT_otherConfig SET ConfigValue='V51020170601' where ConfigID=200 AND ConfigBelong=5
--UPDATE OT_otherConfig SET ConfigValue=510 where ConfigID=201 AND ConfigBelong=5
--UPDATE d9ztinfo SET [Version]='V51020170601' ,ZTNumber=510
--- 
UPDATE OT_otherConfig SET ConfigValue='V61020190916' where ConfigID=200 AND ConfigBelong=5
UPDATE OT_otherConfig SET ConfigValue=610 where ConfigID=201 AND ConfigBelong=5
UPDATE d9ztinfo SET [Version]='V61020190916' ,ZTNumber=610

--执行D9Master中的脚本修改
UPDATE D9Master.dbo.D9AccountList SET VersionNo = 'V61020190916' where DbName = DB_NAME()

GO






---该脚本只支持500版本升级到510; 5.0版本之后将不在支持单独客户升级包
GO



--版本号处理(放在最后)
--UPDATE OT_otherConfig SET ConfigValue='V51020170601' where ConfigID=200 AND ConfigBelong=5
--UPDATE OT_otherConfig SET ConfigValue=510 where ConfigID=201 AND ConfigBelong=5
--UPDATE d9ztinfo SET [Version]='V51020170601' ,ZTNumber=510
--- 
UPDATE OT_otherConfig SET ConfigValue='V62020200316' where ConfigID=200 AND ConfigBelong=5
UPDATE OT_otherConfig SET ConfigValue=620 where ConfigID=201 AND ConfigBelong=5
UPDATE d9ztinfo SET [Version]='V62020200316' ,ZTNumber=610

--执行D9Master中的脚本修改
UPDATE D9Master.dbo.D9AccountList SET VersionNo = 'V62020200316' where DbName = DB_NAME()

GO







/************** 管家婆D9手机版 新装升级脚本 更新:20200309  **************/


/************** 脚本按顺序处理的步骤如下 **************/
---  (第一部分)  D9Master库，创建MdD9_UserPCInfo表
---  (第二部分)  D9Master库，表写预置数据（预留）
---（第三部分）账套库，创建数据表
---（第四部分）账套库，模板类表（先DROP再CREATE）
---（第五部分）账套库，模板表重写预置数据
---（第六部分）账套库，版本迭代库结构和数据升级
---（第七部分）账套库，配置和权限升级
---（第八部分）账套库，自定义数据类型创建升级（预留）
---（第九部分）账套库，函数、存储过程、视图删除
---（第十部分）账套库，函数、存储过程、视图创建（注意依赖先后关系）



/*****************************************************  (第一部分)  D9Master库，创建MdD9_UserPCInfo表 *****************************************************/

/****** Object:  Table D9Master.[dbo].[MdD9_UserPCInfo]    Script Date: 02/28/2020 18:29:09 ******/
IF NOT EXISTS(SELECT 1 FROM D9Master.dbo.sysobjects WHERE xtype='U' AND [name]='MdD9_UserPCInfo')
BEGIN
CREATE TABLE D9Master.[dbo].[MdD9_UserPCInfo](
	[SysID]		 BIGINT IDENTITY(1,1) NOT NULL ,--自增长ID
	[Virtual]	 VARCHAR(500)	DEFAULT '',	--虚拟目录
	[WXSerUrl]	 VARCHAR(500)	DEFAULT '',	--微信服务器URL
	[d9phonecode] VARCHAR(100)	DEFAULT '',	--D9PhoneCode
	[Compary]	 VARCHAR(1000)	DEFAULT '',	--公司名称
	[Industry]	 VARCHAR(50)	DEFAULT '',	--行业
	[Area]		 VARCHAR(50)	DEFAULT '',	--地区
	[Person]	 VARCHAR(50)	DEFAULT '',	--联系人
	[Mobile]	 VARCHAR(50)	DEFAULT '',	--联系人手机
	[PCUrl]		 VARCHAR(50)	DEFAULT '',	--PC服务器URL
	[PCPort]	 VARCHAR(50)	DEFAULT '',	--PC服务器端口
	[Comment]	 VARCHAR(500)	DEFAULT ''	--备注
);

END
GO

IF NOT EXISTS(SELECT 1 FROM D9Master.dbo.syscolumns scolumn,D9Master.dbo.sysobjects sobject
WHERE sobject.name='MdD9_UserPCInfo' and scolumn.id=sobject.id and scolumn.name='d9phonecode')
BEGIN

ALTER TABLE D9Master.[dbo].[MdD9_UserPCInfo] ADD [d9phonecode] VARCHAR(100)	DEFAULT '';
END
GO
UPDATE D9Master.dbo.MdD9_UserPCInfo SET d9phonecode='' WHERE d9phonecode IS NULL;
GO

/***************************************************** （第二部分）D9Master库，表写预置数据（预留） *****************************************************/



/***************************************************** （第三部分）账套库，创建数据表 *****************************************************/

/****** Object:  Table [dbo].[MdD9_UserSubmitAccount]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserSubmitAccount') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UserSubmitAccount](
	[SysID] [BIGINT] IDENTITY(1,1) NOT NULL,
	[LoginID] [VARCHAR](100) NULL DEFAULT '',	
	[UserID] [VARCHAR](100) NULL DEFAULT '',
	[AccountDate] [VARCHAR](100) NULL DEFAULT '',
	[DataType] [INT] NULL DEFAULT 0,
	[CreateTime] [VARCHAR](50) NULL DEFAULT CONVERT([VARCHAR](20),GETDATE(),121),
	[Explain] [VARCHAR](1000) NULL DEFAULT '',
	[Comment] [VARCHAR](1000) NULL DEFAULT ''
	);

/**创建索引*/
CREATE INDEX Index_MdD9_UserSubmitAccount_Main ON MdD9_UserSubmitAccount(UserID,AccountDate);

END
GO


/****** Object:  Table [dbo].[MdD9_UserSignData]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserSignData') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UserSignData](
	[SysID] [BIGINT] IDENTITY(1,1) NOT NULL,
	[SignType] [INT] NULL DEFAULT 0,
	[OffLine] [INT] NULL DEFAULT 0,
	[LoginID] [VARCHAR](100) NULL DEFAULT '',
	[LodeID] [VARCHAR](100) NULL DEFAULT '',
	[BTypeID] [VARCHAR](100) NULL DEFAULT '',
	[DeviceID] [VARCHAR](100) NULL DEFAULT '',
	[SignTime] [VARCHAR](50) NULL DEFAULT '',
	[Longitude] [VARCHAR](20) NULL DEFAULT '',
	[Latitude] [VARCHAR](20) NULL DEFAULT '',
	[Accuracy] [VARCHAR](20) NULL DEFAULT '',
	[Address] [VARCHAR](500) NULL DEFAULT '',
	[SignOutTime] [VARCHAR](50) NULL DEFAULT '',
	[SignOutLongitude] [VARCHAR](20) NULL DEFAULT '',
	[SignOutLatitude] [VARCHAR](20) NULL DEFAULT '',
	[SignOutAccuracy] [VARCHAR](20) NULL DEFAULT '',
	[SignOutAddress] [VARCHAR](500) NULL DEFAULT '',
	[SignOutComment] [VARCHAR](1000) NULL DEFAULT '',
	[Mileage] [NUMERIC](20, 2) NULL DEFAULT 0,
	[DayMileage] [NUMERIC](20, 2) NULL DEFAULT 0,
	[BetweenTime] [NUMERIC](20, 2) NULL DEFAULT 0,
	[LoadTime] [NUMERIC](20, 2) NULL DEFAULT 0,
	[Comment] [VARCHAR](1000) NULL DEFAULT ''
);

/**创建索引*/
CREATE INDEX Index_MdD9_UserSignData_LoginID ON MdD9_UserSignData(LoginID);
END
GO


/****** Object:  Table [dbo].[MdD9_UserRight]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserRight') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UserRight](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[LoginID] [VARCHAR](100) NULL DEFAULT '',
	[RightID] [VARCHAR](500) NULL DEFAULT '',
	[XiwaMaxTime] [VARCHAR](100) NULL DEFAULT ''
);

/**创建索引*/
CREATE INDEX Index_MdD9_UserRight_LoginID ON MdD9_UserRight(LoginID);
CREATE INDEX Index_MdD9_UserRight_RightID ON MdD9_UserRight(RightID);


SET IDENTITY_INSERT [dbo].[MdD9_UserRight] ON
INSERT [dbo].[MdD9_UserRight] ([Num], [LoginID], [RightID], [XiwaMaxTime] ) VALUES (1, N'1', N'1', CONVERT(VARCHAR(50),GETDATE(),121));
SET IDENTITY_INSERT [dbo].[MdD9_UserRight] OFF
END
GO



/****** Object:  Table [dbo].[MdD9_UserPriceLimit]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserPriceLimit') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UserPriceLimit](
	[LoginID] [NVARCHAR](150) NULL DEFAULT '',
	[PriceType] [NVARCHAR](150) NULL DEFAULT '',
	[FullName] [VARCHAR](100) NULL DEFAULT '',
	[XiwaMaxTime]  [VARCHAR](100) NULL DEFAULT ''
);

/**创建聚集索引*/
CREATE UNIQUE CLUSTERED INDEX Index_MdD9_UserPriceLimit_Main ON MdD9_UserPriceLimit(LoginID,PriceType);

END
GO





/****** Object:  Table [dbo].[MdD9_UserLimit]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserLimit') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UserLimit](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[Sort] [VARCHAR](120) NULL DEFAULT '',
	[SortNum] [VARCHAR](100) NULL DEFAULT '',
	[SortName] [VARCHAR](120) NULL DEFAULT '',
	[TypeID_] [VARCHAR](120) NOT NULL DEFAULT '',
	[LimitType] [NVARCHAR](120) NOT NULL DEFAULT '',
	[LimitName] [NVARCHAR](120) NULL DEFAULT '',
	[LimitValue] [INT] NULL DEFAULT 0,
	[Feld1] [VARCHAR](120) NULL DEFAULT '',
	[Feld2] [VARCHAR](120) NULL DEFAULT '',
	[Feld3] [VARCHAR](120) NULL DEFAULT '',
	[Feld4] [VARCHAR](120) NULL DEFAULT '',
	[Feld5] [VARCHAR](120) NULL DEFAULT '',
	[Deleted] [INT] NULL DEFAULT 0,
	[XiwaMaxTime]  [VARCHAR](100) NULL DEFAULT '',
	[Comment] [NVARCHAR](150) NULL DEFAULT ''
);

/**创建聚集索引*/
CREATE UNIQUE CLUSTERED INDEX Index_MdD9_UserLimit_Main ON MdD9_UserLimit(TypeID_,LimitType);

END
GO


/****** Object:  Table [dbo].[MdD9_User]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_User') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_User](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[SysType] [INT] NULL DEFAULT 0,
	[LoginID] [VARCHAR](100) NOT NULL,
	[LoginCode] [NVARCHAR](120) NULL DEFAULT '',
	[LoginName] [NVARCHAR](60) NULL DEFAULT '',
	[STypeID_] [VARCHAR](100) NULL DEFAULT '',
	[TypeID_] [VARCHAR](120) NULL DEFAULT '',
	[PassWord] [NVARCHAR](120) NULL DEFAULT '',
	[FullName] [NVARCHAR](120) NULL DEFAULT '',
	[ETypeID_] [VARCHAR](120) NULL DEFAULT '',
	[EFullName] [NVARCHAR](120) NULL DEFAULT '',
	[DefKTypeID] [VARCHAR](120) NULL DEFAULT '',
	[DefKTypeName] [NVARCHAR](120) NULL DEFAULT '',
	[DefKTypeIDIn] [VARCHAR](120) NULL DEFAULT '',
	[DefKTypeNameIn] [NVARCHAR](120) NULL DEFAULT '',
	[DefETypeID] [VARCHAR](120) NULL DEFAULT '',
	[DefETypeName] [NVARCHAR](120) NULL DEFAULT '',
	[WeiXinIsStop] [VARCHAR](10) NULL DEFAULT 0,
	[loginset] [VARCHAR](10) NULL DEFAULT 0,
	[IsStop] [INT] NULL DEFAULT 0,
	[Deleted] [INT] NULL DEFAULT 0,		
	[BindingPnoneMode] [VARCHAR](1500) NULL DEFAULT '',	
	[LimitGroupID] [VARCHAR](150) NULL DEFAULT '',
	[LimitAutoSync] [INT] NULL DEFAULT 0,
	[MoveBillOutKTypeID] [VARCHAR](1000) NULL DEFAULT '',
	[MoveBillOutKTypeName] [VARCHAR](1000) NULL DEFAULT '',
	[DistributionLoginID] [VARCHAR](50) NULL DEFAULT '',
	[LoginTimeControl] [VARCHAR](100) NULL DEFAULT '',
	[XiwaMaxTime]  [VARCHAR](100) NULL DEFAULT '',
	[Say] [NVARCHAR](120) NULL DEFAULT '',
	[Comment] [NVARCHAR](150) NULL DEFAULT ''
	);


SET IDENTITY_INSERT [dbo].[MdD9_User] ON
INSERT [dbo].[MdD9_User] ([Num], [SysType], [LoginID], [LoginName], [STypeID_], [TypeID_], [PassWord], [FullName], [ETypeID_], [EFullName], [DefKTypeID], [DefKTypeName], [DefKTypeIDIn], [DefKTypeNameIn], [DefETypeID], [DefETypeName], [IsStop], [Deleted], [LoginCode], [Say], [WeiXinIsStop], [loginset], [XiwaMaxTime] , [BindingPnoneMode], [Comment], [LimitGroupID], [LimitAutoSync], [MoveBillOutKTypeID], [MoveBillOutKTypeName], [DistributionLoginID], [LoginTimeControl]) 
VALUES (1, 1, N'1', N'超级管理员', N'', N'1', N'', N'超级管理员', N'1', N'超级管理员', N'', N'', N'', N'', N'', N'', 0, 0, N'1', N'', N'0', N'1', N'', N'', N'', N'', 0, N'', N'', N'', N'')
SET IDENTITY_INSERT [dbo].[MdD9_User] OFF
END
GO







/****** Object:  Table [dbo].[MdD9_UpLoadImage]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UpLoadImage') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UpLoadImage](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[BillId] [NVARCHAR](150) PRIMARY KEY NOT NULL,
	[Btypeid] [NVARCHAR](150) NULL DEFAULT '',
	[ImageTypeID] [NVARCHAR](150) NULL DEFAULT '',
	[Billdate] [NVARCHAR](150) NULL DEFAULT '',
	[DeviceID] [NVARCHAR](150) NULL DEFAULT '',
	[GPS] [NVARCHAR](150) NULL DEFAULT '',
	[Address] [NVARCHAR](150) NULL DEFAULT '',
	[ETypeid] [NVARCHAR](150) NULL DEFAULT '',
	[SignID] [NVARCHAR](150) NULL DEFAULT '',
	[zt] [NVARCHAR](150) NULL DEFAULT '',
	[Deleted] [VARCHAR](10) NULL DEFAULT '0',
	[IsStop] [VARCHAR](10) NULL DEFAULT '0',	
	[obgate1] [NVARCHAR](150) NULL DEFAULT '',
	[obgate2] [NVARCHAR](150) NULL DEFAULT '',
	[Comment] [NVARCHAR](150) NULL DEFAULT ''
);

/**创建索引*/
CREATE INDEX Index_MdD9_UpLoadImage_Btypeid ON MdD9_UpLoadImage(Btypeid);
CREATE INDEX Index_MdD9_UpLoadImage_DeviceID ON MdD9_UpLoadImage(DeviceID);
CREATE INDEX Index_MdD9_UpLoadImage_SignID ON MdD9_UpLoadImage(SignID);

END
GO

/****** Object:  Table [dbo].[MdD9_UpLoadImage_list]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UpLoadImage_List') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UpLoadImage_List](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[BillId] [NVARCHAR](150) NULL DEFAULT '',
	[ImageTypeID] [NVARCHAR](150) NULL DEFAULT '',
	[Times] [NVARCHAR](150) NULL DEFAULT '',
	[ImgIn] [VARCHAR](200) NULL DEFAULT '',
	[DetailRowID] [NVARCHAR](150) NULL DEFAULT '',	
	[Deleted] [VARCHAR](10) NULL DEFAULT '0',
	[IsStop] [VARCHAR](10) NULL DEFAULT '0',
	[obgate1] [NVARCHAR](150) NULL DEFAULT '',
	[obgate2] [NVARCHAR](150) NULL DEFAULT '',
	[Comment] [VARCHAR](500) NULL DEFAULT ''
);

/**创建索引*/
CREATE INDEX Index_MdD9_UpLoadImage_List_BillID ON MdD9_UpLoadImage_List(BillID);

END
GO



/****** Object:  Table [dbo].[MdD9_UpLoadImage_Reply]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UpLoadImage_Reply') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UpLoadImage_Reply](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[BillID] [VARCHAR](100) NULL DEFAULT '',
	[ImageTypeID] [VARCHAR](100) NULL DEFAULT '',
	[LoginID] [VARCHAR](100) NULL DEFAULT '',
	[DateTime] [VARCHAR](100) NULL DEFAULT CONVERT([VARCHAR](50),GETDATE(),121),
	[Content] [VARCHAR](8000) NULL DEFAULT '',
	[Deleted] [INT] NULL DEFAULT 0,
	[Comment] [VARCHAR](1000) NULL DEFAULT ''
);

/**创建索引*/
CREATE INDEX Index_MdD9_UpLoadImage_Reply_BillID ON MdD9_UpLoadImage_Reply(BillID);

END
GO


/****** Object:  Table [dbo].[MdD9_Units]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_Units') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_Units](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[UnitID_] [NVARCHAR](150) PRIMARY KEY NOT NULL,
	[UserCode] [NVARCHAR](150) NULL DEFAULT '',
	[FullName] [NVARCHAR](150) NULL DEFAULT '',
	[XiwaMaxTime]  [NVARCHAR](150) NULL DEFAULT CONVERT([VARCHAR](50),GETDATE(),121),
	[Comment] [NVARCHAR](150) NULL DEFAULT ''
);

END
GO



/****** Object:  Table [dbo].[MdD9_Sysdata]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_Sysdata') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_Sysdata](
	[SysID] [BIGINT] IDENTITY(1,1) NOT NULL,
	[SysValues] [INT] NULL DEFAULT 0,
	[TypeClass] [VARCHAR](120) NULL DEFAULT '',	
	[SortNum] [VARCHAR](100) NULL DEFAULT '',
	[ValueType] [VARCHAR](120) NULL DEFAULT '',
	[TypeName] [VARCHAR](200) NULL DEFAULT '',
	[FullName] [VARCHAR](200) NULL DEFAULT '',
	[ReadOnly] [INT] NOT NULL DEFAULT 0,
	[ENumValue] [VARCHAR](1000) NULL DEFAULT '',
	[MinValue] [VARCHAR](100) NULL DEFAULT '',
	[MaxValue] [VARCHAR](100) NULL DEFAULT '',
	[TypeValues] [VARCHAR](1000) NULL DEFAULT '',
	[TypeImage] [image] NULL,	
	[Feld1] [VARCHAR](100) NULL DEFAULT '',
	[Feld2] [VARCHAR](100) NULL DEFAULT '',	
	[Feld3] [VARCHAR](100) NULL DEFAULT '',	
	[Deleted] [INT] NULL DEFAULT 0,
	[XiwaMaxTime]  [VARCHAR](100) NULL DEFAULT CONVERT([VARCHAR](50),GETDATE(),121),
	[Say] [VARCHAR](500) NULL DEFAULT '',
	[Comment] [VARCHAR](500) NULL DEFAULT ''
	);

/**创建索引*/
CREATE INDEX Index_MdD9_Sysdata_TypeName ON MdD9_Sysdata(TypeName);
END
GO

/****** Object:  Table [dbo].[MdD9_Sysdata]    Script Date: 06/14/2019 11:25:09 ******/
UPDATE dbo.MdD9_Sysdata SET TypeValues=2 WHERE TypeName='TotalPoint'

/****** Object:  Table [dbo].[MdD9_RegisterUser]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_RegisterUser') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_RegisterUser](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[Guid] [VARCHAR](100) NULL DEFAULT '',
	[Imie] [VARCHAR](500) NULL DEFAULT '',
	[LoginID] [VARCHAR](500) NULL DEFAULT '',
	[UserName] [VARCHAR](500) NULL DEFAULT '',
	[UsePeople] [VARCHAR](500) NULL DEFAULT '',
	[PhoneType] [VARCHAR](500) NULL DEFAULT '',
	[UniqueNum] [VARCHAR](500) NULL DEFAULT '',
	[PhoneTel] [VARCHAR](500) NULL DEFAULT '',
	[LoginDate] [VARCHAR](50) NULL DEFAULT '',
	[Virtual] [VARCHAR](1000) NULL DEFAULT '',
	[UpID] [VARCHAR](100) NULL DEFAULT '',
	[IsStop] [VARCHAR](10) NULL DEFAULT '0',
	[Deleted] [VARCHAR](100) NULL DEFAULT '0'	
);

/**创建索引*/
CREATE INDEX Index_MdD9_RegisterUser_Imie ON MdD9_RegisterUser(Imie);
CREATE INDEX Index_MdD9_RegisterUser_LoginID ON MdD9_RegisterUser(LoginID);

END
GO


/****** Object:  Table [dbo].[MdD9_PTypeUnits]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_PTypeUnits') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_PTypeUnits](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[PTypeID_] [VARCHAR](150) NULL DEFAULT '',
	[UnitID_] [VARCHAR](150) NULL DEFAULT '',
	[UnitNum] [VARCHAR](150) NULL DEFAULT '',
	[UnitName] [VARCHAR](150) NULL DEFAULT '',
	[UnitRate] [VARCHAR](50) NULL DEFAULT '1',
	[RateType] [VARCHAR](150) NULL DEFAULT '',
	[UnitPrice] [VARCHAR](4000) NULL DEFAULT '',
	[IsDefault] [VARCHAR](10) NULL DEFAULT '0',
	[Comment] [VARCHAR](150) NULL DEFAULT ''
);

/**创建索引*/
CREATE INDEX Index_MdD9_PTypeUnits_PTypeUnitID ON MdD9_PTypeUnits(PTypeID_,UnitID_);

END
GO


/****** Object:  Table [dbo].[MdD9_PTypePrice]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_PTypePrice') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_PTypePrice](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[PTypeID_] [NVARCHAR](150) NULL DEFAULT '',
	[UnitID_] [NVARCHAR](150) NULL DEFAULT '',
	[PriceType] [NVARCHAR](150) NULL DEFAULT '',
	[Price] [NUMERIC](22, 8) NULL DEFAULT 0,
	[Comment] [NVARCHAR](150) NULL DEFAULT ''
);

/**创建聚集索引*/
CREATE UNIQUE CLUSTERED INDEX Index_MdD9_PTypePrice_Main ON MdD9_PTypePrice(PTypeID_,UnitID_,PriceType);

END
GO





/****** Object:  Table [dbo].[MdD9_LimitGroup]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_LimitGroup') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_LimitGroup](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[Id] [VARCHAR](100) NULL DEFAULT '',
	[LimitCode] [VARCHAR](100) NULL DEFAULT '',
	[LimitName] [VARCHAR](120) NULL DEFAULT '',
	[Deleted] [INT] NULL DEFAULT 0,
	[Comment] [VARCHAR](150) NULL DEFAULT '',
	[XiwaMaxTime] [VARCHAR](1000) NULL DEFAULT CONVERT([VARCHAR](50),GETDATE(),121)
);

END
GO


/****** Object:  Table [dbo].[MdD9_Latitude]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_Latitude') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_Latitude](
	[Btypeid] [NVARCHAR](150) NULL DEFAULT '',
	[Longitude] [VARCHAR](150) NULL DEFAULT '',
	[Latitude] [VARCHAR](150) NULL DEFAULT '',
	[XiwaMaxTime] [VARCHAR](1000) NULL DEFAULT CONVERT([VARCHAR](50),GETDATE(),121)
);

/**创建索引*/
CREATE INDEX Index_MdD9_Latitude_Main ON MdD9_Latitude(Btypeid);

END
GO




/****** Object:  Table [dbo].[MdD9_BillPayData]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_BillPayData') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_BillPayData](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[BillID] [VARCHAR](100) NULL DEFAULT '',
	[PayID] [VARCHAR](500) NULL DEFAULT '',
	[PayTotal] [NUMERIC](28, 6) NULL DEFAULT 0,
	[Comment] [VARCHAR](1000) NULL DEFAULT ''
	);
END
GO




/****** Object:  Table [dbo].[MdD9_Billindex]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_Billindex') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_Billindex](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[BillNumberID] [VARCHAR](100) PRIMARY KEY NOT NULL,
	[STypeID_] [VARCHAR](100) NULL DEFAULT '',
	[STypeID2_] [VARCHAR](100) NULL DEFAULT '',
	[LoginID] [VARCHAR](100) NULL DEFAULT '',
	[LoginName] [VARCHAR](100) NULL DEFAULT '',
	[UserTypeID] [VARCHAR](100) NULL DEFAULT '',
	[UserFullName] [VARCHAR](100) NULL DEFAULT '',
	[Billdate] [VARCHAR](100) NULL DEFAULT '',
	[LoginDate] [datetime] NULL,
	[ArriveDate] [datetime] NULL,
	[DeviceName] [VARCHAR](100) NULL DEFAULT '',
	[BillType] [VARCHAR](100) NULL DEFAULT '',
	[BillTypeID] [VARCHAR](100) NULL DEFAULT '',
	[BillName] [VARCHAR](100) NULL DEFAULT '',
	[BusineTypeID] [NVARCHAR](100) NULL DEFAULT '',
	[OrderCode] [NVARCHAR](100) NULL DEFAULT '',
	[IfEditBill] [NVARCHAR](100) NULL DEFAULT '',
	[VipCardID] [VARCHAR](400) NULL DEFAULT '',
	[BillCode] [VARCHAR](100) NULL DEFAULT '',
	[BillCheckID] [VARCHAR](100) NULL DEFAULT '',
	[BillCheckCode] [VARCHAR](100) NULL DEFAULT '',
	[BTypeID_] [VARCHAR](100) NULL DEFAULT '',
	[BTypeName] [VARCHAR](200) NULL DEFAULT '',
	[KTypeID_] [VARCHAR](100) NULL DEFAULT '',
	[KTypeName] [VARCHAR](100) NULL DEFAULT '',
	[KTypeID2_] [VARCHAR](100) NULL DEFAULT '',
	[KTypeName2] [VARCHAR](100) NULL DEFAULT '',
	[CargoID] [NVARCHAR](1000) NULL DEFAULT '',
	[CargoName] [NVARCHAR](1000) NULL DEFAULT '',
	[CargoID2] [NVARCHAR](1000) NULL DEFAULT '',
	[CargoName2] [NVARCHAR](1000) NULL DEFAULT '',
	[ETypeID_] [VARCHAR](100) NULL DEFAULT '',
	[ETypeName] [VARCHAR](100) NULL DEFAULT '',
	[DTypeID_] [VARCHAR](100) NULL DEFAULT '',
	[DTypeName] [VARCHAR](100) NULL DEFAULT '',
	[BarterType] [VARCHAR](300) NULL DEFAULT '0',
	[PreferenceMoney] [NUMERIC](20, 8) NULL DEFAULT 0,
	[PayATypeID_] [VARCHAR](100) NULL DEFAULT '',
	[PayATypeName] [VARCHAR](100) NULL DEFAULT '',
	[PayMoney] [VARCHAR](200) NULL DEFAULT '0',
	[PriceTrack] [VARCHAR](2) NULL DEFAULT '0',
	[DlySumQty] [NUMERIC](28, 8) NULL DEFAULT 0,
	[DlySumTotal] [NUMERIC](28, 8) NULL DEFAULT 0,
	[State] [INT] NULL DEFAULT 0,
	[Vchcode] [NUMERIC](20, 0) NULL DEFAULT 0,
	[PHID] [NVARCHAR](50) NULL DEFAULT '',
	[PosID] [NVARCHAR](100) NULL DEFAULT '',
	[DetailCounts] [INT] NULL DEFAULT 0,
	[JsState] [INT] NULL DEFAULT 0,
	[JsTotal] [NUMERIC](28, 8) NULL DEFAULT 0,
	[BillGuid] [VARCHAR](100) NULL DEFAULT '',
	[Size] [VARCHAR](100) NULL DEFAULT '',
	[Pictuers] [image] NULL,
	[BillImage2] [image] NULL,
	[BillImage3] [image] NULL,
	[BillImage] [image] NULL,
	[SaveTime] [NVARCHAR](200) NULL,
	[Deleted] [INT] NULL DEFAULT 0,
	[Feld2] [VARCHAR](200) NULL DEFAULT '',
	[Comment] [VARCHAR](300) NULL DEFAULT ''
	);

END
GO



/****** Object:  Table [dbo].[MdD9_Billindex_List]    Script Date: 06/14/2019 11:25:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_Billindex_List') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_Billindex_List](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[BillNumberID] [VARCHAR](100) NOT NULL DEFAULT '',
	[DetailRowID] [INT] NULL DEFAULT 0,
	[STypeID_] [VARCHAR](100) NULL DEFAULT '',
	[IsPayAType] [NUMERIC](12, 0) NULL DEFAULT 0,
	[DetailType] [NVARCHAR](100) NULL DEFAULT '0',
	[UsedType] [NVARCHAR](100) NULL DEFAULT '0',
	[PTypeID_] [VARCHAR](100) NULL DEFAULT '',
	[PTypeUserCode] [VARCHAR](100) NULL DEFAULT '',
	[PTypeName] [VARCHAR](1000) NULL DEFAULT '',
	[KTypeID_] [VARCHAR](100) NULL DEFAULT '',
	[KTypeID2_] [VARCHAR](100) NULL DEFAULT '',
	[UnitID_] [VARCHAR](100) NULL DEFAULT '',
	[UnitNum] [VARCHAR](100) NULL DEFAULT '0',
	[UnitName] [VARCHAR](100) NULL DEFAULT '',
	[UnitRate] [NUMERIC](20, 8) NULL DEFAULT 1,
	[PDAQty] [NUMERIC](20, 4) NULL DEFAULT 0,
	[PDAPrice] [NUMERIC](28, 8) NULL DEFAULT 0,
	[PDADiscount] [NUMERIC](28, 8) NULL DEFAULT 1,
	[PDADistPrice] [NUMERIC](28, 8) NULL DEFAULT 0,
	[DistTotal] [NVARCHAR](1000) NULL DEFAULT '0',
	[PreferenTotal] [NVARCHAR](200) NULL DEFAULT '0',
	[Serial] [VARCHAR](8000) NULL DEFAULT '',
	[GoodsNumber] [NVARCHAR](120) NULL DEFAULT '',
	[ProduceDate] [NVARCHAR](120) NULL DEFAULT '',
	[ValidDate] [NVARCHAR](120) NULL DEFAULT '',
	[GoodSorder] [NVARCHAR](1000) NULL DEFAULT '',
	[Stockuniqueid] [NVARCHAR](1000) NULL DEFAULT '',
	[CostPrice] [NUMERIC](28, 8) NULL DEFAULT 0,
	[StockQty] [NUMERIC](28, 8) NULL DEFAULT 0,	
	[RetailPrice] [NUMERIC](28, 8) NULL DEFAULT 0,
	[OrderCode] [VARCHAR](100) NULL DEFAULT '',
	[OrderID] [NVARCHAR](100) NULL DEFAULT '',
	[OrderDlyID] [VARCHAR](100) NULL DEFAULT '',
	[OrderBakID] [VARCHAR](100) NULL DEFAULT '',
	[UnitPrice] [NUMERIC](28, 8) NULL DEFAULT 0,	
	[Discount] [NUMERIC](28, 8) NULL DEFAULT 1,
	[BillQTY] [NUMERIC](28, 8) NULL DEFAULT 0,
	[BillPrice] [NUMERIC](28, 8) NULL DEFAULT 0,
	[BillDistPrice] [NUMERIC](28, 8) NULL DEFAULT 0,
	[BillTotal] [NUMERIC](28, 8) NULL DEFAULT 0,
	[BillDistTotal] [NUMERIC](28, 8) NULL DEFAULT 0,
	[TaxRate] [NUMERIC](28, 8) NULL DEFAULT 0,
	[Tax] [NUMERIC](28, 4) NULL DEFAULT 0,
	[TaxTotal] [NUMERIC](28, 8) NULL DEFAULT 0,
	[PriceTrack] [NVARCHAR](2) NULL DEFAULT 0,
	[DlyOrder] [NVARCHAR](100) NULL DEFAULT '',	
	[ParBarcode] [NVARCHAR](3500) NULL DEFAULT '',	
	[Unit2Rate] [NUMERIC](28, 8) NULL DEFAULT 1,
	[PackQty] [NVARCHAR](3500) NULL DEFAULT '0',
	[Feld1] [NVARCHAR](3500) NULL DEFAULT '',
	[Feld2] [NVARCHAR](3500) NULL DEFAULT '',	
	[Feld3] [NVARCHAR](100) NULL DEFAULT '',	
	[Comment] [VARCHAR](300) NULL DEFAULT ''
	);

/**创建索引*/
CREATE INDEX Index_BillindexList_BillNumberID ON MdD9_Billindex_List(BillNumberID);
CREATE INDEX Index_BillindexList_PTypeID_ ON MdD9_Billindex_List(PTypeID_);
CREATE INDEX Index_BillindexList_KTypeID_ ON MdD9_Billindex_List(KTypeID_);

END
GO


/****** Object:  Table [dbo].[MdD9_UserSmallPro]    Script Date: 02/28/2020 18:29:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserSmallPro') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UserSmallPro](
	[SysID]		 BIGINT IDENTITY(1,1) NOT NULL ,--自增长ID
	[LoginID]	 VARCHAR(50)	NULL DEFAULT '',--对应操作员ID
	[PassWord]	 VARCHAR(1000)	NULL DEFAULT '',--小程序密码
	[Person]	 VARCHAR(50)	NULL DEFAULT '',--使用人
	[Mobile]	 VARCHAR(50)	NULL DEFAULT '',--使用人手机
	[State]		 VARCHAR(50)	NULL DEFAULT '',--状态：0正常
	[CreateTime] VARCHAR(50)	NULL DEFAULT CONVERT(VARCHAR(50),GETDATE(),121),--创建时间,yyyy-MM-dd HH:mm:ss
	[Comment]	 VARCHAR(500)	NULL DEFAULT ''--备注
);

END
GO


/****** Object:  Table [dbo].[MdD9_UserWeChat]    Script Date: 02/28/2020 18:29:09 ******/
IF NOT EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserWeChat') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[MdD9_UserWeChat](
	[SysID]		 VARCHAR(100)	NOT NULL, --唯一标识符GUID
	[WeChatID]	 VARCHAR(100)	NULL DEFAULT '',	  --微信ID
	[LoginID]	 VARCHAR(50)	NULL DEFAULT '',	  --对应操作员ID
	[Mobile]	 VARCHAR(50)	NULL DEFAULT '',	  --使用人手机
	[Person]	 VARCHAR(50)	NULL DEFAULT '',	  --使用人
	[State]		 VARCHAR(50)	NULL DEFAULT '',	  --状态：0正常
	[CreateTime] VARCHAR(50)	NULL DEFAULT CONVERT(VARCHAR(50),GETDATE(),121),	  --创建时间,yyyy-MM-dd HH:mm:ss
	[Comment]	 VARCHAR(50)	NULL DEFAULT ''	  --备注
);
END
GO




/***************************************************** （第四部分）账套库，模板类表（先DROP再CREATE） *****************************************************/


/****** Object:  Table [dbo].[MdD9_PriceType]  价格类型表（存在先DROP在CREATE）  Script Date: 06/14/2019 11:25:09 ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_PriceType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

DROP TABLE MdD9_PriceType;
END
GO


CREATE TABLE [dbo].[MdD9_PriceType](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[PriceTypeID] [NVARCHAR](150) NULL DEFAULT '',
	[PriceType] [NVARCHAR](150) NULL DEFAULT '',
	[PriceName] [NVARCHAR](150) NULL DEFAULT '',
	[Type] [NVARCHAR](150) NULL DEFAULT '',
	[SaleOrBuy] [NVARCHAR](150) NULL DEFAULT '',
	[FullName] [NVARCHAR](150) NULL DEFAULT '',
	[IsUsed] [NVARCHAR](150) NULL DEFAULT '',
	[isDiscount] [NVARCHAR](100) NULL DEFAULT '0',
	[Comment] [NVARCHAR](150) NULL DEFAULT ''
);
GO

/**创建索引*/
CREATE INDEX Index_MdD9_PriceType_PriceType ON MdD9_PriceType(PriceType);
GO



/****** Object:  Table [dbo].[MdD9_SysdataType] 系统模板表（存在先DROP在CREATE）   Script Date: 06/14/2019 11:25:09 ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_SysdataType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

DROP TABLE MdD9_SysdataType;

END
GO


CREATE TABLE [dbo].[MdD9_SysdataType](
	[SysID] [BIGINT] IDENTITY(1,1) NOT NULL,
	[STypeID_] [VARCHAR](100) NULL DEFAULT '',
	[SysValues] [INT] NULL DEFAULT 0,
	[SortNum] [VARCHAR](100) NULL DEFAULT '',
	[ReadOnly] [INT] NOT NULL DEFAULT 0,
	[TypeClass] [VARCHAR](120) NULL DEFAULT '',	
	[TypeName] [VARCHAR](200) PRIMARY KEY NOT NULL,
	[FullName] [VARCHAR](200) NULL DEFAULT '',
	[ValueType] [VARCHAR](120) NULL DEFAULT '',	
	[ENumValue] [VARCHAR](1000) NULL DEFAULT '',
	[MinValue] [VARCHAR](100) NULL DEFAULT '',
	[MaxValue] [VARCHAR](100) NULL DEFAULT '',
	[TypeValues] [VARCHAR](1000) NULL,
	[TypeImage] [image] NULL,	
	[Feld1] [VARCHAR](100) NULL DEFAULT '',
	[Feld2] [VARCHAR](100) NULL DEFAULT '',
	[Feld3] [VARCHAR](100) NULL DEFAULT '',
	[Deleted] [INT] NULL DEFAULT 0,
	[Say] [VARCHAR](500) NULL DEFAULT '',
	[Comment] [VARCHAR](500) NULL DEFAULT ''
	);
GO



GO




/****** Object:  Table [dbo].[MdD9_UserLimitType]   权限模板表（存在先DROP在CREATE）  Script Date: 06/14/2019 11:25:09 ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserLimitType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

DROP TABLE [dbo].[MdD9_UserLimitType];

END
GO

CREATE TABLE [dbo].[MdD9_UserLimitType](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[Sort] [VARCHAR](120) NULL DEFAULT '',
	[SortName] [VARCHAR](120) NULL DEFAULT '',
	[SortNum] [VARCHAR](100) NULL DEFAULT '',
	[LimitType] [NVARCHAR](120) PRIMARY KEY NOT NULL,
	[LimitName] [NVARCHAR](120) NULL DEFAULT '',
	[LimitValue] [INT] NULL DEFAULT 0,
	[IsUsed] [INT] NULL DEFAULT 0,
	[Deleted] [INT] NULL DEFAULT 0,
	[Feld1] [VARCHAR](120) NULL DEFAULT '',
	[Feld2] [VARCHAR](120) NULL DEFAULT '',
	[Feld3] [VARCHAR](120) NULL DEFAULT '',
	[Feld4] [VARCHAR](120) NULL DEFAULT '',
	[Feld5] [VARCHAR](120) NULL DEFAULT '',
	[Comment] [NVARCHAR](150) NULL DEFAULT ''	
);
GO



/****** Object:  Table [dbo].[MdD9_BillName]    单据类型表（存在先DROP在CREATE） Script Date: 06/14/2019 11:25:09 ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_BillName') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

DROP TABLE [dbo].[MdD9_BillName];

END
GO


CREATE TABLE [dbo].[MdD9_BillName](
	[SysID] [BIGINT] IDENTITY(1,1) NOT NULL,
	[BillType] [VARCHAR](120) PRIMARY KEY NOT NULL,
	[BillTypeID] [VARCHAR](120) NULL DEFAULT '',
	[BillName] [VARCHAR](120) NULL DEFAULT '',
	[BillHead] [VARCHAR](120) NULL DEFAULT '',
	[SourceBillType] [VARCHAR](120) NULL DEFAULT '',
	[ToBillType] [VARCHAR](120) NULL DEFAULT '',
	[FillBillType] [VARCHAR](120) NULL DEFAULT '',
	[Type] [VARCHAR](120) NULL DEFAULT '',
	[TypeName] [VARCHAR](120) NULL DEFAULT '',
	[InOutType] [VARCHAR](120) NULL DEFAULT '',
	[Deleted] [INT] NULL DEFAULT 0,
	[Say] [NVARCHAR](200) NULL DEFAULT '',
	[Comment] [NVARCHAR](200) NULL DEFAULT ''
	);
GO



/****** Object:  Table [dbo].[MdD9_ImageType]  照片类型表（存在先DROP在CREATE）  Script Date: 06/14/2019 11:25:09 ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_ImageType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

DROP TABLE [dbo].[MdD9_ImageType];

END
GO

CREATE TABLE [dbo].[MdD9_ImageType](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[SysType] [INT] NULL DEFAULT 0,
	[TypelId] [NVARCHAR](150) PRIMARY KEY NOT NULL,
	[Typeusercode] [NVARCHAR](150) NULL DEFAULT '',
	[Typename] [VARCHAR](200) NULL DEFAULT '',
	[SortNum] [INT] NULL DEFAULT 0,
	[Deleted] [NVARCHAR](150) NULL DEFAULT '0',
	[IsStop] [NVARCHAR](150) NULL DEFAULT '0',
	[obgate1] [NVARCHAR](150) NULL DEFAULT '',
	[obgate2] [NVARCHAR](150) NULL DEFAULT '',
	[Comment] [NVARCHAR](150) NULL DEFAULT ''
);


GO





/****** Object:  Table [dbo].[MdD9_PricePriority]  价格优先级表（存在先DROP在CREATE）  Script Date: 06/14/2019 11:25:09 ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_PricePriority') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

DROP TABLE [dbo].[MdD9_PricePriority];
END
GO

CREATE TABLE [dbo].[MdD9_PricePriority](
	[Num] [BIGINT] IDENTITY(1,1) NOT NULL,
	[PriceKey] [VARCHAR](100) PRIMARY KEY DEFAULT '',
	[PriceName] [VARCHAR](120) NULL DEFAULT '',
	[Sort] [NVARCHAR](120) NULL DEFAULT '',
	[Comment] [NVARCHAR](200) NULL DEFAULT ''
)
GO





/***************************************************** （第五部分）账套库，模板表重写预置数据 *****************************************************/


/****** Object:  Table [dbo].[MdD9_PriceType]    价格类型表(清空重写) ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_PriceType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

TRUNCATE TABLE [dbo].[MdD9_PriceType];

INSERT [dbo].[MdD9_PriceType] ([PriceTypeID], [PriceType], [PriceName], [Type], [SaleOrBuy], [FullName], [IsUsed], [isDiscount], [Comment]) 
VALUES ( N'Price1', N'Price1', N'Price1', N'', N'Sale', N'预设价1', N'', N'', N'');
INSERT [dbo].[MdD9_PriceType] ([PriceTypeID], [PriceType], [PriceName], [Type], [SaleOrBuy], [FullName], [IsUsed], [isDiscount], [Comment]) 
VALUES ( N'Price2', N'Price2', N'Price2', N'', N'Sale', N'预设价2', N'', N'', N'');
INSERT [dbo].[MdD9_PriceType] ([PriceTypeID], [PriceType], [PriceName], [Type], [SaleOrBuy], [FullName], [IsUsed], [isDiscount], [Comment]) 
VALUES ( N'Price3', N'Price3', N'Price3', N'', N'Sale', N'预设价3', N'', N'', N'');
INSERT [dbo].[MdD9_PriceType] ([PriceTypeID], [PriceType], [PriceName], [Type], [SaleOrBuy], [FullName], [IsUsed], [isDiscount], [Comment]) 
VALUES ( N'Price4', N'Price4', N'Price4', N'', N'Sale', N'预设价4', N'', N'', N'');
INSERT [dbo].[MdD9_PriceType] ([PriceTypeID], [PriceType], [PriceName], [Type], [SaleOrBuy], [FullName], [IsUsed], [isDiscount], [Comment]) 
VALUES ( N'Price5', N'Price5', N'Price5', N'', N'Sale', N'预设价5', N'', N'', N'');
--INSERT [dbo].[MdD9_PriceType] ([PriceTypeID], [PriceType], [PriceName], [Type], [SaleOrBuy], [FullName], [IsUsed], [isDiscount], [Comment])
--VALUES ( N'RetailPrice', N'RetailPrice', N'RetailPrice', N'DefaultBuyPrice', N'Sale', N'零售价', N'', N'', N'');


END
GO





/****** Object:  Table [dbo].[MdD9_SysdataType]    系统配置项表(清空重写) ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_SysdataType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

TRUNCATE TABLE [dbo].[MdD9_SysdataType];

INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'ZtUnique', N'帐套唯一值', N'', N'0CD9702B-2C06-441D-86AD-185D6EB1EC43', N'PDA提交单据,帐套一致性判断', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'SqlDbs', N'MDD9对接SQL数据库名', N'', N'HH130190518', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'EditionType', N'MDD9对软件版本', N'', N'HHIIOrTop130', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'SerVer', N'服务器程序的版本', N'', N'V6.2.0', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'SerEdition', N'服务器程序的版本号日期', N'', N'2019.04.29', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'SqlProcedureVer', N'服务器存储过程版本', N'', N'', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'SqlProcedureEdition', N'服务器存储过程版本号', N'', N'', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'UserEditionType', N'版本类型', N'', N'Normal', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'IFNOT', 0, N'UserPower', N'启用基本信息授权控制', N'', N'否', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'DbDateTimer', N'数据包生成时间', N'', N'', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'A服务器隐藏配置', 19, N'Char', 0, N'RegisterHardWareInfo', N'电脑唯一值', N'', N'7071F492DD5FF81E5B12500B160DBA47B5E1FA3D7AE28B213FC8A0A773E104D7', N'', N'', N'', N'', N'', N'', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'业务录单配置', 1, N'INT', 0, N'QtyPoint', N'数量小数位', N'', N'2', N'', N'', N'', N'', N'', N'10', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'业务录单配置', 1, N'INT', 0, N'PricePoint', N'单价小数位', N'', N'4', N'', N'', N'', N'', N'', N'11', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'业务录单配置', 1, N'INT', 0, N'DiscountPoint', N'折扣小数位', N'', N'4', N'', N'', N'', N'', N'', N'12', NULL, NULL, NULL, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'业务录单配置', 1, N'INT', 0, N'TotalPoint', N'金额小数位', N'', N'2', N'', N'', N'', N'', N'', N'13', NULL, NULL, NULL, 1);
--AddDate：2020年2月17日  By:MYX
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'业务录单配置', 1, N'IMAGE', 0, N'QrCodeAlipay', N'支付宝收款二维码', N'', N'', N'', N'', N'', N'', N'', N'14', NULL, 0, 0, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'业务录单配置', 1, N'IMAGE', 0, N'QrCodeWeChat', N'微信收款二维码', N'', N'', N'', N'', N'', N'', N'', N'15', NULL, 0, 0, 0);
INSERT [dbo].[MdD9_SysdataType] ([STypeID_], [TypeClass], [SysValues], [ValueType], [Deleted], [TypeName], [FullName], [ENumValue], [TypeValues], [Comment], [Say], [Feld1], [Feld2], [Feld3], [SortNum], [TypeImage], [MinValue], [MaxValue], [ReadOnly]) VALUES (N'', N'业务录单配置', 1, N'IfNot', 0, N'SubmitBillSendMessageToAllUser', N'提交单据时发送消息', N'', N'否', N'', N'', N'', N'', N'', N'16', NULL, 0, 0, 0);



END
GO



/****** Object:  Table [dbo].[MdD9_UserLimitType]    用户权限表(清空重写) ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_UserLimitType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

TRUNCATE TABLE [dbo].[MdD9_UserLimitType];


INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'AllowDiscount', N'开单允许打折', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'14');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'AllowGive', N'开单允许赠送', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'15');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'AllUserBillLimit', N'允许查看所有制单人单据', 0, 1, 0, N'不勾选：只能看到自己开的单据，以制单人为统计依据', N'', N'', N'', N'', N'', N'27');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'C', N'报表', N'AType', N'现金银行', 0, 1, 0, N'在线查询资金余额', N'', N'', N'', N'', N'', N'3');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'D', N'外勤', N'BaiduSign', N'位置上报', 0, 1, 0, N'业务员手工上报位置信息', N'', N'', N'', N'', N'', N'1');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'BillDateModify', N'允许修改开单日期', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'12');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'BillPrintDelete', N'允许打印后删除单据', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'25');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F', N'其他权限', N'BTypeAccount', N'查询单位往来账款', 0, 1, 0, N'设置往来单位应收应付的显示', N'', N'', N'', N'', N'', N'8');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'C', N'报表', N'BTypeApArReport', N'应收应付', 0, 1, 0, N'在线查询往来欠款余额', N'', N'', N'', N'', N'', N'2');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'B', N'信息', N'BTypeInfo', N'单位档案', 0, 1, 0, N'查询往来单位详细资料信息', N'', N'', N'', N'', N'', N'5');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'Buy', N'进货开单', 0, 1, 0, N'到货后，把货物实际入库', N'', N'', N'', N'', N'', N'3');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'BuyBack', N'进货退货', 0, 1, 0, N'把货退给厂家', N'', N'', N'', N'', N'', N'4');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'BuyOrder', N'进货订单', 0, 1, 0, N'记录向厂家订货信息', N'', N'', N'', N'', N'', N'2');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'CashBill', N'现金费用', 0, 1, 0, N'处理现金类报销的费用', N'', N'', N'', N'', N'', N'15');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'ChangePrice', N'修改单价权限', 0, 1, 0, N'勾选：可以修改单价；不勾选：单价无法修改', N'', N'', N'', N'', N'', N'19');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'CollectionBill', N'收款单', 0, 1, 0, N'收客户此前欠款', N'', N'', N'', N'', N'', N'13');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F', N'其他权限', N'Cost', N'成本查看', 0, 1, 0, N'影响进货类单据开单、库存报表单价和金额的显示', N'', N'', N'', N'', N'', N'1');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F', N'其他权限', N'FarDayinSet', N'打印配置', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'11');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'MoneyBill', N'一般费用', 0, 1, 0, N'处理与客户相关的费用', N'', N'', N'', N'', N'', N'17');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'NotPullDownPrice', N'允许开单时下拉单价', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'16');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'OtherOutBill', N'其它出库', 0, 1, 0, N'把货出给客户但不影响账款', N'', N'', N'', N'', N'', N'10');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'PayBill', N'付款单', 0, 1, 0, N'向厂家付货款', N'', N'', N'', N'', N'', N'14');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'D', N'外勤', N'PhotoQuery', N'照片查看', 0, 1, 0, N'在线查看业务员上传的照片', N'', N'', N'', N'', N'', N'13');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'PreferenceMoney', N'单据优惠权限', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'13');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'G', N'系统配置', N'PricetypeSet', N'价格权限设置', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'12');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'D', N'外勤', N'Promotion', N'拍照上传', 0, 1, 0, N'现场拍摄巡店照片上报公司', N'', N'', N'', N'', N'', N'2');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'B', N'信息', N'PTypeInfo', N'商品档案', 0, 1, 0, N'查询商品详细资料信息', N'', N'', N'', N'', N'', N'4');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F', N'其他权限', N'PTypePrice', N'商品档案价格查看', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'9');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'C', N'报表', N'PTypeStock', N'库存状况', 0, 1, 0, N'在线查询商品库存剩余数量', N'', N'', N'', N'', N'', N'1');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'RepeatSubmit', N'单据重复提交权限', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'26');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'Sale', N'销售开单', 0, 1, 0, N'把货卖给客户并收款', N'', N'', N'', N'', N'', N'6');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'SaleBack', N'销售退货', 0, 1, 0, N'记录客户退货信息', N'', N'', N'', N'', N'', N'7');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'SaleOrder', N'销售订单', 0, 1, 0, N'记录客户订货信息', N'', N'', N'', N'', N'', N'5');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'A', N'开单', N'SameMove', N'仓库调货', 0, 1, 0, N'处理向公司仓库要货或还货的业务', N'', N'', N'', N'', N'', N'11');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'StockQty', N'开单时允许查看库存余量', 0, 1, 0, N'不勾选：开单选择商品界面库存显示为*号', N'', N'', N'', N'', N'', N'21');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'SubmitBeforePrint', N'打印时无需提交单据', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'22');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'SubmitEndUpdate', N'打印后继续修改权限', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'23');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'ThanStockQtySale', N'允许超出库存数销售', 0, 1, 0, N'勾选：可以负库存开单，销售订单除外', N'', N'', N'', N'', N'', N'17');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'UpdateBill', N'已提交单据修改权限', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'24');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F', N'其他权限', N'UserSet', N'系统配置', 0, 1, 0, N'APP端系统配置权限', N'', N'', N'', N'', N'', N'12');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'B', N'信息', N'Wooldraft', N'草稿查询', 0, 1, 0, N'在线查询已提交但未过账的业务单据', N'', N'', N'', N'', N'', N'15');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'B', N'信息', N'WoolOrder', N'订单查询', 0, 1, 0, N'在线查询订货记录', N'', N'', N'', N'', N'', N'14');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'B', N'信息', N'Woolprocess', N'经营历程', 0, 1, 0, N'在线查询已过账的业务单据', N'', N'', N'', N'', N'', N'16');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'ZeroPrice', N'允许零单价开单', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'18');
----AddDate:2020年2月14日 By:MYX 
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'SaleAccount', N'销售单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'28');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'SaleBackAccount', N'销售退货单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'29');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'BuyAccount', N'进货单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'30');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'BuyBackAccount', N'进货退货单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'31');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'SameMoveAccount', N'仓库调拨单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'32');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'OtherOutBillAccount', N'其他出库单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'33');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'CollectionBillAccount', N'收款单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'34');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'PayBillAccount', N'付款单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'35');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'CashBillAccount', N'现金费用单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'36');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'F1', N'其他权限II', N'MoneyBillAccount', N'一般费用单过账', 0, 1, 0, N'', N'', N'', N'', N'', N'', N'37');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'B', N'信息', N'AddPTypeInfo', N'新增商品', 0, 1, 0, N'在手机端新增商品档案信息', N'', N'', N'', N'', N'', N'38');
INSERT [dbo].[MdD9_UserLimitType] ([Sort], [SortName], [LimitType], [LimitName], [LimitValue], [IsUsed], [Deleted], [Comment], [Feld1], [Feld2], [Feld3], [Feld4], [Feld5], [SortNum]) VALUES (N'B', N'信息', N'AddBTypeInfo', N'新增单位档案', 0, 1, 0, N'在手机端新增客户、供应商档案信息', N'', N'', N'', N'', N'', N'39');




END
GO





/****** Object:  Table [dbo].[MdD9_BillName]    单据类型表(清空重写) ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_BillName') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

TRUNCATE TABLE [dbo].[MdD9_BillName];

INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BuyOrder', N'100', N'进货订单', N'JHDD', N'', N'', N'', N'0', N'订单类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SaleOrder', N'200', N'销售订单', N'XSDD', N'', N'', N'', N'0', N'订单类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'RequestBill', N'204', N'请购单', N'QGD', N'', N'', N'', N'0', N'订单类', N'Nothing', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CombinationSaleOrder', N'160', N'套件订单', N'TXSD', N'', N'', N'', N'0', N'订单类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'QuotePriceBill', N'184', N'报价单', N'BJD', N'', N'', N'', N'0', N'订单类', N'Nothing', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'Buy', N'101', N'进货入库', N'JHD', N'', N'', N'', N'1', N'进货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BuyBack', N'102', N'进货退货', N'JHTD', N'', N'', N'', N'1', N'进货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'Sale', N'201', N'销售出库', N'XSD', N'', N'', N'', N'2', N'销售类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SaleBack', N'202', N'销售退货', N'XSTD', N'', N'', N'', N'2', N'销售类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SaleBackChange', N'24', N'销售换货', N'XSTHD', N'', N'', N'', N'2', N'销售类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'MoveBill', N'301', N'同价调拨单', N'TJDB', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'Retail', N'12', N'零售单', N'LSD', N'', N'', N'', N'2', N'销售类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'PosRetail', N'13', N'Pos零售单', N'POSD', N'', N'', N'', N'2', N'销售类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'RetailBackBill', N'14', N'零售单退货单', N'LSTH', N'', N'', N'', N'2', N'销售类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CZDBill', N'40', N'拆装单', N'CZD', N'', N'', N'', N'2', N'销售类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SCZZBill', N'41', N'生产组装', N'SCZZ', N'', N'', N'', N'2', N'销售类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CombinationSale', N'161', N'套件销售', N'TXS', N'', N'', N'', N'2', N'销售类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'ColligateSale', N'9999', N'综合开单', N'ZHKD', N'', N'', N'', N'2', N'销售类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SameMove', N'301', N'仓库调拨', N'DBD', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'DistinctMove', N'18', N'变价调拨', N'BJDBD', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'StockCheck', N'307', N'存货盘点', N'PDD', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CargoCheck', N'8883', N'货位盘点', N'HWPD', N'', N'', N'', N'3', N'仓储类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'StockCheckJoin', N'203', N'加盟店盘点', N'JMDPD', N'', N'', N'', N'3', N'仓储类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'OtherInBill', N'303', N'其它入库', N'QTIn', N'', N'', N'', N'3', N'仓储类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'OtherOutBill', N'304', N'其它出库', N'QTOut', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BorrowBill', N'71', N'借进单', N'JJD', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BorrowReturn', N'72', N'借进还出', N'JJHC', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'LendBill', N'87', N'借出单', N'JCD', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'LendReturn', N'88', N'借出还回', N'JCHH', N'', N'', N'', N'3', N'仓储类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'StoreOrder', N'701', N'门店要货', N'MDYHD', N'', N'', N'', N'4', N'配货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SamePick', N'218', N'自营店配货单', N'ZYDPH', N'', N'', N'', N'4', N'配货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SamePickBack', N'215', N'自营店退货单', N'ZYDTH', N'', N'', N'', N'4', N'配货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'DistinctPick', N'222', N'加盟店配货单', N'JMDPH', N'', N'', N'', N'4', N'配货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'DistinctPickBack', N'224', N'加盟店退货单', N'JMDTH', N'', N'', N'', N'4', N'配货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CusStockQty', N'520', N'库存上报', N'KCLSB', N'', N'', N'', N'4', N'配货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CustomerBill', N'521', N'客户卡单', N'KHKD', N'', N'', N'', N'4', N'配货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SaleOrderCheck', N'8C', N'销售订单验货', N'XSDD_Y', N'SaleOrder', N'Sale', N'', N'5', N'验货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BuyOrderCheck', N'7C', N'进货订单验货', N'JHDD_Y', N'BuyOrder', N'Buy', N'', N'5', N'验货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SaleCheck', N'11C', N'销售单验货', N'XSD_Y', N'Sale', N'', N'', N'5', N'验货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SaleBackCheck', N'45C', N'销售退货验货', N'XSTD_Y', N'SaleBack', N'', N'', N'5', N'验货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BuyCheck', N'34C', N'进货单验货', N'JHD_Y', N'Buy', N'', N'', N'5', N'验货类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BuyBackCheck', N'6C', N'进货退货验货', N'JHTD_Y', N'BuyBack', N'', N'', N'5', N'验货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SameMoveCheck', N'17C', N'同价调拨验货', N'JHTD_Y', N'SameMove', N'', N'', N'5', N'验货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'DistinctMoveCheck', N'18C', N'变价调拨验货', N'JHTD_Y', N'DistinctMove', N'', N'', N'5', N'验货类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CollectionBill', N'402', N'收款单', N'SKD', N'', N'', N'', N'6', N'钱流类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'PayBill', N'401', N'付款单', N'FKD', N'', N'', N'', N'6', N'钱流类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'MoneyBill', N'404', N'一般费用', N'YBFYD', N'', N'', N'', N'6', N'钱流类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'CashBill', N'403', N'现金费用', N'XJFYD', N'', N'', N'', N'6', N'钱流类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'YufuPayBill', N'190', N'预付款单', N'YFKD', N'', N'', N'', N'6', N'钱流类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'QtsrBill', N'405', N'其他收入', N'QTSR', N'', N'', N'', N'6', N'钱流类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'OtherCollectionBill', N'93', N'其它收款', N'OCB', N'', N'', N'', N'6', N'钱流类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'OtherPayBill', N'36', N'其它付款', N'OPB', N'', N'', N'', N'6', N'钱流类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'YuCollectionBill', N'189', N'预收款单', N'YSKD', N'', N'', N'', N'6', N'钱流类', N'Nothing', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'MoveMoney', N'406', N'转款单', N'ZKD', N'', N'', N'', N'7', N'钱流类', N'Nothing', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'BuyFill', N'34F', N'采购补录单', N'CGBL', N'', N'', N'Buy', N'7', N'补录类', N'In', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SaleFill', N'11F', N'销售补录单', N'XSBL', N'', N'', N'Sale', N'7', N'补录类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'SameMoveFill', N'17F', N'调拨单补录', N'DBBL', N'', N'', N'SameMove', N'7', N'补录类', N'Out', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'MDD9MoneyBill', N'MDD951', N'费用申请单', N'MDD9_FYSQ', N'', N'', N'', N'50', N'管家婆D9手机版', N'Nothing', 0, N'', N'');
INSERT [dbo].[MdD9_BillName] ([BillType], [BillTypeID], [BillName], [BillHead], [SourceBillType], [ToBillType], [FillBillType], [Type], [TypeName], [InOutType], [Deleted], [Say], [Comment]) VALUES (N'MaintainBill', N'178', N'美容快修单', N'MRKX', N'', N'', N'', N'9', N'汽配维修类', N'Nothing', 0, N'', N'');

END
GO






/****** Object:  Table [dbo].[MdD9_ImageType]    照片类型表(无记录则插入) ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_ImageType') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

---表中无记录则插入
IF NOT EXISTS(SELECT TOP 1 1 FROM [dbo].[MdD9_ImageType])
BEGIN

INSERT [dbo].[MdD9_ImageType] ([SysType], [TypelId], [Typeusercode], [Typename], [Comment], [Deleted], [IsStop], [obgate1], [obgate2], [SortNum]) VALUES (1, N'99999', N'qdpz', N'签到拍照', N'系统类型', N'0', N'0', N'', N'', 1);
INSERT [dbo].[MdD9_ImageType] ([SysType], [TypelId], [Typeusercode], [Typename], [Comment], [Deleted], [IsStop], [obgate1], [obgate2], [SortNum]) VALUES (0, N'00001', N'hjcl', N'货架陈列', N'', N'0', N'0', N'', N'', 1);
INSERT [dbo].[MdD9_ImageType] ([SysType], [TypelId], [Typeusercode], [Typename], [Comment], [Deleted], [IsStop], [obgate1], [obgate2], [SortNum]) VALUES (0, N'00004', N'mt', N'门头', N'', N'0', N'0', N'', N'', 2);
INSERT [dbo].[MdD9_ImageType] ([SysType], [TypelId], [Typeusercode], [Typename], [Comment], [Deleted], [IsStop], [obgate1], [obgate2], [SortNum]) VALUES (0, N'00005', N'jp', N'竞品', N'', N'0', N'0', N'', N'', 3);
INSERT [dbo].[MdD9_ImageType] ([SysType], [TypelId], [Typeusercode], [Typename], [Comment], [Deleted], [IsStop], [obgate1], [obgate2], [SortNum]) VALUES (0, N'00002', N'dtcl', N'堆头陈列', N'', N'0', N'0', N'', N'', 4);
INSERT [dbo].[MdD9_ImageType] ([SysType], [TypelId], [Typeusercode], [Typename], [Comment], [Deleted], [IsStop], [obgate1], [obgate2], [SortNum]) VALUES (0, N'00003', N'cxp', N'促销品', N'', N'0', N'0', N'', N'', 5);
INSERT [dbo].[MdD9_ImageType] ([SysType], [TypelId], [Typeusercode], [Typename], [Comment], [Deleted], [IsStop], [obgate1], [obgate2], [SortNum]) VALUES (0, N'00006', N'pop', N'POP', N'', N'0', N'0', N'', N'', 6);

END

END
GO





/****** Object:  Table [dbo].[MdD9_PricePriority]    价格优先级(无记录则插入) ******/
IF EXISTS (SELECT * FROM  sysobjects WHERE ID = object_id(N'MdD9_PricePriority') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN

---表中无记录则插入
IF NOT EXISTS(SELECT TOP 1 1 FROM [dbo].[MdD9_PricePriority])
BEGIN

INSERT [dbo].[MdD9_PricePriority] ([PriceKey], [PriceName], [Sort], [Comment]) VALUES (N'PromoPrice', N'促销价', N'1', N'');
INSERT [dbo].[MdD9_PricePriority] ([PriceKey], [PriceName], [Sort], [Comment]) VALUES (N'PriceTrack', N'价格跟踪', N'2', N'');
INSERT [dbo].[MdD9_PricePriority] ([PriceKey], [PriceName], [Sort], [Comment]) VALUES (N'BTypePrice', N'客户适用价', N'3', N'');
INSERT [dbo].[MdD9_PricePriority] ([PriceKey], [PriceName], [Sort], [Comment]) VALUES (N'DefaultPrice', N'默认开单价', N'4', N'');

END


END
GO



/***************************************************** （第六部分）账套库，版本迭代库结构和数据升级 *****************************************************/






/***************************************************** （第七部分）账套库，配置和权限升级 *****************************************************/




/****** Object:  Table [dbo].[MdD9_Sysdata]    用户配置升级 ******/
INSERT INTO dbo.MdD9_Sysdata
(SysValues,TypeClass,SortNum,ValueType,TypeName,FullName,ENumValue,MinValue,MaxValue,
TypeValues,TypeImage,[ReadOnly],Deleted,xiwamaxtime,Feld1,Feld2,Feld3,Say,Comment)
SELECT
MST.SysValues , -- SysValues - int
MST.TypeClass , -- TypeClass - varchar(120)
MST.SortNum , -- SortNum - varchar(100)
MST.ValueType , -- ValueType - varchar(120)
MST.TypeName , -- TypeName - varchar(200)
MST.FullName , -- FullName - varchar(200)
MST.ENumValue , -- ENumValue - varchar(1000)
MST.MinValue , -- MinValue - varchar(100)
MST.MaxValue , -- MaxValue - varchar(100)
MST.TypeValues , -- TypeValues - varchar(1000)
NULL , -- TypeImage - image
MST.[ReadOnly] , -- ReadOnly - int
MST.Deleted , -- Deleted - int
CONVERT(VARCHAR(50),GETDATE(),121) , -- xiwamaxtime - varchar(100)
MST.Feld1 , -- Feld1 - varchar(100)
MST.Feld2 , -- Feld2 - varchar(100)
MST.Feld3 , -- Feld3 - varchar(100)
MST.Say , -- Say - varchar(500)
MST.Comment  -- Comment - varchar(500)
FROM dbo.MdD9_SysdataType MST
WHERE 1=1
AND NOT EXISTS
(SELECT 1 FROM dbo.MdD9_Sysdata MS WHERE MS.TypeName=MST.TypeName);
GO

UPDATE	dbo.MdD9_Sysdata SET TypeValues=2 WHERE TypeName='TotalPoint'
GO


/****** Object:  Table [dbo].[MdD9_UserLimit]    用户权限升级 ******/
INSERT INTO dbo.MdD9_UserLimit
(Sort,SortNum,SortName,TypeID_,LimitType,LimitName,LimitValue,
xiwamaxtime,Deleted,Feld1,Feld2,Feld3,Feld4,Feld5,Comment)
SELECT
MULT.Sort , -- Sort - varchar(120)
MULT.SortNum , -- SortNum - varchar(100)
MULT.SortName , -- SortName - varchar(120)
MU.LoginID , -- TypeID_ - varchar(120)
MULT.LimitType , -- LimitType - nvarchar(120)
MULT.LimitName , -- LimitName - nvarchar(120)
CASE WHEN MU.LoginID=1 THEN 1 ELSE 0 END , -- LimitValue - int
CONVERT(VARCHAR(50),GETDATE(),121) , -- xiwamaxtime - varchar(100)
0 , -- Deleted - int
MULT.Feld1 , -- Feld1 - varchar(120)
MULT.Feld2 , -- Feld2 - varchar(120)
MULT.Feld3 , -- Feld3 - varchar(120)
MULT.Feld4 , -- Feld4 - varchar(120)
MULT.Feld5 , -- Feld5 - varchar(120)
MULT.Comment  -- Comment - nvarchar(150)
FROM dbo.MdD9_User MU,dbo.MdD9_UserLimitType MULT
WHERE 1=1
AND NOT EXISTS
(SELECT 1 FROM MdD9_UserLimit MUL WHERE MUL.TypeID_=MU.LoginID AND MUL.LimitType=MULT.LimitType);
GO




/****** Object:  Table [dbo].[MdD9_UserPriceLimit]    用户价格类型权限表（只升级超级用户） ******/
INSERT INTO dbo.MdD9_UserPriceLimit
(loginid,PriceType,FullName,xiwamaxtime)
SELECT
N'1' , -- loginid - nvarchar(150)
MPT.PriceType , -- PriceType - nvarchar(150)
MPT.FullName , -- FullName - varchar(100)
CONVERT(VARCHAR(50),GETDATE(),121)  -- xiwamaxtime - varchar(100)
FROM dbo.MdD9_PriceType MPT
WHERE 1=1
AND NOT EXISTS
(SELECT 1 FROM MdD9_UserPriceLimit MUPL WHERE MUPL.loginid='1' AND MUPL.PriceType=MPT.PriceType);
GO












/***************************************************** （第八部分）账套库，自定义数据类型创建升级（预留） *****************************************************/





/***************************************************** D9手机版，版本号、日期更新 *****************************************************/

UPDATE dbo.MdD9_Sysdata SET TypeValues='V6.2.0'
WHERE TypeName='SerVer' OR TypeName='SqlProcedureVer';
GO

UPDATE dbo.MdD9_Sysdata SET TypeValues='2020.03.13'
WHERE TypeName='SerEdition' OR TypeName='SqlProcedureEdition';
GO

/***************************************************** D9手机版，版本号、日期更新 *****************************************************/




/***************************************************** （第九部分）账套库，函数、存储过程、视图删除 *****************************************************/



/*************************************************************/
---BEGIN:规则不统一的函数删除
IF EXISTS (SELECT * FROM sysobjects WHERE  xtype='fn' and name='FN_UpLoadImageGroup')
BEGIN
DROP FUNCTION	dbo.FN_UpLoadImageGroup;
END
GO


/*************************************************************/
---BEGIN:读取函数，删除函数
DECLARE @ExecSql VARCHAR(8000);
DECLARE @FunctionName VARCHAR(200);
SET @ExecSql='';

DECLARE FunctionList CURSOR FOR
SELECT [name] FROM sysobjects WHERE 
xtype='FN' AND [name] LIKE 'FN_MdD9%';
-----=======
OPEN FunctionList
FETCH NEXT FROM FunctionList INTO @FunctionName
WHILE @@FETCH_STATUS = 0
BEGIN
  
----赋值SQL语句
SET @ExecSql='DROP FUNCTION '+ @FunctionName + ';';
----执行SQL语句
EXEC (@ExecSql);

FETCH NEXT FROM FunctionList INTO @FunctionName
END
CLOSE FunctionList
DEALLOCATE FunctionList;

GO
---END:读取函数，删除函数
/*************************************************************/


/*************************************************************/
---BEGIN:读取存储过程，删除存储过程
DECLARE @ExecSql VARCHAR(8000);
DECLARE @ProcedureName VARCHAR(200);
SET @ExecSql='';

DECLARE ProcedureList CURSOR FOR
SELECT [name] FROM sysobjects WHERE 
xtype='P' AND ([name] LIKE 'PR_MdD9%');
-----=======
OPEN ProcedureList
FETCH NEXT FROM ProcedureList INTO @ProcedureName
WHILE @@FETCH_STATUS = 0
BEGIN
  
----赋值SQL语句
SET @ExecSQL=' DROP PROCEDURE '+ @ProcedureName + ';';
----执行SQL语句
EXEC (@ExecSQL);


FETCH NEXT FROM ProcedureList INTO @ProcedureName
END
CLOSE ProcedureList
DEALLOCATE ProcedureList;
GO
---END:读取存储过程，删除存储过程
/*************************************************************/









/***************************************************** （第十部分）账套库，函数、存储过程、视图创建（注意依赖先后关系） *****************************************************/




if EXISTS(Select * From sysobjects  where XType='FN' and Name='FN_MdD9_PTypePrice') 
DROP FUNCTION FN_MdD9_PTypePrice;
GO


/****** Object:  UserDefinedFunction [dbo].[FN_MdD9_PTypePrice]    ******/

CREATE FUNCTION [dbo].[FN_MdD9_PTypePrice](@PTypeID_ varchar(50),@UnitID_ varchar(50))
RETURNS varchar(3000)
AS
BEGIN
DECLARE @RETPrice VARCHAR(3000);
DECLARE @LinkStr VARCHAR(100);
DECLARE @StrLen Int;
    SET @RETPrice = '';
    SET @LinkStr=',';
    SET @StrLen = 0;
    
    SELECT @RETPrice = @RETPrice+Cast(Cast(Price as FLOAT) as varchar(20))+@LinkStr 
    From MdD9_PTypePrice 
    where PTypeID_=@PTypeID_ AND UnitID_=@UnitID_ 
	ORDER BY PriceType Asc;
    
    
    SET @StrLen = Len(@RETPrice); 
    IF @StrLen>0 
    Begin
    ----最后一个分隔符号去除
    SET @RETPrice = SUBSTRING(@RETPrice,1,@StrLen-1);
    END
    
    
    RETURN @RETPrice;
END

GO




if EXISTS(Select * From sysobjects  where XType='FN' and Name='FN_UpLoadImageGroup') 
DROP FUNCTION FN_UpLoadImageGroup;
GO



/****** Object:  UserDefinedFunction [dbo].[FN_UpLoadImageGroup]    ******/

CREATE FUNCTION [dbo].[FN_UpLoadImageGroup](@BillID varchar(100),@ImageTypeID varchar(50))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @RETImgUrl varchar(8000);
DECLARE @LinkStr  VARCHAR(100);
DECLARE @StrLen  Int;

    SET @StrLen = 0;
    SET @RETImgUrl = '';
    Set @LinkStr=';';
    
    SELECT @RETImgUrl = @RETImgUrl+ImgIn+ @LinkStr
    From MdD9_UpLoadImage_list 
    where ImgIn<>'' and BillId=@BillID and ImageTypeID=@ImageTypeID;
    
    RETURN @RETImgUrl;
END

GO





if EXISTS(select * from sysobjects where id = OBJECT_ID(N'[PR_MdD9_UpdateUnitsPrice]') and OBJECTPROPERTY(id,N'IsProcedure')= 1) 
DROP PROCEDURE PR_MdD9_UpdateUnitsPrice;
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



/****** Object:  StoredProcedure [dbo].[PR_MdD9_UpdateUnitsPrice]    ******/


--SELECT * FROM MdD9_PTypePrice
--SELECT * FROM MdD9_PTypeUnits
--EXEC PR_MdD9_UpdateUnitsPrice @SysType=1,@XiWaMaxNum=0

--  *********************************************************************************************
--  ||                                                                                        
--  ||   过程名称：PR_MdD9_UpdateUnitsPrice                                     
--  ||   过程功能：生成商品单位价格数据存储过程
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型                    意义                     输入输出
--  ||----------------------------------------------------------------------------------------
--  ||  			@SysType		      VARCHAR(100),		0 --代表数据升级,只生成商品单位
--  ||                                                      1 --代表生成DB包,单位价格均生成

--  ||  			@XiWaMaxNum		      INT,		        前台差异化传的商品XiWaMaxNumber
--  ||                                                      0 --生成数据包，固定传0
--  ||                                                        --差异化调用，传商品的XiWaMaxNumber
--  ********************************************************************************************* 
CREATE PROCEDURE [dbo].[PR_MdD9_UpdateUnitsPrice](@SysType varchar(100),@XiWaMaxNum INT)
AS
BEGIN
--***********************************************

     --***********************************************************************
     -----商品单位表
     --***********************************************************************
     IF(@XiWaMaxNum=0)
     BEGIN
     --***********************************************************************
     --生成数据包
     --***********************************************************************
     TRUNCATE TABLE MdD9_PTypeUnits;
     INSERT /*+ append */ INTO MdD9_PTypeUnits(PTypeID_,UnitID_,UnitNum,UnitName,UnitRate,IsDefault,Comment)
     SELECT DG.GoodsID,WU.UnitID_,DGP.UnitID,WU.FullName, DGP.Convfactor AS UnitRate,
	 CASE WHEN DGP.UnitID=1 THEN 1 ELSE 0 END AS IsDefault,'' AS Comment
     FROM BD_Goods DG,BD_Goods_Price DGP,MdD9_Units WU
     WHERE DG.GoodsID = DGP.GoodsID And WU.FullName = LTrim(RTrim(DGP.Unit));
     END
     ELSE
     BEGIN
     --***********************************************************************
     --差异化
     --***********************************************************************
     SET @XiWaMaxNum=@XiWaMaxNum;
     END
     --***********************************************************************
     

    
		
	 --***********************************************************************
     ----代表数据升级,只生成商品单位 @SysType=1代表生成DB包,单位价格均生成 
	 IF(@SysType=0) 
	 RETURN;
	 --***********************************************************************
	 
	 
	 --***********************************************************************
     ----商品单位价格表
     --***********************************************************************
     IF(@XiWaMaxNum=0)
     BEGIN
     --***********************************************************************
     --生成数据包
     --***********************************************************************
     
     --清空商品单位价格表
     TRUNCATE TABLE MdD9_PTypePrice;
        
	 --重新写入所有商品单位各个价格记录
	 INSERT /*+ append */ INTO MdD9_PTypePrice(PTypeID_,UnitID_,PriceType,Price,Comment)
     Select DISTINCT WPU.PTypeID_,WPU.UnitID_,WPT.PriceType,'0','' AS Comment 
     From MdD9_PTypeUnits WPU,MdD9_PriceType WPT
     
     END
     ELSE
	 --***********************************************************************
     BEGIN
     --差异化
     --***********************************************************************
     SET @XiWaMaxNum=@XiWaMaxNum;
     END
	 --***********************************************************************
     
	  --****************************************
     ----更新表MdD9_PTypePrice具体价格值
     --****************************************
     DECLARE @chrSQLCursor VARCHAR(8000);
	 DECLARE @type VARCHAR(8000);
	 DECLARE @i INT;
     DECLARE @ii VARCHAR(8000);
	 
	 
	 --****************************************
     ----各个销售价处理
     --****************************************
	 SET @i=1;
	 WHILE @i<=15 
	 BEGIN
	 --**********************
	 SET @ii=@i;
	 SET @type=''
	 SET @type='Price';
	 SET @type=@type+@ii
	 

     SET @chrSQLCursor=' Update WPP Set Price=BGP.'+ @type+' 
	 FROM MdD9_PTypePrice WPP,BD_Goods_Price BGP,MdD9_PTypeUnits WPU,MdD9_PriceType WPT
	 WHERE WPP.PTypeID_=BGP.GoodsID AND WPP.PTypeID_=WPU.PTypeID_
	 AND WPP.UnitID_=WPU.UnitID_ AND WPU.UnitNum=BGP.UnitID
	 AND BGP.'+ @type+'>0
	 AND WPP.PriceType=WPT.PriceType AND WPT.PriceName=''' + @type + ''''

      
      --PRINT @chrSQLCursor;
      EXEC (@chrSQLCursor);
           
      SET @i=@i+1
      --**********************
      END
      --****************************************



	 --****************************************
     --零售价
     --****************************************
     Update WPP Set Price=BGP.Price_Rtl
	 FROM MdD9_PTypePrice WPP,BD_Goods_Price BGP,MdD9_PTypeUnits WPU,MdD9_PriceType WPT
	 WHERE WPP.PTypeID_=BGP.GoodsID AND WPP.PTypeID_=WPU.PTypeID_
	 AND WPP.UnitID_=WPU.UnitID_ AND WPU.UnitNum=BGP.UnitID
	 AND BGP.Price_Rtl>0
	 AND WPP.PriceType=WPT.PriceType AND WPT.PriceName='RetailPrice';
     --****************************************

	
     --***********************************************************************
     ----更新商品单位表中的单位价格（所有商品）
     ----商品单位表
     UPDATE MdD9_PTypePrice SET Price='0' WHERE  Price IS NULL;
     
     UPDATE MdD9_PTypeUnits SET UnitPrice=Price 
     FROM (
     SELECT PP.PTypeID_,PP.UnitID_,dbo.FN_MdD9_PTypePrice(PP.PTypeID_,PP.UnitID_) AS Price
     FROM MdD9_PTypePrice PP,MdD9_PriceType PT
     WHERE PP.PriceType=PT.PriceType 
     GROUP BY PP.PTypeID_,PP.UnitID_)GG 
     where GG.PTypeID_=MdD9_PTypeUnits.PTypeID_ 
     AND GG.UnitID_=MdD9_PTypeUnits.UnitID_;
	--***********************************************************************

    END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





if EXISTS(select * from sysobjects where id = OBJECT_ID(N'[PR_MdD9_DlyAccount]') and OBJECTPROPERTY(id,N'IsProcedure')= 1) 
DROP PROCEDURE PR_MdD9_DlyAccount;
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/****** Object:  StoredProcedure [dbo].[PR_MdD9_DlyAccount]    ******/

--  *********************************************************************************************
--  ||                                                                                        
--  ||   过程名称：PR_MdD9_DlyAccount                                     
--  ||   过程功能：D9单据过账存储过程
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型                    意义                     输入输出
--  ||----------------------------------------------------------------------------------------
--  ||  			@OperatorId		VARCHAR(100),			操作员ID
--  ||  			@UserTypeID		VARCHAR(100),			对应D9操作员ID
--  ||  			@BillType		VARCHAR(100),			单据类型（英文）
--  ||  			@GraspBillID	VARCHAR(100),			管家婆单据ID
--  ||  			@ErrorStr 		VARCHAR(200),			返回消息					OUTPUT
--  ||=========================================================================================   
--  ||   返回值：         值                                  说明
--  ||----------------------------------------------------------------------------------------
--  ||                    1									执行成功
--  ||                  －1									执行失败
--  *********************************************************************************************
--  ||DROP PROCEDURE PR_MdD9_DlyAccount
--  ||----------------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[PR_MdD9_DlyAccount]
(
	@OperatorId		VARCHAR(100),		--操作员ID
	@UserTypeID		VARCHAR(100),		--对应D9操作员ID
	@BillType		VARCHAR(100),		--单据类型（英文）
	@GraspBillID	VARCHAR(100),		--管家婆单据ID
	@ErrorStr		VARCHAR(200) OUTPUT --返回消息
)
AS 
BEGIN
-----=====================================
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRAN D9Account

DECLARE @ReturnValue INT		--调用存储过程后的返回值
DECLARE @retMsg INT				--存储过程UP_PD_BatchPassBill返回结果
DECLARE @BillTypeID VARCHAR(50)	--单据类型ID
SET @ReturnValue ='0'			--设置返回值默认值为'0'

DECLARE @SQL NVARCHAR(MAX),		--SQL语句
		@sqlWhere VARCHAR(2000),--SQL判断条件
		@fieldStr VARCHAR(50),
		@MainTable VARCHAR(50),
		@detailTable VARCHAR(50),
		@serialTable VARCHAR(50),
		@GoodsInfo VARCHAR(100),
		@Msg VARCHAR(200)

--单据类型判断，若当前单据类型为英文则通过BillType英文值获取当前英文值对应的ID
IF(ISNUMERIC(@BillType)=1)
BEGIN
	SET @BillTypeID = @BillType
	SELECT @MainTable=BillTable,@detailTable=BillDetail,@serialTable=BillSerial FROM dbo.PD_BillType WHERE BillTypeId =@BillType
	IF(@@ERROR<>0)
		GOTO Error1
END
ELSE
BEGIN
	SELECT @BillTypeID=BillTypeID,@MainTable=BillTable,@detailTable=BillDetail,@serialTable=BillSerial FROM dbo.PD_BillType WHERE BillTypeId=(SELECT BillTypeID FROM dbo.MdD9_BillName WHERE BillType =@BillType)
	IF(@@ERROR<>0)
		GOTO Error1
END

--若@UserTypeID为空则通过操作员ID@OperatorId转换
IF(ISNULL(@UserTypeID,'')='')
BEGIN
	SELECT @UserTypeID=ETypeID_ FROM MdD9_User MU
	INNER JOIN SS_Operator SO ON SO.ElyID=MU.ETypeID_
	WHERE MU.IsStop='0' AND MU.Deleted='0' AND SO.Stt='1' AND LoginID=@OperatorId
END

--调用存储过程进行过账
EXEC @retMsg=dbo.UP_PD_BatchPassBill @UserTypeID,@GraspBillID,@BillTypeID
IF(@@ERROR<>0)
	GOTO Error1

--检查序列号相关，先判断是否启用序列号
IF EXISTS( SELECT 1 FROM SS_SysCfg WHERE CfgName='SerialNoMgt' AND CfgValue=1)
BEGIN
	IF @BillTypeID IN(101,102,201,202,301,302,303,304,305,306,309,310,600)
	BEGIN
	
		--序列号的数量
		DECLARE @Serial VARCHAR(50)
		SELECT @sqlWhere=CASE WHEN @BillTypeID=302 THEN ' AND G.CostMethod=2' ELSE '' END
		SET @SQL='SELECT TOP 1 @GoodsInfo=GoodsName FROM '+@detailTable+' d
					INNER JOIN dbo.BD_Goods g ON g.GoodsID=d.GoodsID
					LEFT JOIN
					(SELECT COUNT(1)Qty,BillDID FROM '+@serialTable+' GROUP BY BillDID)s
					ON d.DID=s.BillDID
					WHERE BillNo='+CAST(@GraspBillID AS VARCHAR(10))+' AND IsSerial=1 AND d.BSQty<>ISNULL(s.Qty,0)'+@sqlWhere+''
		EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT',@GoodsInfo OUTPUT
		IF isnull(@GoodsInfo,'')<>''
		BEGIN
			IF @retMsg=-6
			SET @Msg='商品【'+@GoodsInfo+'】的序列号数量不等于商品数量'
		END
		
		
		--序列号
		IF @BillTypeID IN(101,202,303,306,310)
		BEGIN
			SELECT @sqlWhere=CASE WHEN @BillTypeID=310 THEN ' AND d.DetailType= 1' ELSE '' END
			SET @SQL='SELECT TOP 1 @GoodsInfo=GoodsName,@Serial=Serial FROM '+@serialTable+' s INNER JOIN '+@detailTable+' d ON s.BillDID=d.DID INNER JOIN BD_Goods G ON d.GoodsID=g.GoodsID
                        WHERE d.BillNo='+CAST(@GraspBillID AS VARCHAR(10))+' AND EXISTS(SELECT 1 FROM  dbo.PD_GoodsSerial gs WHERE gs.Serial=s.Serial AND gs.Flag IN(1,2))'+@sqlWhere+''
            EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT,@Serial VARCHAR(50) OUTPUT,',@GoodsInfo OUTPUT,@Serial OUTPUT
			IF isnull(@GoodsInfo,'')<>''
			BEGIN
				IF @retMsg=-4
				SET @Msg='商品【'+@GoodsInfo+'】的序列号【'+@Serial+'】已经在库'
			END
		END
		
		IF @BillTypeID IN(102,201,301,302,304,305,309,310,600)
		BEGIN
			SELECT @fieldStr=CASE WHEN @BillTypeID IN(301,309) THEN 'Out' ELSE '' END
			SELECT @sqlWhere=CASE WHEN @BillTypeID=310 THEN ' AND d.DetailType=2' ELSE '' END 
			DECLARE @SQL1 VARCHAR(500)
			SET @SQL1=CASE WHEN @BillType=302 THEN '' ELSE ' AND gs.Ppt1ID=d.Ppt1ID AND gs.Ppt2ID=d.Ppt2ID AND gs.WhsPtID=d.'+@fieldStr+'WhsPtID AND gs.BatchNumber=d.BatchNumber
                                     AND gs.ProductDate=d.ProductDate AND gs.EndDate=d.EndDate ' END
                                     
			SET @SQL='SELECT TOP 1 @GoodsInfo=GoodsName,@Serial=Serial FROM (SELECT TOP 1 GoodsName,Serial FROM '+@serialTable+' s  INNER JOIN '+@detailTable+' d ON s.BillDID=d.DID INNER JOIN BD_Goods G ON d.GoodsID=g.GoodsID
						 WHERE d.BillNo='+CAST(@GraspBillID AS VARCHAR(10))+' AND NOT EXISTS(SELECT 1 FROM  dbo.PD_GoodsSerial gs WHERE gs.Serial=s.Serial AND gs.GoodsID=d.GoodsID '+@SQL1
						 +' AND gs.WhsID=d.'+@fieldStr+'WhsID AND gs.Flag=1) AND G.CostMethod=1 '+@sqlWhere+'
						 UNION ALL 
						 SELECT TOP 1 GoodsName,Serial FROM '+@serialTable+' s  INNER JOIN '+@detailTable+' d ON s.BillDID=d.DID INNER JOIN BD_Goods G ON d.GoodsID=g.GoodsID
						 WHERE d.BillNo='+CAST(@GraspBillID AS VARCHAR(10))+' AND NOT EXISTS(SELECT 1 FROM  dbo.PD_GoodsSerial gs WHERE gs.Serial=s.Serial AND gs.GoodsID=d.GoodsID 
						 AND gs.Ppt1ID=d.Ppt1ID AND gs.Ppt2ID=d.Ppt2ID AND gs.WhsPtID=d.'+@fieldStr+'WhsPtID AND gs.BatchNumber=d.BatchNumber AND gs.CostPrice=d.CostPrice
						 AND gs.ProductDate=d.ProductDate AND gs.EndDate=d.EndDate AND gs.WhsID=d.'+@fieldStr+'WhsID AND gs.Flag=1) AND G.CostMethod=2 '+@sqlWhere+')TT'
			EXECUTE sp_executesql @SQL,N'@GoodsInfo VARCHAR(50) OUTPUT,@Serial VARCHAR(50) OUTPUT,',@GoodsInfo OUTPUT,@Serial OUTPUT
			IF isnull(@GoodsInfo,'')<>''
			BEGIN
				IF @retMsg=-4
				SET @Msg='商品【'+@GoodsInfo+'】的序列号【'+@Serial+'】不在库'
			END
		END
	END
END

IF(@retMsg<>0)
BEGIN
	IF(@retMsg='-10')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'单据已存在或已过账'
	END
	ELSE IF(@retMsg='-11')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'账套未激活'
	END
	ELSE IF(@retMsg='-12')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'单据录单日期小于本期开始日期'
	END
	ELSE IF(@retMsg='-13')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'库存数量不能为负'
	END
	ELSE IF(@retMsg='-14')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'存在金额为0的项目'
	END
	ELSE IF(@retMsg='-15')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'借贷不相等'
	END
	ELSE IF(@retMsg='-16')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'单据数据超过订单数量'
	END
	ELSE IF(@retMsg='-17')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'退货数据超过原单数量'
	END
	ELSE IF(@retMsg='-18')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'单据录单日期小于本期开始日期'
	END
	ELSE IF(@retMsg='-102')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'关联单据未归档'
	END
	ELSE IF(@retMsg='9')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'改变单据状态失败'
	END
	ELSE IF(@retMsg='-1')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'库存金额不能为负'
	END
	ELSE IF(@retMsg='-4')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+@Msg
	END
	ELSE IF(@retMsg='-5')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'请录入成本单价'
	END
	ELSE IF(@retMsg='-6')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+@Msg
	END
	ELSE IF(@retMsg='-7')
	BEGIN
		SET @ErrorStr = '错误代码:'+CAST(@retMsg AS VARCHAR(10))+'未录入批次或批次已存在'
	END
	GOTO Error1;
END

-----=====================================
	SET @ReturnValue=1;
	SET @ErrorStr='过账成功';
	COMMIT TRAN D9Account;
	RETURN @ReturnValue;
-----=====================================
 Error1:
	ROLLBACK TRAN D9Account;
	Return @ReturnValue;
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO







if EXISTS(select * from sysobjects where id = OBJECT_ID(N'[PR_MdD9BillIndex]') and OBJECTPROPERTY(id,N'IsProcedure')= 1) 
DROP PROCEDURE PR_MdD9BillIndex;
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/****** Object:  StoredProcedure [dbo].[PR_MdD9BillIndex]    ******/

--  *********************************************************************************************
--  ||                                                                                        
--  ||   过程名称：PR_MdD9BillIndex                                     
--  ||   过程功能：开单存储过程
--  ||=========================================================================================
--  ||   参数说明：  参数名称         类型                    意义                     输入输出
--  ||----------------------------------------------------------------------------------------
--  ||  			@BillNumberID		      VARCHAR(100),		单据ID
--  ||=========================================================================================   
--  ||   返回值：         值                                  说明
--  ||----------------------------------------------------------------------------------------
--  ||                    1									执行成功
--  ||                  －1									执行失败
--  *********************************************************************************************
--  ||DROP PROCEDURE PR_MdD9BillIndex
--  ||----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[PR_MdD9BillIndex](@BillNumberID varchar(100)) AS
  DECLARE @State INT,@BillType varchar(50),@BillDate VARCHAR(50),@BTypeID_ varchar(50),@KTypeID_ varchar(50),@KTypeID2_ varchar(50),@UserID VARCHAR(50);
  DECLARE @LoginName VARCHAR(100),@ViPCardID VARCHAR(50),@PayIDs VARCHAR(500),@PayTotals VARCHAR(500),@SumPayTotal NUMERIC(26,6),@PreTotal NUMERIC(26,6);
  DECLARE @PriceTrack VARCHAR(50),@OrderCode VARCHAR(50),@IfEditBill VARCHAR(50),@Comment NVARCHAR(1000),@Explain NVARCHAR(1000);
  DECLARE @BillTypeID varchar(50),@BillComment varchar(1000);
  DECLARE @BillCode VARCHAR(50),@STypeID VARCHAR(50),@STypeID2 VARCHAR(50),@VchCode varchar(50);
  DECLARE @GNumberPDate varchar(50),@SerialIsUsed varchar(50);
  DECLARE @Tax NUMERIC(20,4);---税率
  SET @Tax=0;
  ----会计期间
  DECLARE @Period VARCHAR(50);
  DECLARE @ReturnValue INT  --调用的返回值,-1失败，0成功
  DECLARE @ProductName VARCHAR(100);----产品名称
  DECLARE @BillName VARCHAR(100);----单据名称
  SET @ReturnValue=-1;
  
  DECLARE @BillID VARCHAR(100);
  SET @BillID=@BillNumberID;
  SET @ProductName='D9手机版';
  --****************************************************************
  
  ---收款日期（收款期限）
  DECLARE @GatheringDate VARCHAR(20);
  ---结算单位ID
  DECLARE @GatherBtypeId VARCHAR(50);
  ---收付款结算方式;1=按单结算 2=按金额结算
  DECLARE @AccountType VARCHAR(50);
  
  
  ---默认结算方式：1=按单结算
  SET @AccountType='1';
  
  --********************************************************************************************************
  SET XACT_ABORT ON
  BEGIN TRAN
	Select @State=State,@BillType=BillType,@BillDate=BillDate,@BillCode=BillCode,@BTypeID_= BTypeID_,
	@KTypeID_=KTypeID_,@KTypeID2_=KTypeID2_,@UserID=UserTypeID,@LoginName=LoginName,@ViPCardID=VipCardID,
	@PayIDs=PayATypeID_,@PayTotals=PayMoney,@PreTotal=PreferenceMoney,@PriceTrack=PriceTrack,
	@OrderCode=OrderCode,@IfEditBill=IfEditBill,@Comment=Comment
    From MdD9_BillIndex 
    where BillNumberID=@BillID;
    
    --********************************************************************************************************
    IF(@State=1)
    BEGIN
    
    ----单据名称读取
    SELECT @BillName=ISNULL(BillName,'') FROM dbo.MdD9_BillName WHERE BillType=@BillType;
    
    
    
    ----读取D9的配置，收付款结算方式;1=按单结算 2=按金额结算
    SELECT @AccountType=ISNULL(CfgValue,'1') FROM SS_SysCfg
	WHERE CfgName='AccountType';
    IF(@@ERROR<>0)
      GOTO Error1

    
    
    
    ----如果是修改单据，先删除原单据
    IF(@IfEditBill='1')
    BEGIN
    
    ----========================================
    ----20170725,解决如果是草稿修改单据，OrderCode存储的是原草稿ID，OrderCode同时也是表示调用的订单ID
    ----草稿编辑并没有订单调用，需要清空，否则会造成有关联订单ID
    UPDATE dbo.MdD9_Billindex SET OrderCode='' WHERE BillNumberID=@BillID;
    
    
    ----========================================
    ----20170725如果是编辑单据，BillType单据类型，@OrderCode为原草稿的单据ID
    DECLARE @OldBillID VARCHAR(50);
    SET @OldBillID='';
    ----查询原始单据的BillID
    SELECT @OldBillID=ISNULL(BillNumberID,'') FROM MdD9_Billindex 
    WHERE BillType=@BillType AND Vchcode=@OrderCode;
    
    IF(@OldBillID='')
    BEGIN
    ----不存在原始草稿单据，将自身标记为删除（来自管家婆的原单，当日报表不统计）
    UPDATE dbo.MdD9_Billindex SET Deleted='1' WHERE BillNumberID=@BillID;
    END
    ELSE
    BEGIN
    ----存在原始草稿单据，将的原始单据标记为删除（来自的原单，当日报表统计用）    
    UPDATE dbo.MdD9_Billindex SET Deleted='1' WHERE BillNumberID=@OldBillID;
    END
    
    
    
    --IF(@BillType='SaleOrder' or @BillType='BuyOrder')
    --BEGIN
    ------订单类
    --DELETE FROM dbo.BakDlyOrder WHERE Vchcode=@OrderCode;
    --DELETE FROM dbo.DlyNdxOrder WHERE Vchcode=@OrderCode;
    --END
    --ELSE
    --BEGIN
    ------非订单类
    --DELETE FROM dbo.BakDly WHERE Vchcode=@OrderCode;
    --DELETE FROM dbo.DlyNdx WHERE Vchcode=@OrderCode;
    --END
       
    END

	--********************************************************************************************************
	----单据部门前台是PATH，先重新关联更新为ID
	UPDATE WB SET WB.DTypeID_=BD.DeptID
	FROM MdD9_Billindex WB,BD_Dept BD
	WHERE 1=1
	AND WB.DTypeID_=BD.Path
	AND WB.DTypeID_<>'' AND WB.BillNumberID=@BillNumberID;
	IF(@@ERROR<>0)
      GOTO Error1


    ----单据部门为空，重新取经手人所属部门ID
	UPDATE WB SET WB.DTypeID_=BE.DeptId
	FROM MdD9_Billindex WB,BD_Employee BE
	WHERE 1=1
	AND WB.ETypeID_=CAST(BE.ElyID AS VARCHAR(50))
	AND WB.DTypeID_='' AND WB.BillNumberID=@BillNumberID AND WB.ETypeID_<>'1';
	IF(@@ERROR<>0)
      GOTO Error1
	--********************************************************************************************************
    
    ---提交的折后单价=单价x折扣
    Update MdD9_BillIndex_List set PDADistPrice=PDAPrice*PDADiscount where BillNumberID=@BillID;
    IF(@@ERROR<>0)
      GOTO Error1
            
    --********************************************************************************************************
    
    ----==============================
	--Declare @MONTH varchar(20),@DAY varchar(20),@BillFlag varchar(20),@number varchar(100)
 --   Set @MONTH=substring(@BillDate,6,2)
 --   Set @DAY=substring(@BillDate,9,2)
 --   Set @number='';
 --   ----==============================
 --   IF LEN(@BillCode)<>0
 --   BEGIN
 --   Set @number=@BillCode;
 --   END
 --   ELSE
 --   BEGIN
 --   ----获取单据编号
 --   exec PR_MdD9_GetBillCode @BillType,@BillTypeID,'00001',@BillDate,'',@MONTH,@DAY,@number output
 --   if(@@ERROR<>0)
 --      goto Error1 
 --   END
    ----==============================
         
         
    ----会计期间
    --SET @Period='1';
    --SELECT @Period=ISNULL(SubValue,'1') FROM dbo.SysData WHERE SubName='period';
    --IF(@Period='')
    --BEGIN
    --SET @Period='1';
    --END


    
    ---往来单位的收款期限
    DECLARE @SKQX INT;
    SET @SKQX=-1;
    SET @GatheringDate='';
    
    SELECT @SKQX=ISNULL(PaidCircle,0) FROM BD_Btype WHERE BTypeID=@BTypeID_;
    IF(@SKQX>=0)
    BEGIN
    ---此客户当前单据的收款日期
    SET @GatheringDate=CONVERT(VARCHAR(10),DATEADD(DAY,@SKQX,CONVERT(DATETIME,@BillDate,101)),120);
    END
    
    
   
    
    ----单据备注
    Set @BillComment='时间:'+Convert(varchar(100),GetDate(),120)+';业务员:'+ @LoginName +';【'+ @ProductName +'】开单生成';
        
        
    ----批次启用的判断
    Select @GNumberPDate=ISNULL(TypeValues,'') From MdD9_Sysdata where TypeName='GNumberPDate';
    ----序列号启用的判断
    Select @SerialIsUsed=ISNULL(TypeValues,'') From MdD9_Sysdata where TypeName='UniqueIsUsed';
    
    
    ----单位换算率判断为0默认为1
    UPDATE MdD9_BillIndex_List SET UnitRate=1 WHERE UnitRate=0 AND BillNumberID=@BillID; 
    IF(@@ERROR<>0)
        GOTO Error1
    
    ----取开单零售价
    Update WBL SET RetailPrice=isnull(BGP.Price_Rtl,0)
    From MdD9_BillIndex_List WBL,BD_Goods_Price BGP 
    WHere WBL.BillNumberID=@BillID AND BGP.GoodsID=WBL.PTypeID_ AND BGP.UnitID=WBL.UnitNum;
    IF(@@ERROR<>0)
        GOTO Error1
            

    
    ----价格取库存成本的单据
    IF(@BillType='SameMove' OR @BillType='OtherOutBill' OR @BillType='OtherInBill')
    BEGIN
		UPDATE MdD9_BillIndex_List SET UnitPrice=CAST(PGS.price*UnitRate AS DECIMAL(28,8)),Discount=1
        FROM MdD9_BillIndex_List WBL,PD_GoodsStock PGS 
        WHERE PGS.GoodsID=WBL.PTypeID_ AND PGS.WhsID=WBL.KTypeID_ 
        AND WBL.BillNumberID=@BillID AND PGS.Qty>0;
        IF(@@ERROR<>0)
            GOTO Error1       
    END
    ELSE
    BEGIN
    
		----其它单据
		Update MdD9_BillIndex_List SET UnitPrice=PDAPrice,Discount=PDADiscount 
		where BillNumberID=@BillID;
		IF(@@ERROR<>0)
            GOTO Error1
		
        
        --************************************************************************************
         -----取客户适用价格
         --if(1=2 AND (@BillType='Sale' or @BillType='SaleBack' OR @BillType='SaleBackChange' or @BillType='SaleOrder'))
         --begin		
         --END            
       --************************************************************************************
        
        ----销售类单据，提交后获取价格跟踪
        IF(@PriceTrack='1' AND (@BillType='Sale' or @BillType='SaleBack' or @BillType='SaleOrder' 
        or @BillType='Retail' OR @BillType='SaleBackChange'))
         BEGIN
         
            ---赋值跟踪价格
			Update WBL SET Unitprice=PPT.SellPrice
            From MdD9_BillIndex_List WBL,PD_PriceTrail PPT 
            where PPT.BTypeID=@BTypeID_ and WBL.PTypeID_=PPT.GoodsID 
            and WBL.UnitNum=PPT.UnitID AND DetailType='0'
            AND WBL.billnumberid=@BillID AND PPT.SellPrice IS NOT NULL;
			IF(@@ERROR<>0)
				GOTO Error1
			
			---赋值跟踪折扣
			Update WBL SET Discount=PPT.SellDis
            From MdD9_BillIndex_List WBL,PD_PriceTrail PPT 
            where PPT.BTypeID=@BTypeID_ and WBL.PTypeID_=PPT.GoodsID 
            and WBL.UnitNum=PPT.UnitID AND DetailType='0'
            AND WBL.billnumberid=@BillID AND PPT.SellDis IS NOT NULL;
			IF(@@ERROR<>0)
				GOTO Error1	
	
         END
         
         ----进货类单据，提交后获取价格跟踪
        IF(@PriceTrack='1' AND (@BillType='Buy' or @BillType='BuyOrder' or @BillType='BuyBack'))
         BEGIN
         
			 ---赋值跟踪价格
			Update WBL SET Unitprice=PPT.PchPrice
            From MdD9_BillIndex_List WBL,PD_PriceTrail PPT 
            where PPT.BTypeID=@BTypeID_ and WBL.PTypeID_=PPT.GoodsID 
            and WBL.UnitNum=PPT.UnitID AND DetailType='0'
            AND WBL.billnumberid=@BillID AND PPT.PchPrice IS NOT NULL;
			IF(@@ERROR<>0)
				GOTO Error1
			
			---赋值跟踪折扣	
			Update WBL SET Discount=PPT.PchDis
            From MdD9_BillIndex_List WBL,PD_PriceTrail PPT 
            where PPT.BTypeID=@BTypeID_ and WBL.PTypeID_=PPT.GoodsID 
            and WBL.UnitNum=PPT.UnitID AND DetailType='0'
            AND WBL.billnumberid=@BillID AND PPT.PchDis IS NOT NULL;
			IF(@@ERROR<>0)
				GOTO Error1
         END        
            
    END
    
    
    ---成本，是出库类单据
    IF(@BillType='SaleOrder' OR @BillType='Sale' OR @BillType='SaleBackChange' 
    OR @BillType='SameMove' OR @BillType='OtherOutBill')
    BEGIN
   
    Update WBL Set CostPrice=CAST((PGS.Total/PGS.Qty) AS DECIMAL(28,8))
    FROM  MdD9_BillIndex_List WBL,PD_GoodsStock PGS
    WHERE PGS.GoodsID=WBL.PTypeID_ AND PGS.WhsID=WBL.KTypeID_
    AND WBL.BillNumberID=@BillNumberID AND PGS.Qty>0;
    IF(@@ERROR<>0)
       GOTO Error1 
    END  
    
    
    ---赠品处理单价赋为0（避免前台出错传单价）
    UPDATE WBL SET UnitPrice=0
    FROM MdD9_BillIndex_List WBL 
    where DetailType='1' AND BillNumberID=@BillID;
    IF(@@ERROR<>0)
		GOTO Error1
		     
    ---表身，数量，价格
    ---服装S，单据单价和数量全是基本单位的
    --SELECT * FROM MdD9_BillIndex_List
    Update WBL SET BillQty=PDAQty*UnitRate,----单据数量，基本单位数量
    BillPrice=UnitPrice/UnitRate,---单据单价，基本单位单价
    BillDistPrice=(UnitPrice*Discount)/UnitRate,----单据折后单价，基本单位折后单价
    BillTotal=CAST(PDAQty*UnitPrice AS NUMERIC(28,2)),----折前金额
    BillDistTotal=CAST(PDAQty*UnitPrice*Discount AS NUMERIC(28,2))----折后金额
    FROM MdD9_BillIndex_List WBL 
    where BillNumberID=@BillID;
    IF(@@ERROR<>0)
		GOTO Error1
	

	---D9表头需要合计折前金额，使用表头Feld2存储
	UPDATE dbo.MdD9_Billindex SET Feld2=0 WHERE BillNumberID=@BillNumberID;
	IF(@@ERROR<>0)
		GOTO Error1




	-----先合计数量、合计金额
	Update WB set DlySumQty=0,DlySumTotal=0,WB.Feld2=0 
	From MdD9_BillIndex WB
	WHERE BillNumberID=@BillID
	IF(@@ERROR<>0)
		GOTO Error1

	
	IF(@BillType='SaleBackChange')
	BEGIN
	----表头的合计数量，合计金额（销售换货单）
	Update WB set DlySumQty=SumQty,DlySumTotal=CAST(DT.BillTotal AS NUMERIC(28,2)),WB.Feld2=CAST(DT.BillDistTotal AS NUMERIC(28,2))
	From MdD9_BillIndex WB,
	(Select BillNumberID,
	SUM((CASE WHEN UsedType='2' THEN CAST(PDAQty AS NUMERIC(28,2)) ELSE 0 END)-
	(CASE WHEN UsedType='1' THEN CAST(PDAQty AS NUMERIC(28,2)) ELSE '0' END)) AS SumQty,
	SUM((CASE WHEN UsedType='2' THEN BillTotal ELSE 0 END)-(CASE WHEN usedtype='1' THEN BillTotal ELSE '0' END)) AS BillTotal,
	SUM((CASE WHEN UsedType='2' THEN BillDistTotal ELSE 0 END)-(CASE WHEN usedtype='1' THEN BillDistTotal ELSE '0' END)) AS BillDistTotal
	From MdD9_BillIndex_List 
	where BillNumberID=@BillID GROUP BY BillNumberID) DT 
	where WB.BillNumberID=DT.BillNumberID AND WB.BillNumberID=@BillID;
	IF(@@ERROR<>0)
		GOTO Error1
	
	END
	ELSE IF(@BillType='CollectionBill' OR @BillType='YuCollectionBill' OR @BillType='PayBill' 
	   OR @BillType='MoneyBill' OR @BillType='CashBill' OR @BillType='QtsrBill')
	BEGIN
	  ----表头的合计数量，合计金额(钱流类单据)
	  Update WB set DlySumQty=0,DlySumTotal=CAST(DT.BillTotal AS NUMERIC(28,2)),WB.Feld2=CAST(DT.BillDistTotal AS NUMERIC(28,2))
	  From MdD9_BillIndex WB,
	  (Select BillNumberID,SUM(UnitPrice) AS BillDistTotal,SUM(UnitPrice) AS BillTotal
	  From MdD9_BillIndex_List 
	  where BillNumberID=@BillID GROUP BY BillNumberID) DT 
	  where WB.BillNumberID=DT.BillNumberID AND WB.BillNumberID=@BillID;
	  IF(@@ERROR<>0)
		GOTO Error1
	END
	ELSE
	BEGIN
	----表头的合计数量，合计金额（商品类单据）
	Update WB set DlySumQty=SumQty,DlySumTotal=CAST(DT.BillTotal AS NUMERIC(28,2)),WB.Feld2=CAST(DT.BillDistTotal AS NUMERIC(28,2))
	From MdD9_BillIndex WB,
	(Select BillNumberID,SUM(PDAQty) as SumQty,SUM(BillDistTotal) AS BillDistTotal,SUM(BillTotal) AS BillTotal
	From MdD9_BillIndex_List 
	where BillNumberID=@BillID GROUP BY BillNumberID) DT 
	where WB.BillNumberID=DT.BillNumberID AND WB.BillNumberID=@BillID;
	IF(@@ERROR<>0)
		GOTO Error1
	
	END
	
		
		
		
	--********************************************************************************************************
    ----单据收付款金额处理:SELECT * FROM MdD9_BillPayData
    --********************************************************************************************************
    ----收付款合计金额先赋值0
    SET @SumPayTotal=0;
    
	----表头的收付款合计金额(单账户收付款金额)
	SELECT @SumPayTotal=ISNULL(SUM(PayTotal),0) 
	FROM dbo.MdD9_BillPayData
	WHERE BillID=@BillNumberID;


	--************************************************************************************
    ----收付款是单账户还是多账户
    DECLARE @Accounts INT;    
    ---单账户收付款的ID,单账户金额
    DECLARE @SignPayID VARCHAR(10);
    SET @Accounts=0;
    SET @SignPayID='0';
	    
    SELECT @Accounts=COUNT(*) 
	FROM dbo.MdD9_BillPayData
	WHERE BillID=@BillNumberID;

    ---如果是单账户
	IF(@Accounts=1)
	BEGIN
	--单账户ID
	SELECT @SignPayID=BF.FinanceID
	FROM dbo.MdD9_BillPayData WBP,BD_Finance BF
	WHERE WBP.PayID=BF.Path AND BillID=@BillNumberID;
	IF(@@ERROR<>0)
		GOTO Error1	
	END
	
    --************************************************************************************
	--********************************************************************************************************
	
	
	

    
	--********************************************************************************************************
	----BEGIN：采购订单
	--********************************************************************************************************
	IF(@BillType='BuyOrder')
    BEGIN
       
    --************************************************************************************
	---采购订单表头：Select * From PD_PchOrdBill
	INSERT INTO dbo.PD_PchOrdBill
	(BillCode,BillDate,DlvDate,BTypeID,DeptID,ElyID,WhsID,BillQty,BTDTotal,Total,Creator,CreateTime,Summary,
	Description,Stt,StopTag,AuditStatus,IsDraft)
	SELECT
	BillCode,        -- BillCode - varchar(50)
	BillDate, -- BillDate - date
	CONVERT(VARCHAR(10),ArriveDate,120), -- DlvDate - date
	WB.BTypeID_,         -- BTypeID - int
	WB.DTypeID_,         -- DeptID - int
	WB.ETypeID_,         -- ElyID - int
	WB.KTypeID_,         -- WhsID - int
	WB.DlySumQty,      -- BillQty - decimal(20, 8)
	WB.DlySumTotal,      -- BTDTotal - decimal(20, 8)---折前金额
	WB.Feld2,      -- Total - decimal(20, 8) ---折后金额
	UserTypeID,         -- Creator - int
	CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
	Comment,        -- Summary - varchar(256)
	@BillComment,        -- Description - varchar(100)
	0,         -- Stt - tinyint
	0,         -- StopTag - tinyint
	0,         -- AuditStatus - tinyint
	1       -- IsDraft - bit
	FROM dbo.MdD9_Billindex WB
    WHERE WB.BillNumberID=@BillID;
    IF(@@ERROR<>0)
		GOTO Error1
    
    Select @VchCode=@@IDENTITY;
    
   
  
    --************************************************************************************
    ----采购订单表身SELECT * FROM PD_PchOrdDetail
	INSERT INTO dbo.PD_PchOrdDetail
	(BillNo,BillDate,BarCode,GoodsID,Ppt1ID,Ppt2ID,WhsID,WhsPtID,UnitID,Convfactor,Price,DiscPrice,TaxPrice,
	Qty,BSQty,Total,DiscTotal,TaxTotal,Discount,TaxRate,Tax,ComQty,ComTotal,Stt,Gift,StopTag,Remark,PriceID)
	SELECT
	@VchCode,         -- BillNo - bigint
	WB.BillDate, -- BillDate - date
	ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
	WBL.PTypeID_,         -- GoodsID - bigint
	0,         -- Ppt1ID - int
	0,         -- Ppt2ID - int
	WBL.KTypeID_,         -- WhsID - int
	wp.WhsPtID,         -- WhsPtID - int
	WBL.UnitNum,         -- UnitID - int
	WBL.UnitRate,      -- Convfactor - decimal(20, 8)
	WBL.UnitPrice,      -- Price - decimal(20, 8)
	WBL.UnitPrice*Discount,      -- DiscPrice - decimal(20, 8)
	WBL.UnitPrice*Discount,      -- TaxPrice - decimal(20, 8)
	WBL.PDAQty,      -- Qty - decimal(20, 8)
	WBL.BillQTY,      -- BSQty - decimal(20, 8)
	WBL.BillTotal,      -- Total - decimal(20, 8)
	WBL.BillDistTotal,      -- DiscTotal - decimal(20, 8)
	WBL.BillDistTotal,      -- TaxTotal - decimal(20, 8)
	WBL.Discount,      -- Discount - decimal(20, 8)
	0,      -- TaxRate - decimal(20, 8)
	0,      -- Tax - decimal(20, 8)
	0,      -- ComQty - decimal(20, 8)
	0,      -- ComTotal - decimal(20, 8)
	0,         -- Stt - tinyint
	WBL.DetailType,         -- Gift - tinyint
	0,         -- StopTag - tinyint
	WBL.Comment,        -- Remark - varchar(100)
	CASE WHEN WBL.DetailType=1 THEN 27 ELSE 21 END -- PriceID - tinyint,27赠品价格，21手动输入
	FROM dbo.BD_Whs_Position wp,MdD9_Billindex WB,MdD9_Billindex_List WBL
    LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
	LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
    WHERE 1=1 AND WB.BillNumberID=WBL.BillNumberID AND wp.WhsID=WBL.KTypeID_ AND wp.WhsPtType=1 AND wp.Stt=1 AND
    WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;

	IF(@@ERROR<>0)
		GOTO Error1


    
	  --************************************************************************************
    END
    --********************************************************************************************************
	----END:采购订单
	--********************************************************************************************************

	--********************************************************************************************************
	----BEGIN：销售订单
	--********************************************************************************************************
	IF(@BillType='SaleOrder')
    BEGIN


	--************************************************************************************
	---销售订单表头：
	----SELECT * From PD_SellOrdBill

	INSERT INTO dbo.PD_SellOrdBill
	(BillCode,BillDate,DlvDate,BTypeID,DeptID,ElyID,WhsID,BillQty,BTDTotal,Total,Creator,CreateTime,Summary,
	Description,Stt,StopTag,AuditStatus,IsDraft)
	SELECT
	BillCode,        -- BillCode - varchar(50)
	BillDate, -- BillDate - date
	CONVERT(VARCHAR(10),ArriveDate,120), -- DlvDate - date
	WB.BTypeID_,         -- BTypeID - int
	WB.DTypeID_,         -- DeptID - int
	WB.ETypeID_,         -- ElyID - int
	WB.KTypeID_,         -- WhsID - int
	WB.DlySumQty,      -- BillQty - decimal(20, 8)
	WB.DlySumTotal,      -- BTDTotal - decimal(20, 8)---折前金额
	WB.Feld2,      -- Total - decimal(20, 8)---折后金额
	UserTypeID,         -- Creator - int
	CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
	Comment,        -- Summary - varchar(256)
	@BillComment,        -- Description - varchar(100)
	0,         -- Stt - tinyint
	0,         -- StopTag - tinyint
	0,         -- AuditStatus - tinyint
	1       -- IsDraft - bit
	FROM dbo.MdD9_Billindex WB
    WHERE WB.BillNumberID=@BillID;
    IF(@@ERROR<>0)
		GOTO Error1
    
    Select @VchCode=@@IDENTITY;


	--************************************************************************************
	---销售订单表身：
	---SELECT * From dbo.PD_SellOrdDetail

	INSERT INTO dbo.PD_SellOrdDetail
	(BillNo,BillDate,BarCode,GoodsID,Ppt1ID,Ppt2ID,WhsID,WhsPtID,UnitID,Convfactor,Price,DiscPrice,TaxPrice,
	Qty,BSQty,Total,DiscTotal,TaxTotal,Discount,TaxRate,Tax,ComQty,ComTotal,Stt,Gift,StopTag,Remark,PriceID)
	SELECT
	@VchCode,         -- BillNo - bigint
	WB.BillDate, -- BillDate - date
	ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
	WBL.PTypeID_,         -- GoodsID - bigint
	0,         -- Ppt1ID - int
	0,         -- Ppt2ID - int
	WBL.KTypeID_,         -- WhsID - int
	wp.WhsPtID,         -- WhsPtID - int
	WBL.UnitNum,         -- UnitID - int
	WBL.UnitRate,      -- Convfactor - decimal(20, 8)
	WBL.UnitPrice,      -- Price - decimal(20, 8)
	WBL.UnitPrice*Discount,      -- DiscPrice - decimal(20, 8)
	WBL.UnitPrice*Discount,      -- TaxPrice - decimal(20, 8)
	WBL.PDAQty,      -- Qty - decimal(20, 8)
	WBL.BillQTY,      -- BSQty - decimal(20, 8)
	WBL.BillTotal,      -- Total - decimal(20, 8)
	WBL.BillDistTotal,      -- DiscTotal - decimal(20, 8)
	WBL.BillDistTotal,      -- TaxTotal - decimal(20, 8)
	WBL.Discount,      -- Discount - decimal(20, 8)
	0,      -- TaxRate - decimal(20, 8)
	0,      -- Tax - decimal(20, 8)
	0,      -- ComQty - decimal(20, 8)
	0,      -- ComTotal - decimal(20, 8)
	0,         -- Stt - tinyint
	WBL.DetailType,         -- Gift - tinyint
	0,         -- StopTag - tinyint
	WBL.Comment,        -- Remark - varchar(100)
	CASE WHEN WBL.DetailType=1 THEN 27 ELSE 21 END -- PriceID - tinyint,27赠品价格，21手动输入
	FROM dbo.BD_Whs_Position wp,MdD9_Billindex WB,MdD9_Billindex_List WBL
    LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
	LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
    WHERE 1=1 AND WB.BillNumberID=WBL.BillNumberID AND wp.WhsID=WBL.KTypeID_ AND wp.WhsPtType=1 AND wp.Stt=1 AND
    WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;

	IF(@@ERROR<>0)
		GOTO Error1


	END
    --********************************************************************************************************
	----END：销售订单
	--********************************************************************************************************


	--********************************************************************************************************
	----BEGIN：订单类：收付款生成收付款单据
	--********************************************************************************************************
	IF((@BillType='BuyOrder' OR @BillType='SaleOrder') AND @SumPayTotal>0)
    BEGIN
		----单据编号前缀
		DECLARE @BillCodeHead VARCHAR(50);
		SET @BillCodeHead='';
		----订单生成收付款单的单据ID
		DECLARE @MF_VchCode VARCHAR(50);
		SET @MF_VchCode='';

		IF(@BillType='BuyOrder')
		BEGIN
		----PayBill
		SET @BillTypeID='401';
		SET @BillCodeHead='FK_';
		END
		IF(@BillType='SaleOrder')
		BEGIN
		----CollectionBill
		SET @BillTypeID='402';
		SET @BillCodeHead='SK_';
		END
		

		--************************************************************************************
		---表头：
		---SELECT * From dbo.MF_PayRecBill;
		INSERT INTO dbo.MF_PayRecBill
		(BillTypeID,BillCode,BillDate,BTypeID,DeptID,ElyID,BPTotal,Privilege,Total,Creator,CreateTime,
		PosElyID,PosTime,Summary,Description,Red,StlTag,IsDraft,AuditStatus)
		SELECT
		@BillTypeID,         -- BillTypeID - int
		@BillCodeHead+WB.BillCode,        -- BillCode - varchar(50)
		WB.BillDate, -- BillDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		@SumPayTotal,      -- BPTotal - decimal(20, 8) 预收付账款金额
		0,      -- Privilege - decimal(20, 8)
		@SumPayTotal,      -- Total - decimal(20, 8) 收付款总金额
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Red - tinyint
		0,         -- StlTag - tinyint
		1,      -- IsDraft - bit
		0          -- AuditStatus - tinyint
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @MF_VchCode=@@IDENTITY;


		--************************************************************************************
		---表身：
		---SELECT * From dbo.MF_PayRecDetail;
		INSERT INTO dbo.MF_PayRecDetail
		(BillNo,FinanceID,Total,Remark)
		SELECT @MF_VchCode,BF.FinanceID,WBP.PayTotal,''
		FROM dbo.MdD9_BillPayData WBP,BD_Finance BF
		WHERE 1=1
		AND WBP.BillID=@BillID AND WBP.PayID=BF.Path
		AND WBP.PayTotal>=0;
		IF(@@ERROR<>0)
			GOTO Error1



	END
	 --********************************************************************************************************
	----END：订单类：收付款生成收付款单据
	--********************************************************************************************************
       
	


	--********************************************************************************************************
	----BEGIN：销售单
	--********************************************************************************************************
	IF(@BillType='Sale')
    BEGIN
		
		SET @BillTypeID='201';

		--************************************************************************************
		---销售单表头：
		---SELECT * From dbo.PD_SellBill WHERE BillNo=9 OR BillNo=10;
		INSERT INTO dbo.PD_SellBill
		(BillCode,BillDate,DlvDate,BTypeID,DeptID,ElyID,WhsID,LogistBTypeID,LogistBillNo,Freight,FreightTotal,FreightFinanceID,FreightType,BillQty,
		BTDTotal,Total,Privilege,PayRecTotal,FinanceID,IsAccounts,PaidTotal,FreightPaidTotal,Creator,CreateTime,PosElyID,PosTime,Summary,Description,Stt,
		Red,StlTag,FreightStlTag,IsDraft,IsOS,InvoiceMode,InvoiceTotal,AuditStatus,VerifyElyID,VerifyDate,IsInvoice,VipCardID,DeductionCent,IsDeduction,ExchangeCent)
		SELECT
		BillCode,        -- BillCode - varchar(50)
		BillDate, -- BillDate - date
		BillDate, -- DlvDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		WB.KTypeID_,         -- WhsID - int
		0,         -- LogistBTypeID - int
		'',        -- LogistBillNo - varchar(20)
		0,      -- Freight - decimal(20, 8)
		0,      -- FreightTotal - decimal(20, 8)
		0,         -- FreightFinanceID - int
		0,      -- FreightType - bit
		WB.DlySumQty,      -- BillQty - decimal(20, 8)
		WB.DlySumTotal,      -- BTDTotal - decimal(20, 8)---折前金额
		WB.Feld2,      -- Total - decimal(20, 8)---折后金额
		WB.PreferenceMoney,      -- Privilege - decimal(20, 8)
		@SumPayTotal,      -- PayRecTotal - decimal(20, 8)
		---表头收付款账户ID：单账户为：账户ID，多账户写：-100，未收款写：0
		CASE WHEN @Accounts=1 THEN @SignPayID WHEN @Accounts>1 THEN -100 ELSE 0 END, -- FinanceID - int
		0,      -- IsAccounts - bit
		0,      -- PaidTotal - decimal(20, 8)
		0,      -- FreightPaidTotal - decimal(20, 8)
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Stt - tinyint
		0,         -- Red - tinyint
		0,         -- StlTag - tinyint
		0,         -- FreightStlTag - tinyint
		1,      -- IsDraft - bit
		0,         -- IsOS - tinyint
		0,         -- InvoiceMode - tinyint
		0,      -- InvoiceTotal - decimal(20, 8)
		0,         -- AuditStatus - tinyint
		0,         -- VerifyElyID - int
		NULL,        -- VerifyDate - varchar(20)
		1,      -- IsInvoice - bit
		0,         -- VipCardID - int
		0,      -- DeductionCent - decimal(10, 0)
		0,      -- IsDeduction - bit
		0       -- ExchangeCent - decimal(10, 0)
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;


		--************************************************************************************
		---销售单表身：
		---SELECT * From dbo.PD_SellDetail WHERE BillNo=9 OR BillNo=10;
		INSERT INTO dbo.PD_SellDetail
		(BillNo,BillDate,OrdDID,BarCode,GoodsID,Ppt1ID,Ppt2ID,WhsID,WhsPtID,UnitID,Convfactor,Price,CostPrice,GoodsCostTotal,DiscPrice,TaxPrice,Qty,BSQty,Total,
		DiscTotal,TaxTotal,Discount,TaxRate,Tax,Gift,Remark,IsReconciled,PriceID,InPutPrice,VerifyQty,ComQty,ComTotal,BatchNumber,ProductDate,EndDate,IsSelectBatch)
		SELECT
		@VchCode,         -- BillNo - bigint
		WB.BillDate, -- BillDate - date
		0,         -- OrdDID - bigint
		ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
		WBL.PTypeID_,         -- GoodsID - bigint
		0,         -- Ppt1ID - int
		0,         -- Ppt2ID - int
		WBL.KTypeID_,         -- WhsID - int
		wp.WhsPtID,         -- WhsPtID - int
		WBL.UnitNum,         -- UnitID - int
		WBL.UnitRate,      -- Convfactor - decimal(20, 8)
		WBL.UnitPrice,      -- Price - decimal(20, 8)
		WBL.CostPrice,      -- CostPrice - decimal(20, 8)
		ISNULL(GS.Price,0)*WBL.BillQTY,      -- GoodsCostTotal - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- DiscPrice - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- TaxPrice - decimal(20, 8)
		WBL.PDAQty,      -- Qty - decimal(20, 8)
		WBL.BillQTY,      -- BSQty - decimal(20, 8)
		WBL.BillTotal,      -- Total - decimal(20, 8)
		WBL.BillDistTotal,      -- DiscTotal - decimal(20, 8)
		WBL.BillDistTotal,      -- TaxTotal - decimal(20, 8)
		WBL.Discount,      -- Discount - decimal(20, 8)
		0,      -- TaxRate - decimal(20, 8)
		0,      -- Tax - decimal(20, 8)
		WBL.DetailType,         -- Gift - tinyint
		WBL.Comment,        -- Remark - varchar(100)
		0,      -- IsReconciled - bit
		CASE WHEN WBL.DetailType=1 THEN 27 ELSE 21 END, -- PriceID - tinyint,27赠品价格，21手动输入
		1,         -- InPutPrice - tinyint
		0,      -- VerifyQty - decimal(20, 8)
		0,      -- ComQty - decimal(20, 8)
		0,      -- ComTotal - decimal(20, 8)
		'',        -- BatchNumber - varchar(50)
		'',        -- ProductDate - varchar(10)
		'',        -- EndDate - varchar(10)
		1       -- IsSelectBatch - bit
		FROM dbo.BD_Whs_Position wp,MdD9_Billindex WB,MdD9_Billindex_List WBL
		LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
		LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
		LEFT JOIN dbo.PD_GoodsStock GS ON gs.GoodsID=WBL.PTypeID_ AND gs.WhsID=WBL.KTypeID_ 
		WHERE  WB.BillNumberID=WBL.BillNumberID AND wp.WhsID=WBL.KTypeID_ AND wp.WhsPtType=1 AND wp.Stt=1 AND
		WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1

		--************************************************************************************
		----多账户收付款记录
		----SELECT * FROM PD_MulAccounts
		IF(@Accounts>1)
		BEGIN
			INSERT INTO dbo.PD_MulAccounts
			(BillTypeID,BillNo,FinanceID,Total)
			SELECT @BillTypeID,@VchCode,BF.FinanceID,WBP.PayTotal
			FROM dbo.MdD9_BillPayData WBP,BD_Finance BF
			WHERE 1=1
			AND WBP.BillID=@BillID AND WBP.PayID=BF.Path
			AND WBP.PayTotal>=0;
			IF(@@ERROR<>0)
				GOTO Error1

		END
		--************************************************************************************
	END
	--********************************************************************************************************
	----END：销售单
	--********************************************************************************************************


	
	--********************************************************************************************************
	----BEGIN：销售退货单
	--********************************************************************************************************
	IF(@BillType='SaleBack')
    BEGIN

		SET @BillTypeID='202';

		--************************************************************************************
		---销售退货单表头：
		---SELECT * From dbo.PD_SellRetBill;
		INSERT INTO dbo.PD_SellRetBill
		(BillCode,BillDate,DlvDate,BTypeID,DeptID,ElyID,WhsID,BillQty,BTDTotal,Total,Privilege,PayRecTotal,FinanceID,IsAccounts,
		PaidTotal,Creator,CreateTime,PosElyID,PosTime,Summary,Description,Stt,Red,StlTag,IsDraft,IsOS,InvoiceMode,InvoiceTotal,
		AuditStatus,IsInvoice,VipCardID,DeductionCent,IsDeduction,ExchangeCent)
		SELECT
		BillCode,        -- BillCode - varchar(50)
		BillDate, -- BillDate - date
		BillDate, -- DlvDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		WB.KTypeID_,         -- WhsID - int
		WB.DlySumQty,      -- BillQty - decimal(20, 8)
		WB.DlySumTotal,      -- BTDTotal - decimal(20, 8)---折前金额
		WB.Feld2,      -- Total - decimal(20, 8)---折后金额
		CAST(WB.PreferenceMoney AS NUMERIC(28,2)),      -- Privilege - decimal(20, 8)
		@SumPayTotal,      -- PayRecTotal - decimal(20, 8)
		---表头收付款账户ID：单账户为：账户ID，多账户写：-100，未收款写：0
		CASE WHEN @Accounts=1 THEN @SignPayID WHEN @Accounts>1 THEN -100 ELSE 0 END, -- FinanceID - int
		0,      -- IsAccounts - bit
		0,      -- PaidTotal - decimal(20, 8)
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Stt - tinyint
		0,         -- Red - tinyint
		0,         -- StlTag - tinyint
		1,      -- IsDraft - bit
		0,         -- IsOS - tinyint
		0,         -- InvoiceMode - tinyint
		0,      -- InvoiceTotal - decimal(20, 8)
		0,         -- AuditStatus - tinyint
		1,      -- IsInvoice - bit
		0,         -- VipCardID - int
		0,      -- DeductionCent - decimal(10, 0)
		0,      -- IsDeduction - bit
		0       -- ExchangeCent - decimal(10, 0)
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;

		--************************************************************************************
		---销售退货单表身：
		---SELECT * From dbo.PD_SellRetDetail;
		INSERT INTO dbo.PD_SellRetDetail
		(BillNo,BillDate,BarCode,GoodsID,Ppt1ID,Ppt2ID,WhsID,WhsPtID,UnitID,Convfactor,Price,CostPrice,GoodsCostTotal,DiscPrice,TaxPrice,Qty,BSQty,Total,
		DiscTotal,TaxTotal,Discount,TaxRate,Tax,Gift,Remark,IsReconciled,PriceID,InPutPrice,SellDID,BatchNumber,ProductDate,EndDate,IsSelectBatch)
		SELECT
		@VchCode,         -- BillNo - bigint
		WB.BillDate, -- BillDate - date
		ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
		WBL.PTypeID_,         -- GoodsID - bigint
		0,         -- Ppt1ID - int
		0,         -- Ppt2ID - int
		WBL.KTypeID_,         -- WhsID - int
		wp.WhsPtID,         -- WhsPtID - int
		WBL.UnitNum,         -- UnitID - int
		WBL.UnitRate,      -- Convfactor - decimal(20, 8)
		WBL.UnitPrice,      -- Price - decimal(20, 8)
		WBL.CostPrice,      -- CostPrice - decimal(20, 8)
		CAST(WBL.CostPrice*WBL.PDAQty AS NUMERIC(28,2)),      -- GoodsCostTotal - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- DiscPrice - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- TaxPrice - decimal(20, 8)
		WBL.PDAQty,      -- Qty - decimal(20, 8)
		WBL.BillQTY,      -- BSQty - decimal(20, 8)
		WBL.BillTotal,      -- Total - decimal(20, 8)
		WBL.BillDistTotal,      -- DiscTotal - decimal(20, 8)
		WBL.BillDistTotal,      -- TaxTotal - decimal(20, 8)
		WBL.Discount,      -- Discount - decimal(20, 8)
		0,      -- TaxRate - decimal(20, 8)
		0,      -- Tax - decimal(20, 8)
		WBL.DetailType,         -- Gift - tinyint
		WBL.Comment,        -- Remark - varchar(100)
		0,      -- IsReconciled - bit
		CASE WHEN WBL.DetailType=1 THEN 27 ELSE 21 END, -- PriceID - tinyint,27赠品价格，21手动输入
		1,         -- InPutPrice - tinyint
		0,   --SellDID  - bigint
		'',        -- BatchNumber - varchar(50)
		'',        -- ProductDate - varchar(10)
		'',        -- EndDate - varchar(10)
		0       -- IsSelectBatch - bit
		FROM dbo.BD_Whs_Position wp,MdD9_Billindex WB,MdD9_Billindex_List WBL
		LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
		LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
		WHERE 1=1 AND WB.BillNumberID=WBL.BillNumberID AND wp.WhsID=WBL.KTypeID_ AND wp.WhsPtType=1 AND wp.Stt=1 AND
		WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1

		--************************************************************************************
		----多账户收付款记录
		----SELECT * FROM PD_MulAccounts
		IF(@Accounts>1)
		BEGIN
			INSERT INTO dbo.PD_MulAccounts
			(BillTypeID,BillNo,FinanceID,Total)
			SELECT @BillTypeID,@VchCode,BF.FinanceID,WBP.PayTotal
			FROM dbo.MdD9_BillPayData WBP,BD_Finance BF
			WHERE 1=1
			AND WBP.BillID=@BillID AND WBP.PayID=BF.Path
			AND WBP.PayTotal>=0;
			IF(@@ERROR<>0)
				GOTO Error1

		END
		--************************************************************************************

	END
	--********************************************************************************************************
	----END：销售退单
	--********************************************************************************************************



	--********************************************************************************************************
	----BEGIN：进货单
	--********************************************************************************************************
	IF(@BillType='Buy')
    BEGIN
		SET @BillTypeID='101';

		--************************************************************************************
		---表头：
		---SELECT * From dbo.PD_PchBill;
		INSERT INTO dbo.PD_PchBill
		(BillCode,BillDate,DlvDate,BTypeID,DeptID,ElyID,WhsID,LogistBTypeID,Freight,FreightTotal,FreightFinanceID,BillQty,
		BTDTotal,Total,Privilege,PayRecTotal,FinanceID,IsAccounts,PaidTotal,FreightPaidTotal,Creator,CreateTime,PosElyID,PosTime,Summary,Description,Stt,
		Red,StlTag,FreightStlTag,IsDraft,InvoiceMode,InvoiceTotal,AuditStatus,VerifyElyID,VerifyDate,IsInvoice)
		SELECT
		BillCode,        -- BillCode - varchar(50)
		BillDate, -- BillDate - date
		BillDate, -- DlvDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		WB.KTypeID_,         -- WhsID - int
		0,         -- LogistBTypeID - int
		0,      -- Freight - decimal(20, 8)
		0,      -- FreightTotal - decimal(20, 8)
		0,         -- FreightFinanceID - int
		WB.DlySumQty,      -- BillQty - decimal(20, 8)
		WB.DlySumTotal,      -- BTDTotal - decimal(20, 8)---折前金额
		WB.Feld2,      -- Total - decimal(20, 8)---折后金额
		WB.PreferenceMoney,      -- Privilege - decimal(20, 8)
		@SumPayTotal,      -- PayRecTotal - decimal(20, 8)
		---表头收付款账户ID：单账户为：账户ID，多账户写：-100，未收款写：0
		CASE WHEN @Accounts=1 THEN @SignPayID WHEN @Accounts>1 THEN -100 ELSE 0 END, -- FinanceID - int
		0,      -- IsAccounts - bit
		0,      -- PaidTotal - decimal(20, 8)
		0,      -- FreightPaidTotal - decimal(20, 8)
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Stt - tinyint
		0,         -- Red - tinyint
		0,         -- StlTag - tinyint
		0,         -- FreightStlTag - tinyint
		1,      -- IsDraft - bit
		0,         -- InvoiceMode - tinyint
		0,      -- InvoiceTotal - decimal(20, 8)
		0,         -- AuditStatus - tinyint
		0,         -- VerifyElyID - int
		NULL,        -- VerifyDate - varchar(20)
		1      -- IsInvoice - bit
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;


		--************************************************************************************
		---表身：
		---SELECT * From dbo.PD_PchDetail;
		INSERT INTO dbo.PD_PchDetail
		(BillNo,BillDate,OrdDID,BarCode,GoodsID,Ppt1ID,Ppt2ID,WhsID,WhsPtID,UnitID,Convfactor,Price,CostPrice,GoodsCostTotal,DiscPrice,TaxPrice,Qty,BSQty,Total,
		DiscTotal,TaxTotal,Discount,TaxRate,Tax,Gift,Remark,IsReconciled,Freight,InPrice,InTotal,PriceID,InPutPrice,VerifyQty,ComQty,ComTotal,BatchNumber,ProductDate,EndDate)
		SELECT
		@VchCode,         -- BillNo - bigint
		WB.BillDate, -- BillDate - date
		0,         -- OrdDID - bigint
		ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
		WBL.PTypeID_,         -- GoodsID - bigint
		0,         -- Ppt1ID - int
		0,         -- Ppt2ID - int
		WBL.KTypeID_,         -- WhsID - int
		wp.WhsPtID,         -- WhsPtID - int
		WBL.UnitNum,         -- UnitID - int
		WBL.UnitRate,      -- Convfactor - decimal(20, 8)
		WBL.UnitPrice,      -- Price - decimal(20, 8)
		WBL.BillDistPrice,      -- CostPrice - decimal(20, 8)
		WBL.BillDistTotal,      -- GoodsCostTotal - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- DiscPrice - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- TaxPrice - decimal(20, 8)
		WBL.PDAQty,      -- Qty - decimal(20, 8)
		WBL.BillQTY,      -- BSQty - decimal(20, 8)
		WBL.BillTotal,      -- Total - decimal(20, 8)
		WBL.BillDistTotal,      -- DiscTotal - decimal(20, 8)
		WBL.BillDistTotal,      -- TaxTotal - decimal(20, 8)
		WBL.Discount,      -- Discount - decimal(20, 8)
		0,      -- TaxRate - decimal(20, 8)
		0,      -- Tax - decimal(20, 8)
		WBL.DetailType,         -- Gift - tinyint
		WBL.Comment,        -- Remark - varchar(100)
		0,      -- IsReconciled - bit
		0,      -- Freight - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- InPrice - decimal(20, 8)
		WBL.BillDistTotal,      -- InTotal - decimal(20, 8)
		CASE WHEN WBL.DetailType=1 THEN 27 ELSE 21 END, -- PriceID - tinyint,27赠品价格，21手动输入
		1,         -- InPutPrice - tinyint
		0,      -- VerifyQty - decimal(20, 8)
		0,      -- ComQty - decimal(20, 8)
		0,      -- ComTotal - decimal(20, 8)
		'',        -- BatchNumber - varchar(50)
		'',        -- ProductDate - varchar(10)
		''        -- EndDate - varchar(10)
		FROM dbo.BD_Whs_Position wp,MdD9_Billindex WB,MdD9_Billindex_List WBL
		LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
		LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
		LEFT JOIN dbo.PD_GoodsStock GS ON gs.GoodsID=WBL.PTypeID_ AND gs.WhsID=WBL.KTypeID_ 
		WHERE WB.BillNumberID=WBL.BillNumberID AND wp.WhsID=WBL.KTypeID_ AND wp.WhsPtType=1 AND wp.Stt=1 AND
		WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1

		--************************************************************************************
		----多账户收付款记录
		----SELECT * FROM PD_MulAccounts
		IF(@Accounts>1)
		BEGIN
			INSERT INTO dbo.PD_MulAccounts
			(BillTypeID,BillNo,FinanceID,Total)
			SELECT @BillTypeID,@VchCode,BF.FinanceID,WBP.PayTotal
			FROM dbo.MdD9_BillPayData WBP,BD_Finance BF
			WHERE 1=1
			AND WBP.BillID=@BillID AND WBP.PayID=BF.Path
			AND WBP.PayTotal>=0;
			IF(@@ERROR<>0)
				GOTO Error1

		END
		--************************************************************************************

	END
	--********************************************************************************************************
	----END：进货单
	--********************************************************************************************************




	--********************************************************************************************************
	----BEGIN：进货退单
	--********************************************************************************************************
	IF(@BillType='BuyBack')
    BEGIN
		SET @BillTypeID='102';

		--************************************************************************************
		---表头：
		---SELECT * From dbo.PD_PchRetBill;
		INSERT INTO dbo.PD_PchRetBill
		(BillCode,BillDate,DlvDate,BTypeID,DeptID,ElyID,WhsID,BillQty,BTDTotal,Total,Privilege,PayRecTotal,FinanceID,IsAccounts,
		PaidTotal,Creator,CreateTime,PosElyID,PosTime,Summary,Description,Stt,Red,StlTag,IsDraft,InvoiceMode,InvoiceTotal,
		AuditStatus,IsInvoice)
		SELECT
		BillCode,        -- BillCode - varchar(50)
		BillDate, -- BillDate - date
		BillDate, -- DlvDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		WB.KTypeID_,         -- WhsID - int
		WB.DlySumQty,      -- BillQty - decimal(20, 8)
		WB.DlySumTotal,      -- BTDTotal - decimal(20, 8)---折前金额
		WB.Feld2,      -- Total - decimal(20, 8)---折后金额
		WB.PreferenceMoney,      -- Privilege - decimal(20, 8)
		@SumPayTotal,      -- PayRecTotal - decimal(20, 8)
		---表头收付款账户ID：单账户为：账户ID，多账户写：-100，未收款写：0
		CASE WHEN @Accounts=1 THEN @SignPayID WHEN @Accounts>1 THEN -100 ELSE 0 END, -- FinanceID - int
		0,      -- IsAccounts - bit
		0,      -- PaidTotal - decimal(20, 8)
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Stt - tinyint
		0,         -- Red - tinyint
		0,         -- StlTag - tinyint
		1,      -- IsDraft - bit
		0,         -- InvoiceMode - tinyint
		0,      -- InvoiceTotal - decimal(20, 8)
		0,         -- AuditStatus - tinyint
		1      -- IsInvoice - bit
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;


		--************************************************************************************
		---表身：
		---SELECT * From dbo.PD_PchRetDetail;
		INSERT INTO dbo.PD_PchRetDetail
		(BillNo,BillDate,BarCode,GoodsID,Ppt1ID,Ppt2ID,WhsID,WhsPtID,UnitID,Convfactor,Price,CostPrice,GoodsCostTotal,DiscPrice,TaxPrice,Qty,BSQty,Total,
		DiscTotal,TaxTotal,Discount,TaxRate,Tax,Gift,Remark,IsReconciled,PriceID,InPutPrice,PchDID,BatchNumber,ProductDate,EndDate,IsSelectBatch)
		SELECT
		@VchCode,         -- BillNo - bigint
		WB.BillDate, -- BillDate - date
		ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
		WBL.PTypeID_,         -- GoodsID - bigint
		0,         -- Ppt1ID - int
		0,         -- Ppt2ID - int
		WBL.KTypeID_,         -- WhsID - int
		wp.WhsPtID,         -- WhsPtID - int
		WBL.UnitNum,         -- UnitID - int
		WBL.UnitRate,      -- Convfactor - decimal(20, 8)
		WBL.UnitPrice,      -- Price - decimal(20, 8)
		ISNULL(GS.Price,0),      -- CostPrice - decimal(20, 8)
		ISNULL(gs.Total,0),      -- GoodsCostTotal - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- DiscPrice - decimal(20, 8)
		WBL.UnitPrice*Discount,      -- TaxPrice - decimal(20, 8)
		WBL.PDAQty,      -- Qty - decimal(20, 8)
		WBL.BillQTY,      -- BSQty - decimal(20, 8)
		WBL.BillTotal,      -- Total - decimal(20, 8)
		WBL.BillDistTotal,      -- DiscTotal - decimal(20, 8)
		WBL.BillDistTotal,      -- TaxTotal - decimal(20, 8)
		WBL.Discount,      -- Discount - decimal(20, 8)
		0,      -- TaxRate - decimal(20, 8)
		0,      -- Tax - decimal(20, 8)
		WBL.DetailType,         -- Gift - tinyint
		WBL.Comment,        -- Remark - varchar(100)
		0,      -- IsReconciled - bit
		CASE WHEN WBL.DetailType=1 THEN 27 ELSE 21 END, -- PriceID - tinyint,27赠品价格，21手动输入
		1,         -- InPutPrice - tinyint
		0,   --PchDID  - bigint
		'',        -- BatchNumber - varchar(50)
		'',        -- ProductDate - varchar(10)
		'',        -- EndDate - varchar(10)
		1       -- IsSelectBatch - bit
		FROM dbo.BD_Whs_Position wp,MdD9_Billindex WB,MdD9_Billindex_List WBL
		LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
		LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
		LEFT JOIN dbo.PD_GoodsStock GS ON gs.GoodsID=WBL.PTypeID_ AND gs.WhsID=WBL.KTypeID_ 
		WHERE WB.BillNumberID=WBL.BillNumberID AND wp.WhsID=WBL.KTypeID_ AND wp.WhsPtType=1 AND wp.Stt=1 AND
		WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1

		--************************************************************************************
		----多账户收付款记录
		----SELECT * FROM PD_MulAccounts
		IF(@Accounts>1)
		BEGIN
			INSERT INTO dbo.PD_MulAccounts
			(BillTypeID,BillNo,FinanceID,Total)
			SELECT @BillTypeID,@VchCode,BF.FinanceID,WBP.PayTotal
			FROM dbo.MdD9_BillPayData WBP,BD_Finance BF
			WHERE 1=1
			AND WBP.BillID=@BillID AND WBP.PayID=BF.Path
			AND WBP.PayTotal>=0;
			IF(@@ERROR<>0)
				GOTO Error1

		END
		--************************************************************************************
	END
	--********************************************************************************************************
	----END：进货退单
	--********************************************************************************************************




	--********************************************************************************************************
	----BEGIN：仓库调拨单
	--********************************************************************************************************
	IF(@BillType='SameMove')
    BEGIN
		SET @BillTypeID='301';

		--************************************************************************************
		---表头：
		---SELECT * From dbo.PD_AllotBill;
		INSERT INTO dbo.PD_AllotBill
		(BillCode,BillDate,OutWhsID,InWhsID,DeptID,ElyID,BillQty,Total,Creator,CreateTime,
		PosElyID,PosTime,Summary,Description,Red,IsDraft,BillTypeID,InspectTag,AuditStatus,VerifyElyID,VerifyDate)
		SELECT
		BillCode,        -- BillCode - varchar(50)
		BillDate, -- BillDate - date
		WB.KTypeID_,         -- OutWhsID - int
		WB.KTypeID2_,         -- InWhsID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		WB.DlySumQty,      -- BillQty - decimal(20, 8)
		WB.DlySumTotal,      -- Total - decimal(20, 8)
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Red - tinyint
		1,      -- IsDraft - bit
		@BillTypeID,         -- BillTypeID - int
		1,         -- InspectTag - tinyint
		0,         -- AuditStatus - tinyint
		0,         -- VerifyElyID - int
		NULL         -- VerifyDate - varchar(20)
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;

		--************************************************************************************
		---表身：
		---SELECT * From dbo.PD_AllotDetail;
		INSERT INTO dbo.PD_AllotDetail
		(ReqDID,BillNo,BillDate,BarCode,GoodsID,Ppt1ID,Ppt2ID,InWhsID,InWhsPtID,OutWhsID,OutWhsPtID,UnitID,Convfactor,Qty,BSQty,
		CostPrice,GoodsCostTotal,AllotPrice,AllotTotal,Remark,InspectQty,InPutPrice,VerifyQty,BatchNumber,ProductDate,EndDate,IsSelectBatch)
		SELECT
		0,         -- ReqDID - bigint
		@VchCode,         -- BillNo - bigint
		WB.BillDate, -- BillDate - date
		ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
		WBL.PTypeID_,         -- GoodsID - bigint
		0,         -- Ppt1ID - int
		0,         -- Ppt2ID - int
		WB.KTypeID2_,         -- InWhsID - int
		wpi.WhsPtID,         -- InWhsPtID - int
		WB.KTypeID_,         -- OutWhsID - int
		wpo.WhsPtID,         -- OutWhsPtID - int
		WBL.UnitNum,         -- UnitID - int
		WBL.UnitRate,      -- Convfactor - decimal(20, 8)
		WBL.PDAQty,      -- Qty - decimal(20, 8)
		WBL.BillQTY,      -- BSQty - decimal(20, 8)
		WBL.CostPrice,      -- CostPrice - decimal(20, 8)
		CAST(WBL.CostPrice*WBL.BillQTY AS NUMERIC(28,2)),      -- GoodsCostTotal - decimal(20, 8)
		WBL.UnitPrice,      -- AllotPrice - decimal(20, 8)
		CAST(WBL.CostPrice*WBL.BillQTY AS NUMERIC(28,2)),      -- AllotTotal - decimal(20, 8)
		WBL.Comment,        -- Remark - varchar(100)
		WBL.BillQTY,      -- InspectQty - decimal(20, 8)
		1,         -- InPutPrice - tinyint
		0,      -- VerifyQty - decimal(20, 8)
		'',        -- BatchNumber - varchar(50)
		'',        -- ProductDate - varchar(10)
		'',        -- EndDate - varchar(10)
		1       -- IsSelectBatch - bit
		FROM dbo.BD_Whs_Position wpi,dbo.BD_Whs_Position wpo,MdD9_Billindex WB,MdD9_Billindex_List WBL
		LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
		LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
		WHERE 1=1 AND WB.BillNumberID=WBL.BillNumberID  AND wpi.WhsID=WB.KTypeID2_ AND wpi.WhsPtType=1 AND wpi.Stt=1 
		 AND wpo.WhsID=WB.KTypeID_ AND wpo.WhsPtType=1 AND wpo.Stt=1 AND
		WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1


	END
	--********************************************************************************************************
	----END：仓库调拨单
	--********************************************************************************************************




	--********************************************************************************************************
	----BEGIN：其它出库单
	--********************************************************************************************************
	IF(@BillType='OtherOutBill')
    BEGIN
		SET @BillTypeID='304';

		--************************************************************************************
		---表头：
		---SELECT * From dbo.PD_InOutWhsBill;
		INSERT INTO dbo.PD_InOutWhsBill
		(BillTypeID,BillCode,BillDate,BTypeID,DeptID,ElyID,WhsID,BillQty,Total,Creator,CreateTime,PosElyID,PosTime,
		Summary,Description,Red,IsDraft,AuditStatus,VipCardID,ExchangeCent)
		SELECT
		@BillTypeID,         -- BillTypeID - int
		WB.BillCode,        -- BillCode - varchar(50)
		WB.BillDate, -- BillDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		WB.KTypeID_,         -- WhsID - int
		WB.DlySumQty,      -- BillQty - decimal(20, 8)
		WB.DlySumTotal,      -- Total - decimal(20, 8)
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Red - tinyint
		1,      -- IsDraft - bit
		0,         -- AuditStatus - tinyint
		0,         -- VipCardID - int
		0       -- ExchangeCent - decimal(10, 0)
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;


		--************************************************************************************
		---表身：
		---SELECT * From dbo.PD_InOutWhsDetail;
		INSERT INTO dbo.PD_InOutWhsDetail
		(BillNo,BillDate,BarCode,GoodsID,Ppt1ID,Ppt2ID,WhsID,WhsPtID,UnitID,Convfactor,Qty,
		BSQty,Price,CostPrice,GoodsCostTotal,Remark,InPutPrice,BatchNumber,ProductDate,EndDate,IsSelectBatch)
		SELECT
		@VchCode,         -- BillNo - bigint
		WB.BillDate, -- BillDate - date
		ISNULL(BGP.BarCode,''),        -- BarCode - varchar(30)
		WBL.PTypeID_,         -- GoodsID - bigint
		0,         -- Ppt1ID - int
		0,         -- Ppt2ID - int
		WBL.KTypeID_,         -- WhsID - int
		wp.WhsPtID,         -- WhsPtID - int
		WBL.UnitNum,         -- UnitID - int
		WBL.UnitRate,      -- Convfactor - decimal(20, 8)
		WBL.PDAQty,      -- Qty - decimal(20, 8)
		WBL.BillQTY,      -- BSQty - decimal(20, 8)
		WBL.UnitPrice,      -- Price - decimal(20, 8)
		WBL.CostPrice,      -- CostPrice - decimal(20, 8)
		CAST(WBL.BillDistTotal AS NUMERIC(28,2)),      -- GoodsCostTotal - decimal(20, 8)
		WBL.Comment,        -- Remark - varchar(100)
		1,         -- InPutPrice - tinyint
		'',        -- BatchNumber - varchar(50)
		'',        -- ProductDate - varchar(10)
		'',        -- EndDate - varchar(10)
		1       -- IsSelectBatch - bit
		FROM dbo.BD_Whs_Position wp,MdD9_Billindex WB,MdD9_Billindex_List WBL
		LEFT JOIN BD_Goods P ON WBL.PTypeID_=P.GoodsID
		LEFT JOIN dbo.BD_Goods_Price BGP ON WBL.PTypeID_=BGP.GoodsID AND WBL.UnitNum=BGP.UnitID
		WHERE 1=1 AND WB.BillNumberID=WBL.BillNumberID AND wp.WhsID=WBL.KTypeID_ AND wp.WhsPtType=1 AND wp.Stt=1 AND
		WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1

	END
	--********************************************************************************************************
	----END：其它出库单
	--********************************************************************************************************



	--********************************************************************************************************
	----BEGIN：收款单\付款单
	--********************************************************************************************************
	IF(@BillType='CollectionBill' OR @BillType='PayBill')
    BEGIN
		
		IF(@BillType='CollectionBill')
		BEGIN
		SET @BillTypeID='402';
		END
		IF(@BillType='PayBill')
		BEGIN
		SET @BillTypeID='401';
		END
        
		

		--************************************************************************************
		---表头：
		---SELECT * From dbo.MF_PayRecBill;
		INSERT INTO dbo.MF_PayRecBill
		(BillTypeID,BillCode,BillDate,BTypeID,DeptID,ElyID,BPTotal,Privilege,Total,Creator,CreateTime,
		PosElyID,PosTime,Summary,Description,Red,StlTag,IsDraft,AuditStatus)
		SELECT
		@BillTypeID,         -- BillTypeID - int
		WB.BillCode,        -- BillCode - varchar(50)
		WB.BillDate, -- BillDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		---预收付账款金额，如果是按单结算没有结算单据需处理成预收金额，如果是按金额结算写0
		CASE WHEN @AccountType='1' THEN WB.DlySumTotal ELSE 0 END,-- BPTotal - decimal(20, 8) 预收付账款金额  
		WB.PreferenceMoney,  -- Privilege - decimal(20, 8)
		WB.DlySumTotal,      -- Total - decimal(20, 8) --收付款金额合计
		WB.UserTypeID,       -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Red - tinyint
		0,         -- StlTag - tinyint
		1,      -- IsDraft - bit
		0          -- AuditStatus - tinyint
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;


		--************************************************************************************
		---表身：
		---SELECT * From dbo.MF_PayRecDetail;
		INSERT INTO dbo.MF_PayRecDetail
		(BillNo,FinanceID,Total,Remark)
		SELECT
		@VchCode,    -- BillNo - bigint
		BF.FinanceID,    -- FinanceID - int
		WBL.UnitPrice, -- Total - decimal(20, 8)
		WBL.Comment    -- Remark - varchar(100)
		FROM MdD9_Billindex WB,MdD9_Billindex_List WBL,dbo.BD_Finance BF
		WHERE 1=1 AND WB.BillNumberID=WBL.BillNumberID 
		AND WBL.PTypeID_=BF.Path AND wbl.PTypeID_<>''
		AND WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1


	END
	--********************************************************************************************************
	----END：收款单\付款单
	--********************************************************************************************************





	--********************************************************************************************************
	----BEGIN：一般费用单\现金费用单
	--********************************************************************************************************
	IF(@BillType='MoneyBill' OR @BillType='CashBill')
    BEGIN
		IF(@BillType='MoneyBill')
		BEGIN
		SET @BillTypeID='404';
		END
        ELSE IF (@BillType='CashBill')
		BEGIN
		SET @BillTypeID='403';
		END

		

		--************************************************************************************
		---表头：
		---SELECT * From dbo.MF_FeeRecBill;
		INSERT INTO dbo.MF_FeeRecBill
		(BillTypeID,BillCode,BillDate,BTypeID,DeptID,ElyID,FinanceID,PayRecTotal,Total,PaidTotal,
		Creator,CreateTime,PosElyID,PosTime,Summary,Description,Red,StlTag,IsDraft,IsOS,AuditStatus)
		SELECT
		@BillTypeID,         -- BillTypeID - int
		WB.BillCode,        -- BillCode - varchar(50)
		WB.BillDate, -- BillDate - date
		WB.BTypeID_,         -- BTypeID - int
		WB.DTypeID_,         -- DeptID - int
		WB.ETypeID_,         -- ElyID - int
		---表头收付款账户ID：单账户为：账户ID，多账户写：-100，未收款写：0
		CASE WHEN @Accounts=1 THEN @SignPayID WHEN @Accounts>1 THEN -100 ELSE 0 END, -- FinanceID - int
		@SumPayTotal,      -- PayRecTotal - decimal(20, 8)
		WB.DlySumTotal,      -- Total - decimal(20, 8)
		0,      -- PaidTotal - decimal(20, 8)
		WB.UserTypeID,         -- Creator - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- CreateTime - datetime
		0,         -- PosElyID - int
		CONVERT(VARCHAR(50),GETDATE(),121), -- PosTime - datetime
		WB.Comment,        -- Summary - varchar(256)
		@BillComment,        -- Description - varchar(100)
		0,         -- Red - tinyint
		0,         -- StlTag - tinyint
		1,      -- IsDraft - bit
		0,         -- IsOS - tinyint
		0          -- AuditStatus - tinyint
		FROM dbo.MdD9_Billindex WB
		WHERE WB.BillNumberID=@BillID;
		IF(@@ERROR<>0)
			GOTO Error1
    
		SELECT @VchCode=@@IDENTITY;


		--************************************************************************************
		---表身：
		---SELECT * From dbo.MF_FeeRecDetail;
		INSERT INTO dbo.MF_FeeRecDetail
		(BillNo,FinanceID,Total,Remark)
		SELECT
		@VchCode,    -- BillNo - bigint
		BF.FinanceID,    -- FinanceID - int
		WBL.UnitPrice, -- Total - decimal(20, 8)
		WBL.Comment    -- Remark - varchar(100)
		FROM MdD9_Billindex WB,MdD9_Billindex_List WBL,dbo.BD_Finance BF
		WHERE 1=1 AND WB.BillNumberID=WBL.BillNumberID
		AND WBL.PTypeID_=BF.Path AND wbl.PTypeID_<>''
		AND WB.BillNumberID=@BillID  ORDER BY WBL.DetailRowID;
		IF(@@ERROR<>0)
			GOTO Error1
		
		--************************************************************************************
		----多账户收付款记录
		----SELECT * FROM PD_MulAccounts
		IF(@Accounts>1)
		BEGIN
			INSERT INTO dbo.PD_MulAccounts
			(BillTypeID,BillNo,FinanceID,Total)
			SELECT @BillTypeID,@VchCode,BF.FinanceID,WBP.PayTotal
			FROM dbo.MdD9_BillPayData WBP,BD_Finance BF
			WHERE 1=1
			AND WBP.BillID=@BillID AND WBP.PayID=BF.Path
			AND WBP.PayTotal>=0;
			IF(@@ERROR<>0)
				GOTO Error1

		END
		--************************************************************************************

	END
	--********************************************************************************************************
	----END：一般费用单\现金费用单
	--********************************************************************************************************
	

   
   
   
   
   --********************************************************************************************************
   ----虚拟库存处理
   --********************************************************************************************************
   
   --********************************************************************************************************
   
   
   
   --********************************************************************************************************
   ----发送单据消息
   --********************************************************************************************************
   --Insert Into Xw_Message(SendID,ReciveID,SendDate,MSG,MSGAddTion,MSGType,New,Deleted)
   --Select WB.UserTypeID,LU.ETypeID,Getdate(),'【'+ @ProductName + '】-提醒您:'+ Char(13) + Char(13) 
   --+'【'+ WB.LoginName +'】开了一张单据编号为【'+ WB.BillCode +'】 的'+@BillName +'!','','0','1','0' 
   --From LoginUser LU,dbo.MdD9_Billindex WB
   --WHERE 1=1 AND WB.BillNumberID=@BillID;
   --IF(@@ERROR<>0)
   --    GOTO Error1
   
   
   Update WB SET State='3',VchCode=@VchCode 
   FROM MdD9_BillIndex WB
   where WB.BillNumberID=@BillID and WB.State='1';
   IF(@@ERROR<>0)
       GOTO Error1
   
   --********************************************************************************************************
   END
   --********************************************************************************************************
   
   
   
   --******************************************
   COMMIT TRAN
   SET @ReturnValue=1;
   SELECT @ReturnValue AS ReturnValue;
   RETURN;
   --******************************************
  Error1:
   ROLLBACK TRAN;
   SELECT @ReturnValue AS ReturnValue;

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO











--升级手机版操作员
INSERT INTO dbo.MdD9_User
(
	SysType,
	LoginID,
	LoginName,
	TypeID_,
	FullName,
	IsStop,
	Deleted,
	LoginCode,
	WeiXinIsStop,
	loginset,
	LimitAutoSync,
	ETypeID_,
	EFullName,
	[PassWord]
)
SELECT	0,
		s.ElyId,
		e.ElyName,
		s.ElyId,
		e.ElyName,
		0,
		0,
		s.ElyId,
		0,
		0,
		0,
		s.ElyId,
		e.ElyName,
		s.[PassWord]
FROM	SS_Operator s,
		BD_Employee e
WHERE	S.ElyID = e.ElyID
		AND s.ElyID NOT IN (SELECT LoginID FROM dbo.MdD9_User)
		AND S.ElyID <> 1
		
--特殊处理ETypeID_
UPDATE dbo.MdD9_User SET ETypeID_ = LoginID WHERE ISNULL(ETypeId_,'') = ''		
UPDATE dbo.MdD9_User SET TypeID_ = LoginID WHERE ISNULL(TypeID_,'') = ''
		
--- 将新增用户赋予全部权限
INSERT  INTO dbo.MdD9_UserLimit
( 
    Sort ,
    SortNum ,
    SortName ,
    TypeID_ ,
    LimitType ,
    LimitName ,
    LimitValue ,
    xiwamaxtime ,
    Deleted ,
    Comment
)
SELECT  MULT.Sort ,
        MULT.SortNum ,
        MULT.SortName ,
        MU.LoginID ,
        MULT.LimitType ,
        MULT.LimitName ,
        1 ,
        ( SELECT    CONVERT(VARCHAR, GETDATE(), 120)
        ) ,
        0 ,
        MULT.Comment
FROM    dbo.MdD9_UserLimitType MULT ,
        dbo.MdD9_User MU
WHERE   NOT EXISTS ( SELECT *
                        FROM   MdD9_UserLimit WUL
                        WHERE  MULT.LimitType = WUL.LimitType
								AND WUL.TypeID_ = MU.LoginID )
        AND MU.Deleted = 0
        AND MU.LoginID <> ''
                            
---- 新增用户赋予全部价格类型权限
INSERT INTO dbo.MdD9_UserPriceLimit (loginid , PriceType , xiwamaxtime ,FullName)
SELECT MU.LoginID,MPT.PriceType,(select CONVERT(varchar,GETDATE(),120)), MPT.FullName 
FROM MdD9_PriceType MPT ,dbo.MdD9_User MU WHERE MU.LoginID NOT IN (SELECT loginid FROM MdD9_UserPriceLimit)                            
                    
---- 新增用户赋予自身的管辖人员权限
INSERT INTO dbo.MdD9_UserRight ( LoginID, RightID, xiwamaxtime ) 
SELECT MU.LoginID,MU.LoginID,(select CONVERT(varchar,GETDATE(),120)) FROM MdD9_User MU
WHERE MU.LoginID NOT IN (SELECT LoginID FROM dbo.MdD9_UserRight)                    



---修改自动的版本日期
GO
UPDATE SYS_SysData SET SubValue = CONVERT(VARCHAR(30),GETDATE(),120) WHERE SubName = 'packdatetime'
GO




SET NOCOUNT OFF
