SQL查询 - 检查日期是否在关闭日

时间:2010-12-16 15:22:05

标签: sql sql-server tsql

我正在创建一个在线预订系统&需要将被关闭的日期排除在预订之外。需要一个选择查询来查看“日期”(圣诞节)是否>> = [ClosedFrom] AND< = [ClosedTo]

ClosedFrom& ClosedTo是SQL Server 2008中的日期时间列。

这是我的表格:

 ----------------------------------------------------------
 ClosedDateID     --     ClosedFrom     --     ClosedTo
 ----------------------------------------------------------
 1                --     2010-12-24     --     2010-01-04
 2                --     2011-04-20     --     2010-04-20
 ----------------------------------------------------------

以下查询有望向您展示我想要实现的目标:

 SELECT [ClosedFrom],[ClosedTo]
 FROM [Package.Closed.Dates]
 where '2010-12-25' >=  [ClosedFrom] AND '2010-12-25' <= [ClosedTo] 

先谢谢你的帮助;)


UPDATE:

感谢Refilter的回答,但我仍然无法解决这个问题:(我在下面提供了更多详情。

这是我的表脚本:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Package.Closed.Dates](
    [ClosedDateID] [int] IDENTITY(1,1) NOT NULL,
    [ClosedDate] [datetime] NULL,
    [ClosedFrom] [datetime] NULL,
    [ClosedTo] [datetime] NULL,
 CONSTRAINT [PK_Package.Closed.Dates] PRIMARY KEY CLUSTERED 
(
    [ClosedDateID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

这是我的表数据:

INSERT INTO [dbo].[Package.Closed.Dates]
           ([ClosedDate]
           ,[ClosedFrom]
           ,[ClosedTo])
     VALUES
           ('2010-12-25'
           ,'2010-12-20'
           ,'2010-12-28'
GO

这是我的查询,检查单个日期(ClosedDate)以查看我们是否已关闭(此返回“我们当天关闭” - 工作):

if exists (

SELECT [ClosedDate]
  FROM [Package.Closed.Dates]
  where [ClosedDate] =  '2010-12-25'

)

select 'we are CLOSED that day'

else 

select 'we are OPEN that day'

以下是您在两个日期(ClosedFrom&amp; ClosedTo)之间进行检查的查询,以查看我们是否已关闭(此时总是返回“我们当天打开” - 不工作):

if exists (

SELECT [ClosedFrom],[ClosedTo] 
  FROM [Package.Closed.Dates]
where '2010-12-25' between [ClosedFrom] AND [ClosedTo]  

)

select 'we are CLOSED that day'

else 

select 'we are OPEN that day'

我也尝试了下面的查询(这总是回归“我们当天打开” - 不工作):


if exists (
SELECT [ClosedFrom],[ClosedTo] 
  FROM [MWD.Package.Closed.Dates]
where '2010-12-25' >= [ClosedFrom] AND '2010-12-25' <= [ClosedTo]
) select 'we are CLOSED that day' else select 'we are OPEN that day'

另外一个快速说明,我需要查看“日期”(圣诞节)是否>&gt; = [ClosedFrom] AND&lt; = [ClosedTo]

2 个答案:

答案 0 :(得分:3)

SELECT [ClosedFrom], [ClosedTo]  
FROM [Package.Closed.Dates]  
where '2010-12-25' between [ClosedFrom] AND [ClosedTo]  

答案 1 :(得分:0)

这可能适合你。这将删除时间组件并使其成为00

DECLARE @DateToCheck DATETIME
SET @DateToCheck = '2010-12-25'    

IF EXISTS ( SELECT 1   
            FROM [Package.Closed.Dates]   
            WHERE CONVERT(DATETIME,@DateToCheck,112) BETWEEN CONVERT(DATETIME, 
                  [ClosedFrom],112) AND CONVERT(DATETIME,[ClosedTo] ,112)
          )
   SELECT 'we are CLOSED that day'    
ELSE     
   SELECT 'we are OPEN that day'