将日期时间的nvarchar转换为日期范围查询
问题描述:
我的GLD(GL帐户)表包括年和期间列,都是nvarchar类型。将日期时间的nvarchar转换为日期范围查询
我的目的是让用户在查询中选择一个日期范围。例如,要搜索...
- inpYearBegin:2013
- inpPeriodBegin:3
- inpYearEnd时间:2014年
- inpPeriodEnd:12
但是最终发生的是结果将不会显示2014年的第1到第2期。我认为我需要将字段转换为日期时间,但我不确定从那里去哪里。我的SQL Server查询迄今:
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~'
答
所有你需要做的是调整的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月(含)
另一种方式去那里是使用discriminent功能,像这样:
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
,简化了查询,但我真的不能说一个比另一个更容易理解。但也许更重要的是:它可能(强调可能是)为您提供更好的执行计划。
什么RDBMS?这些转换功能对于每个供应商都不相同。 –
看起来像SQL Server。但是你应该告诉,而不是让我们猜测。 –
@PieterGeerkens:它是SQL服务器;发布编辑。谢谢。 – user3769185