如何使用sql查询更新日期范围?

时间:2011-03-23 03:26:45

标签: sql

这是我的sql代码

    DECLARE @Product TABLE ( Date_From Datetime, Date_To Datetime, Product_ID INT)
INSERT INTO @Product Values
('20110323', '20110326', 101)
INSERT INTO @Product Values
('20110327','20110329',101)

-- The actual solution --
DECLARE @Beg Datetime, @End Datetime
SET @Beg = '20110323'
SET @End = '20110323'

IF @Beg = @End
BEGIN
    DECLARE @Temp TABLE (Date_From Datetime, Date_To Datetime, Product_ID INT, [Version] INT)
    INSERT INTO @Temp
    SELECT p.*, x.[Version]
    FROM @Product AS p, (SELECT 1 AS [Version] UNION SELECT 2 AS [Version]) AS x
    WHERE @Beg BETWEEN p.Date_From AND p.Date_To   

    DELETE FROM @Product WHERE @Beg BETWEEN Date_From AND Date_To   

    UPDATE @temp SET
        Date_From = CASE WHEN [Version] = 1 AND @Beg BETWEEN Date_From AND Date_To THEN DateAdd(dd, -1, @Beg)
                         WHEN [Version] = 2 AND @Beg BETWEEN Date_From AND Date_To THEN DateAdd(dd, +1, @Beg)
                         ELSE Date_From END,
        Date_To =  CASE WHEN [Version] = 1 AND @Beg BETWEEN Date_From AND Date_To THEN DateAdd(dd, -1, @Beg)
                       WHEN [Version] = 2 AND @Beg BETWEEN Date_From AND Date_To THEN DateAdd(dd, +1, @Beg)
                       ELSE Date_From END
    INSERT INTO @Product ( Date_From, Date_To, Product_ID)
    SELECT  Date_From, Date_To, Product_ID FROM @Temp
END

ELSE

BEGIN
    UPDATE @Product
     SET
        Date_From = CASE WHEN Date_From BETWEEN @Beg AND @End THEN DateAdd(dd, 1, @End) ELSE Date_From END,
        Date_To = CASE WHEN Date_To BETWEEN @Beg AND @End THEN DateAdd(dd, -1, @Beg) ELSE Date_To END
    WHERE Date_From BETWEEN @Beg AND @End
    OR Date_To BETWEEN @Beg AND @End
DELETE FROM @Product WHERE Date_From > Date_To
END

SELECT * FROM @Product ORDER BY Date_From

这是出局......

2011-03-22 00:00:00.000 2011-03-22 00:00:00.000 101
2011-03-24 00:00:00.000 2011-03-24 00:00:00.000 101
2011-03-27 00:00:00.000 2011-03-29 00:00:00.000 101

此输出中的问题是22,它不在DECLARE表中

我需要的是低于预期

2011-03-24 00:00:00.000 2011-03-24 00:00:00.000 101
2011-03-27 00:00:00.000 2011-03-29 00:00:00.000 101

0 个答案:

没有答案