SQL 2008 - 如果日期尚不存在,则插入表中

时间:2012-03-14 02:23:38

标签: sql-server-2008 if-statement insert

您好我如何制作以下脚本来插入作品。 首先检查表是否存在,如果是,仅插入表中,并且我只想在表中没有日期范围时插入表中。否则请选择表格。

DECLARE @date1 datetime
DECLARE @date2 datetime
DECLARE @dailyEnd1 varchar(12)
DECLARE @dailyEnd2 varchar(12)
DECLARE @column varchar(100)
DECLARE @Script varchar(8000)
SET @date1 = '09 jan 2012'
SET @date2 = '15 jan 2012'

SET @dailyEnd1 = @date1
SET @dailyEnd2 = @date2

IF OBJECT_ID('tempdb..#table1') is not null

    BEGIN   
        IF NOT EXIST (SELECT MinDate, MaxDate FROM #table1
            WHERE MinDate = '02 Jan 2012' AND MaxDate = '08 jan 2012'
            GROUP BY MinDate, MaxDate)
            BEGIN
                INSERT INTO #table1 (MinDate, MaxDate, [Week], OutletID, OutletName, Transactions, Spend)
                SELECT min(dailyEnd-1), max(dailyEnd-1), 
                convert(varchar(12),Min(dailyEnd-1), 104)+'-'+convert(varchar(12),MAX(dailyEnd-1),104), 
                OutletID, OutletName, 
                sum(Transactions), sum(Sales)
                FROM #table2 (NOLOCK)
                WHERE dailyEnd-1 >= @dailyEnd1
                AND dailyEND-1 <= @dailyEnd2
                GROUP BY OutletID, OutletName
            END
    END

ELSE
    BEGIN

    SELECT min(dailyEnd-1) as MinDate, max(dailyEnd-1) as MaxDate, 
    convert(varchar(12),Min(dailyEnd-1), 104)+'-'+convert(varchar(12),MAX(dailyEnd-1),104) as [Week], OutletID, OutletName, sum(Transactions) as Transactions, sum(Sales) as Spend
    INTO #table1
    FROM #table2 (NOLOCK)
    WHERE dailyEnd-1 >= @dailyEnd1
    AND dailyEND-1 <= @dailyEnd2
    GROUP BY OutletID, OutletName

    END

由于

1 个答案:

答案 0 :(得分:0)

NOT EXISTS之后的WHERE中移动INSERT条款。

含义,只插入NOT EXISTS的日期范围。