将nvarchar转换为日期范围查询的日期时间

时间:2014-07-24 23:24:21

标签: sql sql-server

我的GLD(GL帐户)表包括年份和期间列,均为nvarchar类型。

我的目的是允许用户在查询中选择一系列日期。例如,要搜索...

  • inpYearBegin:2013
  • inpPeriodBegin:3
  • inpYearEnd:2014
  • inpPeriodEnd:12

但最终发生的事情是结果不会显示2014年的1到2期。我认为我需要将字段转换为日期时间,但我不确定从那里开始。到目前为止我的SQL服务器查询:

Select GLD.GLD_EndingBalance,
  GLD.GLD_AcctNbr,
  GLD.GLD_Year,
  GLD.GLD_Period,
  Year(Cast(GLD.GLD_Year As DateTime)) As Year
From GLD
Where GLD.GLD_AcctNbr = '140000'
And GLD.GLD_Year >= '@Request.inpYearBegin~'
And GLD.GLD_Period >= '@Request.inpPeriodBegin~'
And GLD.GLD_Year <= '@Request.inpYearEnd~'
And GLD.GLD_Period <= '@Request.inpPeriodEnd~'

1 个答案:

答案 0 :(得分:0)

您需要做的就是稍微调整where子句并添加一些括号来控制比较,如下所示:

declare @FromYear  int = 2013
declare @FromMonth int =    3
declare @ThruYear  int = 2014
declare @ThruMonth int =   12

select t.GLD_EndingBalance ,
       t.GLD_AcctNbr       ,
       t.GLD_Year          ,
       t.GLD_Period        ,
       Year( Cast(GLD.GLD_Year As DateTime) ) as Year
from GLD t
where t.GLD_AcctNbr = '140000'
  and        t.GLD_Year between @FromYear and @ThruYear 
  and (      t.GLD_Year > @FromYear                                  
        OR   t.GLD_Year < @ThruYear                                  
        OR ( t.GLD_Year = @FromYear and t.GLD_Period >= @FromMonth ) 
        OR ( t.GLD_Year = @ThruYear and t.GLD_Period <= @ThruMonth )
      )

上述内容应从2013年3月至2014年12月(包括首尾两天)返回行。

另一种方法是使用像这样的区别函数:

select t.GLD_EndingBalance ,
       t.GLD_AcctNbr       ,
       t.GLD_Year          ,
       t.GLD_Period        ,
       Year( Cast(GLD.GLD_Year As DateTime) ) as Year
from GLD t
where t.GLD_AcctNbr = '140000'
  and t.GLD_Year between @FromYear and @ThruYear 
  and t.GLD_Period between case when t.GLD_YEar = @FromYear then @FromMonth else  1 end
                       and case when t.GLD_YEAR = @ThruYear then @ThruMonth else 12 end

这简化了查询,但我真的不能说一个人比另一个人更容易理解。

也许更重要的是,它可能(强调可能)为您提供更好的执行计划。