具有两个日期参数的两个日期字段中的条件

时间:2011-09-28 06:21:45

标签: sql sql-server-2005 sql-server-2008

我在表中有一个ID字段,两个日期字段名为From_Date和To_Date。我想用日期标准选择这个日期。

ID From_Date   To_Date
1  2011-05-03  2011-05-28
2  2011-04-29  2011-05-10
3  2011-05-09  2011-05-20
4  2011-04-28  2011-05-09
5  2011-04-29  2011-05-19
6  2011-05-09  2011-05-09
7  2011-05-09  2011-05-09
8  2011-05-09  2011-05-09
9  2011-05-21  2011-05-21
10 2011-06-06  2011-06-06
11 2011-05-21  2011-05-28
12 2011-05-14  2011-05-28
13 2011-05-23  2011-05-24
14 2011-05-27  2011-05-27
15 2011-05-23  2011-05-24

现在我想要两个参数作为开始日期和结束日期的条件 喜欢

@StartDate = '05/01/2011'
@EndDate = '05/10/2011'

当startdate和enddate参数之间的日期数组应与From_Date和To_Date字段之间的日期数组进行比较时,我想要这些参数的输出

输出:

ID From_Date   To_Date
1  2011-05-03  2011-05-18
2  2011-04-29  2011-05-10
3  2011-05-09  2011-05-20
4  2011-04-28  2011-05-09
5  2011-04-29  2011-05-19
6  2011-05-09  2011-05-09
7  2011-05-09  2011-05-09
8  2011-05-09  2011-05-09

这可能在单个查询中使用触发器或函数吗?

2 个答案:

答案 0 :(得分:2)

如果您希望获得From_DateTo_Date的所有记录都位于您的日期范围(@StartDate and @EndDate)之间,则可以使用以下简单查询:

SELECT * FROM TableName
WHERE (From_Date BETWEEN @StartDate AND @EndDate) OR (To_Date BETWEEN @StartDate AND @EndDate);

答案 1 :(得分:1)

select *
from YourTable
where From_Date <= @EndDate and
      To_Date >= @StartDate

http://data.stackexchange.com/stackoverflow/q/113761/