从日期范围获取数据

时间:2018-06-12 11:53:51

标签: sql-server

我有一个列TransationDate是十进制数据类型,数据类似于20170121 我想在日期范围内显示数据,在我的查询中它只显示一条记录。什么错误,我的询问可以由任何机构告诉我。

declare @EndDate  varchar(10)
set  @StartDate   ='20170121'
set  @EndDate     ='20170129' 

SELECT  *
    FROM  LCOM.dbo.PORCPAH PORCPAH
    WHERE CONVERT(DATETIME, CONVERT(VARCHAR(8), PORCPAH.TRANSDATE), 112) >= @StartDate
    AND CONVERT(DATETIME, CONVERT(VARCHAR(8), PORCPAH.TRANSDATE), 112) <= @EndDate

2 个答案:

答案 0 :(得分:1)

您使用的是varchar值而不是date值,因此您的比较显然无法正常运行。使用适当的数据类型可以减少问题:

declare @StartDate date = '20170121';
declare @EndDate date = '20170129';

select *
from LCOM.dbo.PORCPAH p
where p.TRANSDATE >= @StartDate
  and p.TRANSDATE <= @EndDate;

使用您的其他答案作为基础,如果您使用适当的数据类型来存储date值,则此脚本的输出与脚本中的输出相同:

declare @t table(dt date);
insert @t values('20150712'),('20160320'),('20160113'),('20170813'),('20180302'),('20160318'),('20171112'),('20180601'),('20160308'),('20180601'),('20180602'),('20180603'),('20180604'),('20180605'),('20180606');

declare @startdt date ='20180601';
declare @enddt date = '20180606';

select *
from @t
where dt between @startdt and @enddt
order by dt;

答案 1 :(得分:0)

我明白了

 declare @t table
(
dt decimal(30,0)
)
insert @t
values
(20150712),
(20160320),
(20160113),
(20170813),
(20180302),
(20160318),
(20171112),
(20180601),
(20160308),

(20180601),
(20180602),
(20180603),
(20180604),
(20180605),
(20180606)

declare @startdt varchar(20)='20180601'
declare @enddt varchar(20) = '20180606'

select *
from @t
where dt between @startdt and @enddt
order by dt