将Table中的日期与TableAU中的几个日期范围进行比较:构建WHERE语句

时间:2014-11-16 03:37:50

标签: sql sql-server tsql date between

我想从TableB中选择在VacationHistory(TableA)表中的一个日期范围之间具有开始日期的项目。

假设我有具有开始和结束日期值的VacationHistory数据表(TableA)。我需要做的是将另一个数据表(TableB)的日期与VacationHistory(TableA)中的日期范围进行比较。因此,如果VacationHistory数据表中有三个条目,我会这样做:

SELECT *
FROM TableB WHERE (
        (DateInTableB BETWEEN '2014-10-21' AND '2014-10-27')
     OR (DateInTableB BETWEEN '2014-11-05' AND '2014-11-13')
     OR (...)
)

但是,如何使用此WHERE子句中的VacationHistory表中的所有日期范围构建此查询。我想我无法说BETWEEN IN (....)

我尝试过的是构建整个where子句::

的字符串
DECLARE @listStr VARCHAR(MAX)
SELECT  @listStr = COALESCE(@listStr + ' OR ' , '') + 
    ('DateInTableB BETWEEN ''' + CAST(StartDate AS NVARCHAR) + ''' AND ' 
              + '''' + CAST(EndDate AS NVARCHAR) + '''') 
FROM VacationHistory
SELECT @listStr

@listStr有这样的内容:DateInTableB BETWEEN '2014-11-05' AND '2014-11-13' OR DateInTableB BETWEEN '2014-10-21' AND '2014-10-27'

但是,我不认为我可以直接在where子句中使用@listStr,如下所示:

WHERE (@listStr)

我该怎么办?

3 个答案:

答案 0 :(得分:1)

如果您只想在TableAU中的任何日期范围内找到Table中具有开始日期的行,您可以使用相关的exists

select * 
from TableB b 
where exists (
    select 1 
    from TableA a
    where b.StartDate between a.StartDate and a.EndDate
)

Sample SQL Fiddle

答案 1 :(得分:0)

简单INNER JOIN就是您所需要的。

SELECT DISTINCT b.id,
       b.StartDate
FROM   TableB b
       JOIN TableA a
         ON b.StartDate BETWEEN a.StartDate AND a.EndDate 

或者

SELECT *
FROM   TableB
       INNER JOIN (SELECT Min(StartDate) StartDate,
                          Max(EndDate)   EndDate
                   FROM   TableA) A
               ON DateInTableB BETWEEN A.StartDate AND A.EndDate 

如果您希望以您尝试过的方式获得答案,那么您需要Dynamic SQL

declare @sql nvarchar(max)
DECLARE @listStr VARCHAR(MAX)

SELECT  @listStr = COALESCE(@listStr + ' OR ' , '') + 
    ('DateInTableB BETWEEN ''' + CAST(StartDate AS NVARCHAR) + ''' AND ' 
              + '''' + CAST(EndDate AS NVARCHAR) + '''') 
FROM VacationHistory


set @sql = 'SELECT *
FROM TableB where '+@listStr+''

exec sp_executesql @sql

答案 2 :(得分:0)

SELECT *
FROM TableB
inner join 
(
select Min(StartDate) StartDate, Max(EndDate) EndDate From TableA
) A
on  DateInTableB between A.StartDate and A.EndDate