2012-05-24 130 views
2

我有一堆SQL選擇收集數據用於導出和分析。我已經在幾個變量中聲明瞭我想要收集數據的日期範圍並運行查詢,總共有10個選擇使用相同的日期範圍變量。我想要做的就是輕鬆地從查詢中排除某些日期(它們是單日而不是範圍),使用某種排除列表,我可以在變量中聲明,這樣我所有的選擇都會刪除這些特定的日期,而不是編輯每個選擇聲明。SQL日期排除

DECLARE @date_start DATETIME, @date_end DATETIME 
SET @date_start = '2011-10-20 00:00:00' 
SET @date_end = '2012-05-18 23:59:59' 

SELECT 
date, col1, col2, col3 
FROM 
table1 
WHERE 
date BETWEEN CONVERT(DATETIME, @date_start, 102) AND CONVERT(DATETIME, @date_end, 102) 

SELECT 
date, col4, col5, col8 
FROM 
table2 
WHERE 
date BETWEEN CONVERT(DATETIME, @date_start, 102) AND CONVERT(DATETIME, @date_end, 102) 

SELECT 
date, col3, col5, col6, col7, col8 
FROM 
table3 
WHERE 
date BETWEEN CONVERT(DATETIME, @date_start, 102) AND CONVERT(DATETIME, @date_end, 102) 
+2

你爲什麼要將日期轉換爲日期? – Oded

+1

當在SQL Server中使用日期範圍來使用'> ='和'<'而不是'between'時,通常會更好。這使您可以使用更合理的表示形式,並避免當前發生的問題,即缺少在間隔的最後一秒發生的任何事情(例如'2012-05-18T23:59:59.003')。 –

+0

這是一個遺留/懶惰的事情,我使用的某些日期列的數據類型實際上並不是數據庫中的日期時間,這是一個解決方法。 – user1414459

回答

0

應用:

附加給你的查詢:和日期不在(DATE1,DATE2 ...)

0

您可以使用在where條件指定所選的日期。並且當你只考慮日期部分時,更好地使用轉換(varchar,datecolumn,111),它給出了yyyy/MM/dd格式。不需要給時間部分23:59:59。

0

用你正在查找的日期創建一個表變量,並在查詢中使用它。

您可以使用日期範圍變量和另一個包含您不想查找的日期的表來構建該表。

事情是這樣的:

declare @date_start datetime 
declare @date_end datetime 

-- The date range you want. Don't add time part. 
set @date_start = '20010102' 
set @date_end = '20010107' 

declare @NotTheDatesYouAreLookingFor as table 
(
    date datetime 
) 

insert into @NotTheDatesYouAreLookingFor values 
('20010103'), 
('20010105') 

declare @TheDatesYouAreLookingFor as table 
(
    date datetime primary key 
) 

;with C(date) as 
(
    select @date_start 
    union all 
    select date + 1 
    from C 
    where date < @date_end 
) 
insert into @TheDatesYouAreLookingFor(date) 
select date 
from C 
    where date not in (select date 
        from @NotTheDatesYouAreLookingFor) 

而且你的查詢應使用表@TheDatesYouAreLookingFor這樣。

select T1.date, T1.col1, T1.col2, T1.col3 
from table1 as T1 
    inner join @TheDatesYouAreLookingFor as TD 
    on T1.date >= TD.date and T1.date < dateadd(day, 1, TD.date)