SQL Server:比较日期范围之间的日期

时间:2017-09-12 16:58:20

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

我有这个代码无效。 @SomeDate is of datetime`数据类型。我只对日期部分感兴趣,比较时不需要时间:

DECLARE @year VARCHAR = datepart(year,@SomeDate)
DECLARE @FromDate DATE = CAST(@year + '-' + CAST(1 AS varchar) + '-' + CAST(1 AS varchar) AS DATETIME)
DECLARE @ToDate DATE = CAST(@year + '-' + CAST(5 AS varchar) + '-' + CAST(1 AS varchar) AS DATETIME)

IF (@SomeDate NOT BETWEEN @FromDate AND @ToDate)

分配@FromDate和@ToDate变量时失败了,它说:转换varchar到日期时间超出了间隔

尝试#1:

DECLARE @year VARCHAR(4) = datepart(year,@SomeDate)
DECLARE @FromDate DATE = CAST(@year + '-' + CAST(1 AS varchar(2)) + '-' + CAST(1 AS varchar(2)) AS DATETIME)
DECLARE @ToDate DATE = CAST(@year + '-' + CAST(5 AS varchar(2)) + '-' + CAST(1 AS varchar(2)) AS DATETIME)

IF (@SomeDate NOT BETWEEN @FromDate AND @ToDate)

但没有工作

2 个答案:

答案 0 :(得分:1)

它失败了,因为您没有为任何varchars指定长度。看看@Year的结果。它将成为*(未指定长度被视为varchar(1),在这种情况下,SQL会扭曲为星号)。将@year的长度指定为varchar(4)(并在cast语句中执行相同操作)。您应该养成始终指定数据类型长度的习惯,以避免出现这类问题。

e.g。

declare @someDate datetime = getdate()

DECLARE @year VARCHAR(4) = datepart(year,@SomeDate)
DECLARE @FromDate DATE = CAST(@year + '-' + CAST(1 AS varchar(2)) + '-' + CAST(1 AS varchar(2)) AS DATETIME)
DECLARE @ToDate DATE = CAST(@year + '-' + CAST(5 AS varchar(2)) + '-' + CAST(1 AS varchar(2)) AS DATETIME)

IF (@SomeDate NOT BETWEEN @FromDate AND @ToDate)
select 1

答案 1 :(得分:0)

您可以稍微简化一下

示例(请参阅声明@FromDate和@ToDate)

Declare @SomeDate date = GetDate()

Declare @FromDate date = DateName(YEAR,@SomeDate)+'0101'
Declare @ToDate   date = DateName(YEAR,@SomeDate)+'0501'

Select FromDate = @FromDate
      ,ToDate   = @ToDate
      ,SomeDate = @SomeDate
      ,IsBetween = case when @SomeDate between @FromDate and @ToDate then 'Yes' else 'No' end

<强>返回

FromDate    ToDate      SomeDate    IsBetween
2017-01-01  2017-05-01  2017-09-12  No