SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<gcy>
-- Create date: <2008-3-31>
-- Description:	<新增楼宇订单统计>
-- =============================================
CREATE FUNCTION [dbo].[f_newBuildOrder]
(		
	@state int,
	@startDate_time varchar(20), 
	@endDate_time varchar(20)	
)
RETURNS TABLE 
AS
RETURN 
(
--	if @state>-100 begin
		select z.name as zoneName,t.*  from (
			select areaName,count(v_order_generalList.id) as orderCount,sum(total) as orderTotal ,tbl_area.zoneID,areaId		
			from v_order_generalList  left join tbl_area on areaID = tbl_area.id      							 
			where  isdelete = 0 and date_time between @startDate_time and @endDate_time and areaid not in 
			(
				select areaid from v_order_generalList where date_time < @startDate_time and state = @state
			) 
			and v_order_generalList.state = @state
			group by areaID, areaName,tbl_area.zoneID
		) as t left join tbl_zone z on z.id=t.zoneID
--	end else begin
--		select z.name as zoneName,t.*  from (
--			select areaName,count(v_order_generalList.id) as orderCount,sum(total) as orderTotal ,tbl_area.zoneID,areaId		
--			from v_order_generalList  left join tbl_area on areaID = tbl_area.id      							 
--			where  isdelete = 0 and date_time between @startDate_time and @endDate_time and areaid not in 
--			(
--				select areaid from v_order_generalList where date_time < @startDate_time
--			) 			
--			group by areaID, areaName,tbl_area.zoneID
--		) as t left join tbl_zone z on z.id=t.zoneID
--	end
)


GO
/****** 对象:  UserDefinedFunction [dbo].[f_Reports_OrderComparisonByArea]    脚本日期: 02/01/2010 11:43:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <2008-6-24>
-- Description:	<订单对比分析——按楼宇>
-- =============================================
CREATE FUNCTION [dbo].[f_Reports_OrderComparisonByArea]
(	
	@OrderState int,
	@AreaManagerId int,
	@BeginTime1 datetime,
	@EndTime1 datetime,
	@BeginTime2 datetime,
	@EndTime2 datetime
)
RETURNS TABLE 
AS
RETURN 
(
	select Id, Name,
	(
		select isnull(sum(Total), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime1 and Date_Time<@EndTime1
			and AreaId=Area.id
		) as TotalAmount1,
		(
		select isnull(count(id), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime1 and Date_Time<@EndTime1
			and AreaId=Area.id
		) as TotalCount1,
		(
		select isnull(sum(Total), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime2 and Date_Time<@EndTime2
			and AreaId=Area.id
		) as TotalAmount2,
		(
		select isnull(count(id), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime2 and Date_Time<@EndTime2
			and AreaId=Area.id
		) as TotalCount2
	from v_Location_Area as Area
	where isDelete=0 and state=1
		and id in (select areaid from tbl_areaManager2Area where userID=@AreaManagerId)
)

GO
/****** 对象:  UserDefinedFunction [dbo].[f_Reports_OrderComparisonByAreaManager]    脚本日期: 02/01/2010 11:43:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Venson>
-- Create date: <2008-6-24>
-- Description:	<订单对比分析——按区域>
-- =============================================
CREATE FUNCTION [dbo].[f_Reports_OrderComparisonByAreaManager]
(	
	@OrderState int,
	@AreaManagerId int,
	@BeginTime1 datetime,
	@EndTime1 datetime,
	@BeginTime2 datetime,
	@EndTime2 datetime
)
RETURNS TABLE 
AS
RETURN 
(
	select Id, Truename as Name,
		(
		select isnull(sum(Total), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime1 and Date_Time<@EndTime1
			and AreaId in (select AreaId from tbl_areaManager2Area where UserId=Users.Id)
		) as TotalAmount1,
		(
		select isnull(count(id), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime1 and Date_Time<@EndTime1
			and AreaId in (select AreaId from tbl_areaManager2Area where UserId=Users.Id)
		) as TotalCount1,
		(
		select isnull(sum(Total), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime2 and Date_Time<@EndTime2
			and AreaId in (select AreaId from tbl_areaManager2Area where UserId=Users.Id)
		) as TotalAmount2,
		(
		select isnull(count(id), 0) from v_Order_GeneralList
		where State=@OrderState and Date_Time>=@BeginTime2 and Date_Time<@EndTime2
			and AreaId in (select AreaId from tbl_areaManager2Area where UserId=Users.Id)
		) as TotalCount2
	from tbl_systemUser as Users
	where Id=@AreaManagerId
)

GO
/****** 对象:  UserDefinedFunction [dbo].[f_Reports_OrderComparisonByRest]    脚本日期: 02/01/2010 11:43:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Venson>
-- Create date: <2008-6-21>
-- Description:	<订单对比分析——按餐馆>
-- =============================================
CREATE FUNCTION [dbo].[f_Reports_OrderComparisonByRest]
(	
	@OrderState int,
	@AreaManagerId int,
	@BeginTime1 datetime,
	@EndTime1 datetime,
	@BeginTime2 datetime,
	@EndTime2 datetime
)
RETURNS TABLE 
AS
RETURN 
(
	select Id, Name,
		(
		select isnull(sum(Total), 0) from v_Order_GeneralList
		where RestId=Rest.Id and State=@OrderState and Date_Time>=@BeginTime1 and Date_Time<@EndTime1
			and AreaId in
			(
				select AreaId from tbl_areaManager2Area where UserId=@AreaManagerId
			)
		) as TotalAmount1,
		(
		select isnull(count(id), 0) from v_Order_GeneralList
		where RestId=Rest.Id and State=@OrderState and Date_Time>=@BeginTime1 and Date_Time<@EndTime1
			and AreaId in
			(
				select AreaId from tbl_areaManager2Area where UserId=@AreaManagerId
			)
		) as TotalCount1,
		(
		select isnull(sum(Total), 0) from v_Order_GeneralList
		where RestId=Rest.Id and State=@OrderState and Date_Time>=@BeginTime2 and Date_Time<@EndTime2
			and AreaId in
			(
				select AreaId from tbl_areaManager2Area where UserId=@AreaManagerId
			)
		) as TotalAmount2,
		(
		select isnull(count(id), 0) from v_Order_GeneralList
		where RestId=Rest.Id and State=@OrderState and Date_Time>=@BeginTime2 and Date_Time<@EndTime2
			and AreaId in
			(
				select AreaId from tbl_areaManager2Area where UserId=@AreaManagerId
			)
		) as TotalCount2
	from tbl_restaurant as Rest
	where isDelete=0 and state=1 and sclassid=3
)

GO
/****** 对象:  UserDefinedFunction [dbo].[f_suiteMenuTable_GetPriceList]    脚本日期: 02/01/2010 11:43:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<gcy>
-- Create date: <2008-4-1>
-- Description:	<取得菜单价格列表>
-- =============================================
CREATE FUNCTION [dbo].[f_suiteMenuTable_GetPriceList]
(	
	@menuID int
)
RETURNS table
AS
return
(	
	select distinct price from tbl_suiteMenuConfig where isDelete=0 and menuID=@menuID
)




GO
/****** 对象:  UserDefinedFunction [dbo].[Split]    脚本日期: 02/01/2010 11:43:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE FUNCTION [dbo].[Split](@splitString varchar(8000),@splitChar varchar(8000))
returns @T table
(
	splitValue varchar(8000)
)
AS
begin
	declare
		@type int,
		@tl varchar(8000),
		@index bigint
	
	set @splitString = ltrim((rtrim(@splitString)));
	set @index = charindex(@splitChar, @splitString);

	while(@index<>0)
	begin
		set @tl = ltrim(rtrim(left(@splitString, @index-1)))
		if @tl<>''
			insert into @T values(@tl);
		set @splitString = right(@splitString, len(@splitString) - @index);
		set @index = charindex(@splitChar, @splitString);
	end;
	if @splitString is not null
		insert into @T values(@splitString);
return;
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		wangjh
-- Create date: 2008-9-18
-- Description:	推荐好友获得积分的明细
-- =============================================
CREATE FUNCTION [dbo].[f_CommendFriendIntegral]
(
	@extendId int = 0, --推荐人
	@userId int = 0 --推荐的好友
	
)
RETURNS int
AS
BEGIN
	declare @amount int
	select @amount = isnull(sum(amount),0) from tbl_userIntegralDetail where orderid in(
	select id from v_Order_GeneralList where userid=str(@userId) and state='1') and userid=str(@extendID)
	RETURN (@amount)
END

GO
/****** 对象:  UserDefinedFunction [dbo].[f_GetFullPy]    脚本日期: 02/01/2010 11:46:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
 根据汉字获取全拼
 1.生成所有读音临时表
 2.根据Chinese_PRC_CS_AS_KS_WS 排序获取读音
*/
CREATE function [dbo].[f_GetFullPy](@str varchar(100))
returns varchar(8000)
as
begin
 declare @re varchar(8000) 
 declare @strlen int 
 select @strlen=len(@str),@re=''
 while @strlen>0
 begin     
      select top 1 @re=UPPER(substring(py,1,1) )+substring(py,2,len(py))+@re,@strlen=@strlen-1 
      from tbl_fullPyDict a where chr<=substring(@str,@strlen,1) 
      order by chr collate Chinese_PRC_CS_AS_KS_WS  desc 
      if @@rowcount=0
        select @re=substring(@str,@strlen,1)+@re,@strlen=@strlen-1
   end
 return(@re)
end

 





GO
/****** 对象:  UserDefinedFunction [dbo].[f_GetOperatorUserName]    脚本日期: 02/01/2010 11:46:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[f_GetOperatorUserName]
(@operatorRole int=0,-- 1.普通用户 2.餐馆管理员 3.豆丁客服
@operatorId int=0)
returns varchar(8000)
as
begin
declare @result varchar(8000)
set @result =''

if @operatorRole = 0
return @result
if @operatorId = 0
return @result
if @operatorRole =1 or @operatorRole = 2
begin
select @result = nickName from tbl_user where id = @operatorId
end
else if @operatorRole =3
begin
select @result = nickName from tbl_systemUser where id = @operatorId
end
return @result
end


GO
/****** 对象:  UserDefinedFunction [dbo].[f_GetPy]    脚本日期: 02/01/2010 11:46:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[f_GetPy](@Str varchar(500)='')
returns varchar(500)
as
begin
    declare @strlen int,@return varchar(500),@ii int
    declare @n int,@c char(1),@chn nchar(1)

    select @strlen=len(@str),@return='',@ii=0
    set @ii=0
    while @ii<@strlen
    begin
        select @ii=@ii+1,@n=63,@chn=substring(@str,@ii,1)
        if @chn>'z'
        select @n = @n +1
                    ,@c = case chn when @chn then char(@n) else @c end
            from(
                select top 27 * from (
                    select chn = '吖'
                    union all select '八'
                    union all select '嚓'
                    union all select '咑'
                    union all select '妸'
                    union all select '发'
                    union all select '旮'
                    union all select '铪'
                    union all select '丌'        --because have no 'i'
                    union all select '丌'
                    union all select '咔'
                    union all select '垃'
                    union all select '嘸'
                    union all select '拏'
                    union all select '噢'
                    union all select '妑'
                    union all select '七'
                    union all select '呥'
                    union all select '仨'
                    union all select '他'
                    union all select '屲'        --no 'u'
                    union all select '屲'        --no 'v'
                    union all select '屲'
                    union all select '夕'
                    union all select '丫'
                    union all select '帀'
                    union all select @chn) as a
                order by chn COLLATE Chinese_PRC_CI_AS 
            ) as b
        else set @c='a'
        set @return=@return+@c
    end
    return(@return)
end

GO
/****** 对象:  UserDefinedFunction [dbo].[f_GetRestDoodiiDeduct]    脚本日期: 02/01/2010 11:46:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		wangjh
-- Create date: 2008-10-9
-- Description:	根据餐馆Id获得一段时间里的豆丁提成
-- =============================================
--select [dbo].[f_GetRestDoodiiDeduct](6926,'1900-1-1','9999-1-1')
CREATE FUNCTION [dbo].[f_GetRestDoodiiDeduct]
(
	@restId int=0,
	@StartDate datetime='1900-1-1',
	@EndDate datetime='9999-1-1'
)
RETURNS float
AS
BEGIN
declare @DoodiiDeduct float
set @DoodiiDeduct = 0
select @DoodiiDeduct=sum(total*deduct) from(
select isnull((
 select sum(vo.total) from v_Order_GeneralList vo
where vo.state=1 and vo.deliverDate between @startDate and @endDate
and vo.restid=signup.restid 
and vo.deliverDate between signup.startDate 
and Convert(varchar(10),dateadd(d,1,signUp.fallInDate),120)
 ),0) as total,signUp.deduct from tbl_restSignUpHistory as signUp
 where restid=@restId
)as t
RETURN @DoodiiDeduct
END



GO
/****** 对象:  UserDefinedFunction [dbo].[f_getShopBusinessState]    脚本日期: 02/01/2010 11:46:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



/*
取得餐馆营业状态
1营业中、2已售完、3休息中、4暂停业
*/
create function [dbo].[f_getShopBusinessState](@shopID int)
returns int
as
begin
declare @shopBusinessState int

	select @shopBusinessState=
		(
			case state 
				when 0 then /*正常营业（营业中、休息中）*/					
					(select 
						case 
							when count(ID)>0  then 1--'营业中'
							else 3--'休息中'
						end
					from tbl_ShopBusinessTime 
						where shopID=@shopID and 
							Cast(Cast(DatePart(hh,(select * from v_getDate)) as varchar(2)) + '.' + Cast(DatePart(mi,(select * from v_getDate)) as varchar(2)) as float)
							 between startClock and endClock
					)
				when 1 then 2--'已售完' 
				when 2 then 4--'暂停业' 
				else 4--'暂停业'
			end
		)
	from tbl_ShopBusinessState where shopID=@shopID
 return(@shopBusinessState)
end

 







GO
/****** 对象:  UserDefinedFunction [dbo].[f_getShopBusinessStateStr]    脚本日期: 02/01/2010 11:46:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*
取得餐馆营业状态
*/
CREATE function [dbo].[f_getShopBusinessStateStr](@shopID int)
returns varchar(6)
as
begin
declare @shopBusinessStateStr varchar(6)

	select @shopBusinessStateStr=
		(
			case state 
				when 0 then /*正常营业（营业中、休息中）*/					
					(select 
						case 
							when count(ID)>0  then '营业中'
							else '休息中'
						end
					from tbl_ShopBusinessTime 
						where shopID=@shopID and 
							Cast(Cast(DatePart(hh,(select * from v_getDate)) as varchar(2)) + '.' + Cast(DatePart(mi,(select * from v_getDate)) as varchar(2)) as float)
							 between startClock and endClock
					)
				when 1 then '已售完' 
				when 2 then '暂停业' 
				else '暂停业'
			end
		)
	from tbl_ShopBusinessState where shopID=@shopID
 return(@shopBusinessStateStr)
end

 






GO
/****** 对象:  UserDefinedFunction [dbo].[f_Order_getIntegralByRules]    脚本日期: 02/01/2010 11:46:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[f_Order_getIntegralByRules]
	(@total float)
	RETURNS float
as
begin
	declare @orderIntegral float
	declare @rate float,@baseIntegral float,@baseIntegralRate float,@maxIntegral float,@integralNote varchar(50),@userID bigint,@userName as varchar(8000),@orderPostTime datetime,@deliverDate dateTime,@deliverSpan float
	declare @startPrice float,@endPrice float,@state0 int,@rowTbl_integralRate int,@orderAmount int,@activityRate float,@activityIntegral float,@deliverSpanRate float
	/*取得积分规则*/
	declare @commendOrderIntegral float,@commendOrderDateAmount int,@falseIntegral float,@orderRate float,@spreadDepth int,@extendUserID bigint,@Integral float			

	

	/*1取得默订积分规则设定*/
	select top 1 @commendOrderIntegral=commendOrderIntegral,@commendOrderDateAmount=commendOrderDateAmount,@orderRate=orderRate,@falseIntegral = falseOrderIntegral,@spreadDepth=spreadDepth from tbl_integralRate
	set @rowTbl_integralRate=@@rowcount
	if @rowTbl_integralRate=0 begin
		select @commendOrderIntegral=0,@commendOrderDateAmount=0,@orderRate=0,@falseIntegral=0,@spreadDepth=0
	end	

	/*2取得订单积分比例基本规则表*/
	select top 1 @baseIntegralRate=integral from tbl_orderBaseIntegralRule where (select * from v_getDate)>=startTime and (select * from v_getDate)<dateAdd(d,1,endTime) and isDelete=0
	if @@rowCount=0 
		set @baseIntegralRate=@orderRate					

	/*3取得订餐积分金额比例规则设定*/
	select top 1 @rate=rate  from tbl_orderIntegralRateClass a inner join tbl_orderIntegralRate b on b.classID=a.id 
			where (select * from v_getDate)>=a.startTime and (select * from v_getDate)<dateAdd(d,1,a.endTime) and a.isDelete=0
			and @total>=b.startMoney and @total<b.endMoney and b.isDelete=0										
	if @@rowcount=0 
		set @rate=0
	
	/*4取得活动积分规则表*/
	select top 1 @activityRate=rate,@activityIntegral=integral from tbl_activityIntegralRate 
			where @deliverDate>=startTime and @deliverDate<dateAdd(d,1,endTime) and isDelete=0
	if @@rowCount=0 begin
		set @activityRate=0
		set @activityIntegral=0
	end
	
	/*5取得预订积分规则表*/
	set @deliverSpan=datediff(minute,@orderPostTime,@deliverDate)/60
	select @deliverSpanRate=b.rate from tbl_reserveIntegralRateClass a inner join tbl_reserveIntegralRate b on b.classID=a.id
			where (select * from v_getDate)>=a.startTime and (select * from v_getDate)<dateAdd(d,1,a.endTime) and a.isDelete=0
				and @deliverSpan>=b.startSpan and @deliverSpan<b.endSpan and b.isDelete=0
	if @@rowCount=0 begin
		set @deliverSpanRate=0
	end			
	
	set @baseIntegral=@baseIntegralRate*@total

	/* 用户订餐获得积分  开始*/	--(包括：订餐基金规则，额外积分，活动积分，提前预订餐积分)								
	/*取出最大者*/
	select @maxIntegral=max(a) from (
		select @rate*@baseIntegral as a
		union
		select @activityRate*@baseIntegral+@activityIntegral as a
		union
		select @deliverSpanRate*@baseIntegral as a
	) as t
	set @orderIntegral=@maxIntegral+@baseIntegral

	return @orderIntegral

end
GO
/****** 对象:  UserDefinedFunction [dbo].[f_Reports_GetHoldOrderUserCount]    脚本日期: 02/01/2010 11:46:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<venson>
-- Create date: <2008-6-18>
-- Description:	<获取某日某楼宇稳定订餐客户总数>
-- =============================================
CREATE FUNCTION [dbo].[f_Reports_GetHoldOrderUserCount]
(
	@Date datetime,
	@AreaId bigint
)
RETURNS int
AS
BEGIN
	declare @Ret int;
	select @Ret=count(distinct(userID)) from v_Order_GeneralList
	where state=1 and userid<>0 and areaid=@AreaId and date_time<@Date and date_time>=@Date-6
	return @Ret
END

GO
/****** 对象:  UserDefinedFunction [dbo].[f_Reports_GetLostOrderUserCount]    脚本日期: 02/01/2010 11:46:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Venson>
-- Create date: <2008-6-18>
-- Description:	<获取某日某楼宇流失订餐客户总数>
-- =============================================
CREATE FUNCTION [dbo].[f_Reports_GetLostOrderUserCount]
(
	@Date datetime,
	@AreaId bigint
)
RETURNS int
AS
BEGIN
	declare @Ret int;
	
	select @Ret=count(distinct(userID))
	from v_Order_GeneralList
	where date_time<@Date-6 and userID<>0 and state=1 and areaId=@AreaId
		and userID not in(
			select userID
			from v_Order_GeneralList
			where date_time>=@Date-6 and date_time<@Date+1 and userID<>0
				and state=1 and areaId=@AreaId
		)
	
	return @Ret
END

GO
/****** 对象:  UserDefinedFunction [dbo].[f_Reports_GetNewOrderUserCount]    脚本日期: 02/01/2010 11:46:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Venson>
-- Create date: <2008-6-17>
-- Description:	<获取某日某楼宇新增订餐客户总数>
-- =============================================
CREATE FUNCTION [dbo].[f_Reports_GetNewOrderUserCount] 
(
	@Date datetime,
	@AreaId bigint
)
RETURNS int
AS
BEGIN
	declare @Ret int

	select @Ret=count(distinct(userid))
	from v_Order_GeneralList
	where date_time>=@Date and date_time<@Date+1 and state=1 and userid<>0 and areaid=@AreaId
		and userid not in(
			select distinct(userid)
			from v_Order_GeneralList
			where date_time<@Date and state=1 and userid<>0 and areaid=@AreaId
		)
	return @Ret
END

GO
/****** 对象:  UserDefinedFunction [dbo].[f_restCheckTodayMenu]    脚本日期: 02/01/2010 11:46:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--检查餐馆某天是否有订单
--参数：@restID:餐馆ID,@dateTime:日期
--返回：大于0为餐馆当日有日期，等于0为餐馆当日没有日期
CREATE function [dbo].[f_restCheckTodayMenu]
	(@restID bigint,@dateTime DateTime=getDate)
	returns int
as begin	
	declare @deliverDay int,@menuType int,@menuAmount int
	select @deliverDay=case datepart(weekday,@dateTime) 
			when 1 then 64
			when 2 then 1
			when 3 then 2
			when 4 then 4
			when 5 then 8
			when 6 then 16
			when 7 then 32 
	end
	set @deliverDay=127
	select @menuType=menuType from tbl_restaurant where ID=@restID
	if @menuType=0 begin
		select @menuAmount=count(mt.id) 
		from tbl_MenuTAble mt 
			left join tbl_menuClass mc on mc.id=mt.ClassID
			left join tbl_restaurant r on r.id=mt.restID
		where mC.isDeliver=1 and mC.isDelete=0 and mt.state=0 
			and r.isDelete=0 and r.state=1 and r.menuType=@menuType and r.ID=@restID
			and (mt.deliverDay & @deliverDay)>0 /*--二进制与 1,2,4,8,16,32,64 依次代表周一到周日*/
	end else begin
		select @menuAmount=count(smt.id) 
		from tbl_suiteMenuTable smt 
			left join tbl_restaurant r on r.id=smt.restID
		where smT.isDelete=0
			and r.isDelete=0 and r.state=1 and r.menuType=@menuType and r.ID=@restID
			and (smT.deliverDay & @deliverDay)>0 /*--二进制与 1,2,4,8,16,32,64 依次代表周一到周日*/
			and smT.id in (/*--分类时间*/
							select MenuID from tbl_suiteMenuList smL left join tbl_suiteMenuClass smCl on smCl.id=smL.classID
								where smCL.restID=@restID and smCl.isDelete=0 and (smCl.dayID & @deliverDay)>0 /*--二进制与 1,2,4,8,16,32,64 依次代表周一到周日*/
			)
	end
	return(@menuAmount)
end


GO
/****** 对象:  UserDefinedFunction [dbo].[f_suiteMenuConfigContent_Get]    脚本日期: 02/01/2010 11:46:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<gcy>
-- Create date: <2008-1-15>
-- Description:	<根据配置ID取得配品内容>
-- =============================================
CREATE FUNCTION [dbo].[f_suiteMenuConfigContent_Get]
(	
	@configID int
)
RETURNS varchar(8000)
AS
BEGIN	
	declare @configContent varchar(8000)
	set @configContent=''
	select @configContent=@configContent+[name]+',' from tbl_suiteMenuElement 
	where isDelete=0 and id in 	
	(
		select elementID from tbl_suiteMenuContent where configID = @configID						
	)	
	set @configContent=substring(@configContent,1,len(@configContent)-1)
	RETURN @configContent
END


GO
/****** 对象:  UserDefinedFunction [dbo].[f_suiteMenuTable_GetPriceListStr]    脚本日期: 02/01/2010 11:46:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<gcy>
-- Create date: <2008-4-1>
-- Description:	<取得菜单价格列表字符串>
-- =============================================
CREATE FUNCTION [dbo].[f_suiteMenuTable_GetPriceListStr]
(	
	@menuID int
)
RETURNS varchar(8000)
AS
BEGIN	
	declare @configContent varchar(8000)
	set @configContent=''
	select @configContent=@configContent+Cast([price] as varchar(8000))+'/' from f_suiteMenuTable_GetPriceList(@menuID)	
	if len(@configContent)>0
		set @configContent=substring(@configContent,1,len(@configContent)-1)
	
	RETURN @configContent
END




GO
/****** 对象:  UserDefinedFunction [dbo].[f_suiteMenuTable_isIncludePrice]    脚本日期: 02/01/2010 11:46:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<gcy>
-- Create date: <2008-4-1>
-- Description:	<取得菜单价格列表字符串>
-- =============================================
CREATE FUNCTION [dbo].[f_suiteMenuTable_isIncludePrice]
(	
	@menuID int,
	@price float
)
RETURNS int
AS
BEGIN		
	return(select top 1 count(id) as amount from tbl_suiteMenuConfig where menuID = @menuID and price=@price)
END





GO
/****** 对象:  UserDefinedFunction [dbo].[myStrCompare]    脚本日期: 02/01/2010 11:46:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE   function   [dbo].[myStrCompare](@str1   varchar(8000),@str2   varchar(8000))   
  returns   float   
  as   
  begin   
          declare   @i   int,@j   int,@k   int,@ret   float   
          select   @i   =   max(strlen),@j=min(strlen),@k=0   
          from   (select   strlen=len(@str1)   union   select   strlen=len(@str2))   t   
            
          if(@j=0)   
                  return   0   
            
          while   @j>0   
          begin   
                  if   substring(@str1,@j,1)=substring(@str2,@j,1)   
                          set   @k=@k+1   
                  set   @j=@j-1   
          end   
            
          set   @ret   =   @k*100.0/@i   		  
          return   @ret   
  end   
GO
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go



-- =============================================
-- Author:		<gcy>
-- Create date: <2008-1-17>
-- Description:	<添加或修改时更新拼单字段(spy,qpy)>
-- =============================================
create TRIGGER [tg_area_updatePy]
   ON  [dbo].[tbl_area]
   for INSERT,UPDATE
AS 
BEGIN	
	SET NOCOUNT ON;
	declare @id int
	select top 1 @id=id from inserted
    update tbl_area set [name]=rtrim(ltrim([name])), spy=dbo.f_GetPy(rtrim(ltrim([name]))),qpy=dbo.f_GetFullPy(rtrim(ltrim([name]))) where id=@id

END