SELECT Date, TotalAllowance
FROM Calculation
WHERE EmployeeId = 1
AND Date BETWEEN to_date('2011/02/25','yyyy-mm-dd')
AND to_date ('2011/02/27','yyyy-mm-dd');
declare @Approval_date datetime
set @Approval_date =getdate()
Approval_date between @Approval_date +' 00:00:00.000' and @Approval_date +' 23:59:59.999'
select * from tblUser Where
convert(varchar(10),CreatedDate,111) between '2015/04/01' and '2016/04/01' //--**Working**
或
select * from tblUser Where
(CAST(CreatedDate AS DATETIME) between CAST('2015/04/01' AS DATETIME) And CAST('2016/4/30'AS DATETIME)) //--**Working**
或
select * from tblUser Where
(YEAR(CreatedDate) between YEAR('2015/04/01') And YEAR('2016/4/30'))
//--**Working**
下面的AND是无效的:
select * from tblUser Where
Convert(Varchar(10),CreatedDate,111) >= Convert(Varchar(10),'01-01-2015',111) and Convert(Varchar(10),CreatedDate,111) <= Convert(Varchar(10),'31-12-2015',111) //--**Not Working**
select * from tblUser Where
(Convert(Varchar(10),CreatedDate,111) between Convert(Varchar(10),'01-01-2015',111) And Convert(Varchar(10),'31-12-2015',111)) //--**Not Working**
永远不要使用这样的代码:Date between '2011/02/25' and '2011/02/27 23:59:59.999'
或者这个:Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'
想知道为什么,自己试试吧:
DECLARE @DatetimeValues TABLE
(MyDatetime datetime);
INSERT INTO @DatetimeValues VALUES
('2011-02-27T23:59:59.997')
,('2011-02-28T00:00:00');
SELECT MyDatetime
FROM @DatetimeValues
WHERE MyDatetime BETWEEN '2020-01-01T00:00:00' AND '2020-01-01T23:59:59.999';
SELECT MyDatetime
FROM @DatetimeValues
WHERE MyDatetime >= '2011-02-25T00:00:00' AND MyDatetime <= '2011-02-27T23:59:59.999';