如何根据Dayname和Mindate增加日期

时间:2015-06-16 08:07:32

标签: sql sql-server

select DATENAME(DW,'06/24/2015')

我的表看起来像这样。我如何根据最短日期的日期名称来实现这一目标

Declare @t table (Dated VARCHAR(20),Dayname VARCHAR(10))
INSERT INTO @t (Dated,Dayname)values ('06/17/2015','Wednesday'),
('06/17/2015','Friday'),
('06/17/2015','Monday'),
('06/17/2015','Wednesday')
select * from @t

Required Output : 
Dated   Dayname
06/17/2015  Wednesday
06/19/2015  Friday
06/22/2015  Monday
06/24/2015  Wednesday

2 个答案:

答案 0 :(得分:0)

创建以下功能

CREATE FUNCTION dbo.WeekDay(@DayOfWeek Varchar(9))
RETURNS INT
            AS
    BEGIN
    DECLARE @iDayofWeek INT
    SELECT @iDayofWeek = CASE @DayOfWeek
                    WHEN 'Sunday' THEN 1
                    WHEN 'Monday' THEN 2
                    WHEN 'Tuesday' THEN 3
                    WHEN 'Wednesday' THEN 4
                    WHEN 'Thursday' THEN 5
                    WHEN 'Friday' THEN 6
                    WHEN 'Saturday' THEN 7
        END
    RETURN (@iDayofWeek)
    END
GO

现在在查询中使用它来获取相关日期的整数值,并使用DATEADD函数相应增加

答案 1 :(得分:0)

使用此代码:(如果您只需要星期一,星期三和星期五)

 Create proc Insert_date(
    @startdate date, 
    @enddate date 
    )

    as begin 
    set nocount on

    declare @date date
    declare @day varchar(15)
    declare @n int
    declare @count int

    create table #tab(Dated date,Dayname VARCHAR(10))


    Set @n=0
    select @count=DATEDIFF(dd,@startdate,@enddate)+1

    While(@n<=@count)
     Begin
     select @date=DATEADD(day,@n,@startdate)
     select @day=DATENAME(DW,@date)

     if DATENAME(DW,@date) in('Wednesday','Friday','Monday')
    begin
     INSERT INTO #tab (Dated,Dayname)
     select @date,@day
    end


     select @n=@n+1

    end

   set nocount off
    end

执行:

Exec Insert_date '06/17/2015','06/24/2015'

输出:

Dated        Dayname
2015-06-17  Wednesday
2015-06-19  Friday
2015-06-22  Monday
2015-06-24  Wednesday