在Sql Server 2008中比较两个日期和两个其他日期

时间:2013-07-24 11:52:03

标签: asp.net sql-server database stored-procedures

我在sql server中有一个带有以下模式的表。

   **ID   Title     ActiveFromDate  ActiveToDate**
    1      Test       2013-07-06      2013-08-22
    2      Test       2013-07-01      2013-07-30

我想通过ActiveFromDate和Active ToDate选择记录,即选择某些日期范围之间的所有记录。

     SELECT ISNULL(COUNT(*),0) AS Total, dbo.ArrangementPromotion.Title
FROM dbo.ArrangementPromotion
WHERE(
       (dbo.ArrangementPromotion.ActiveFromDate BETWEEN '2013-08-01' AND '2013-08-14') 
    OR (dbo.ArrangementPromotion.ActiveToDate BETWEEN '2013-08-01' AND '2013-08-14' )
     )
     AND dbo.ArrangementPromotion.Inactive = 0 
     AND dbo.ArrangementPromotion.Deleted = 0
     AND(12 IS NOT NULL OR dbo.ArrangementPromotion.ID <> 12 )
GROUP BY dbo.ArrangementPromotion.Title

但是如果参数@ActiveToDate中的日期小于表格Active ToDate,那么我无法获得所需的结果。 任何身体都可以帮助我。

由于

1 个答案:

答案 0 :(得分:2)

我认为您可能正在寻找类似

的内容
   (dbo.ArrangementPromotion.ActiveFromDate BETWEEN '2013-08-01' AND '2013-08-14') 
OR (dbo.ArrangementPromotion.ActiveToDate BETWEEN '2013-08-01' AND '2013-08-14' )
OR ('2013-08-01' BETWEEN dbo.ArrangementPromotion.ActiveFromDate AND dbo.ArrangementPromotion.ActiveToDate)
OR ('2013-08-14' BETWEEN dbo.ArrangementPromotion.ActiveFromDate AND dbo.ArrangementPromotion.ActiveToDate)

'2013-08-01'应为@ActiveFrom'2013-08-14' @ActiveTo