0

我正在尝试编写一个查询,该查询将在两个设定日期之间运行所有日期和日期名称。

例子:

Date1 = 12/28/2005
Date2 = 12/30/2006

结果:

12/28/2005 Wednesday
12/29/2005 Thursday
12/30/2005 Friday
12/31/2005 Saturday
01/01/2006 Sunday
01/02/2006 Monday
01/03/2006 Tuesday

任何帮助表示赞赏!

4

3 回答 3

0

你可以检查这个小提琴

编码:

DECLARE @Date1 DATETIME
DECLARE @Date2 DATETIME

SET @Date1 = '20051228'
SET @Date2 = '20061230'

;WITH cteSequence ( SeqNo) as
(
      SELECT 0
      UNION ALL
      SELECT SeqNo + 1
      FROM cteSequence
      WHERE SeqNo < DATEDIFF(d,@Date1,@Date2)
)
SELECT CONVERT(VARCHAR,DATEADD(d,SeqNo,@Date1),1) + ' ' + DATENAME(dw,DATEADD(d,SeqNo,@Date1))
FROM cteSequence
OPTION ( MAXRECURSION 0);


GO
于 2013-08-29T08:29:04.930 回答
0

您没有指定您的 DBMS,所以我假设 Postgres:

select i::date, to_char(i, 'Day')
from generate_series(timestamp '2005-12-28 00:00:00', 
                     timestamp '2006-12-30 00:00:00', interval '1' day) i;

ANSI SQL 解决方案是:

with recursive date_list (the_date) as (
    values ( date '2005-12-28' )
    union all
    select cast(p.the_date + interval '1' day as date)
    from date_list p
    where p.the_date <= date '2006-12-30
)
select * 
from date_list;
于 2013-08-29T09:11:25.657 回答
0

您可以使用该表值函数:

create function DateTable
(
  @FirstDate datetime,
  @LastDate datetime,
  @handle nvarchar(10)='day',
  @handleQuantity int=1
)
returns @datetable table (
  [date] datetime
)
AS
begin

  with CTE_DatesTable
  as 
  (
    select @FirstDate AS [date]
    union ALL
    select case @handle
        when 'month' then dateadd(month, @handleQuantity, [date])
        when 'year' then dateadd(year, @handleQuantity, [date])
        when 'hour' then dateadd(hour, @handleQuantity, [date])
        when 'minute' then dateadd(minute, @handleQuantity, [date])
        when 'second' then dateadd(second, @handleQuantity, [date])
        else dateadd(day, @handleQuantity, [date])
        end
    from CTE_DatesTable
    where @LastDate >=
    case @handle
        when 'month' then dateadd(month, @handleQuantity, [date])
        when 'year' then dateadd(year, @handleQuantity, [date])
        when 'hour' then dateadd(hour, @handleQuantity, [date])
        when 'minute' then dateadd(minute, @handleQuantity, [date])
        when 'second' then dateadd(second, @handleQuantity, [date])
        else DATEADD(day, @handleQuantity, [date])
        end
  )
  insert @datetable ([date])
  select [date] from CTE_DatesTable
  option (MAXRECURSION 0)

  return
end

你可以这样称呼它:

select [date],datepart(weekday,[date]) from dbo.DateTable('12/28/2005','12/30/2006',default,default)
于 2013-08-29T08:31:42.707 回答