列出表的两个Date列之间的所有日期

时间:2011-10-19 03:58:30

标签: sql sql-server date

我的表PRODUCT有3列:

Product_ID
INTRODUCED_DATE
WITHDRAWAL_DATE

我需要从此表创建派生表PRODUCT_ALL_DATES,列出产品处于活动状态的所有日期。日期范围为INTRODUCED_DATE(开始日期)和WITHDRAWAL_DATE(结束)日期)

如何在SQL Server中实现此目的?我已在附加图像中指示了示例输出:

http://i.imgur.com/vOBVa.jpg

谢谢!

4 个答案:

答案 0 :(得分:5)

declare @dateh table(ind int identity(1,1),date1 smalldatetime,date2 smalldatetime)

insert into @dateh select '1/1/2011','1/15/2011'

select * from @dateh

;with T as
(
    select date1,date2 from @dateh as d
    union all
    select dateadd(dd,1,date1),date2 From T 
    where  dateadd(dd,1,date1)<= date2
)
Select date1 from T

答案 1 :(得分:1)

我可以想到两种方法来实现这个目标

  1. 编写存储过程并循环以填充第二个表
  2. 用另一种语言编写程序来完成它。
  3. 显而易见的问题是你为什么要这样做?什么是数据处于当前形式无法解决的问题

答案 2 :(得分:0)

根据日期的总范围,这应该有效。如果总体上有大范围的日期,则可能需要调整MAX递归。

;WITH DaysCTE( Date ) as
(
    SELECT MIN(INTRODUCED_DATE) AS Date FROM PRODUCT
        UNION ALL
    SELECT DATEADD(day, 1, Date) 
        FROM DaysCTE
        where Date < (SELECT MAX(@WITHDRAWAL_DATE) FROM PRODUCT)
)

SELECT
   PRODUCT_ID,
   DaysCTE.Date
FROM
   PRODUCT
INNER JOIN DaysCTE
 ON DaysCTE.Date >= PRODUCT.INTRODUCED_DATE
    AND DaysCTE.DATE <= PRODUCT.WITHDRAWAL_DATE

答案 3 :(得分:0)

以下是您查询的答案, 我试过使用Cursor。它工作正常。

    CREATE TABLE product
(
product_id int
,INTRODUCED_DATE DATETIME
,WITHDRAWAL_DATE DATETIME
)

INSERT INTO product VALUES (100,'01-01-2011','01-05-2011')
INSERT INTO product VALUES (200,'05-30-2011','06-05-2011')

CREATE TABLE PRODUCT_ALL_DATES
(
product_id int
,Dates_Active DATETIME
)

DECLARE @product int
,@Introduct_Date DATETIME
,@Withdrawal_date DATETIME
,@Dates_Active DATETIME

DECLARE pointer_cur CURSOR FAST_FORWARD
FOR
SELECT * FROM product a

OPEN pointer_cur

FETCH NEXT FROM pointer_cur
INTO @Product,@Introduct_Date,@Withdrawal_date

WHILE(@@FETCH_STATUS=0)
BEGIN

    WHILE(@Introduct_Date<=@Withdrawal_date)
    BEGIN
        SET @Dates_Active=@Introduct_Date

        INSERT INTO PRODUCT_ALL_DATES
        SELECT @product,@Dates_Active

        SELECT @Introduct_Date=dateadd(day,1,@Introduct_Date)

    END

FETCH NEXT FROM POINTER_CUR
INTO @Product,@Introduct_Date,@Withdrawal_date

END

CLOSE POINTER_CUR
DEALLOCATE POINTER_CUR

SELECT * FROM PRODUCT_ALL_DATES