淘宝直通车分时折扣 SQL

USE [CRM]
GO
/****** Object:  UserDefinedFunction [dbo].[GetDiscountByCampaignId]    Script Date: 09/28/2012 15:18:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        xst
-- Create date: 2012.08.30
-- Description:    all 表示不打折扣,否则根据“;” 来分隔判断当前天是星期几,
 --然后再判断当前系统时间是在当前星期X中的那个时间段来对产品进行打相应的折扣
-- =============================================
ALTER FUNCTION [dbo].[GetDiscountByCampaignId]
(
    @campaign_id nvarchar(100) --计划id
)
RETURNS int
AS
BEGIN
    
    declare @discount int,
    @scheduleOfWeek nvarchar(max), --一周折扣日程
    @scheduleOfDay nvarchar(max), --当天折扣日程
    @scheduleField nvarchar(max), --折扣日程时间段
    @timePrefix nvarchar(11), --时间前缀
    @timeSuffix nvarchar(7), --时间后缀
    @dayOfWeekCnIndex int  --系统当天的星期数
    
    declare @tempTable TABLE
    (
        [id] int identity(1,1),
        [value] nvarchar(max)
    )
    declare @tempScheduleTable TABLE
    (
        beginTime datetime,
        endTime datetime,
        discount int
    )

    select @scheduleOfWeek=schedule from dbo.DC_CampaignSchedule
    where campaign_id=@campaign_id

    if(UPPER(RTRIM(LTRIM(@scheduleOfWeek)))='ALL')
    BEGIN
        set @discount=100
        return @discount
    END

    set @timePrefix = convert(char(11),getdate(),120)
    set @timeSuffix = ':00.000'

    set @dayOfWeekCnIndex=(
        select case 
        when datepart(dw, GETDATE())=1 then 7
        when datepart(dw, GETDATE())=2 then 1
        when datepart(dw, GETDATE())=3 then 2
        when datepart(dw, GETDATE())=4 then 3
        when datepart(dw, GETDATE())=5 then 4
        when datepart(dw, GETDATE())=6 then 5
        when datepart(dw, GETDATE())=7 then 6
        end dayOfWeek_CN
    )
    
    select @scheduleOfDay=value from dbo.GetTableBySplit(@scheduleOfWeek,';')
    where id = @dayOfWeekCnIndex
    
    insert into @tempTable(value)
    select REPLACE(value,'24:00','23:59') as value
    from dbo.GetTableBySplit(@scheduleOfDay,',')
    
    insert into @tempScheduleTable(beginTime,endTime,discount)
    select 
    cast(@timePrefix+substring(value,0,charindex('-',value))+@timeSuffix as datetime) AS beginTime,
    cast(@timePrefix+substring(value,charindex('-',value)+1,5)+@timeSuffix as datetime) AS endTime,
    substring(value,charindex('-',value)+7,3) as discount
    from @tempTable

    select @discount=discount from @tempScheduleTable
    WHERE getdate()>=beginTime and getdate()<endTime

    -- Return the result of the function
    RETURN @discount

END


--SET DATEFIRST 1 --设置周一为每周第一天
    SELECT @@DATEFIRST
    --查询每周一对应的日期(通用,不管@@DATEFIRST如何变动)
    SELECT DATEADD(DAY,1-(DATEPART(WEEKDAY,GETDATE())+@@DATEFIRST-2)%7-1,GETDATE())
    --查询每周一对应的日期(@@DATEFIRST为7,SQL Server默认周日为每周第一天)
    SELECT DATEADD(DAY,2-DATEPART(WEEKDAY,GETDATE()),GETDATE())
posted @ 2012-09-28 15:21  xust  阅读(424)  评论(0)    收藏  举报