正如在主题行中提到的,SQL返回的结果不在特定的日期范围内,这是我在下面的SQL剪辑:
DECLARE @StartDate DATETIME
,@EndDate DATETIME
SET @StartDate = '2017-03-04 00:50:00.000'
SET @EndDate = '2017-03-05 01:30:00.000
SELECT * FROM table (NOLOCK) WHERE CreatedOn BETWEEN @StartDate AND @EndDate
部分结果
CreatedOn
2017-03-04 04:59:57.010
2017-03-04 17:39:50.460
2017-03-04 05:28:22.610
2017-03-04 20:54:39.257
2017-03-04 17:33:19.107
答案 0 :(得分:0)
Try below query and also check your CreatedOn data type as DATETIME OR
VARCHAR
DECLARE @StartDate DATETIME,@EndDate DATETIME
SET @StartDate = '2017-03-04 00:50:00.000'
SET @EndDate = '2017-03-05 01:30:00.000
SELECT * FROM table (NOLOCK)
WHERE DATEDIFF(DAY,CreatedOn,@StartDate) <= 0 AND
DATEDIFF(DAY,CreatedOn,@EndDate) >= 0
答案 1 :(得分:0)
正如其他人所说,对于给定的CreatedOn测试数据,您无法获得不同的结果。如果仍有问题,您需要发布实际结果与预期结果。
以下是我测试的脚本,它始终打印Yes
(因为日期在范围内)
SET NOCOUNT ON
DECLARE @StartDate DATETIME = '2017-03-04 00:50:00.000',
@EndDate DATETIME = '2017-03-05 01:30:00.000'
DECLARE @CreatedOn TABLE
(
id INT IDENTITY,
CreatedOn DATETIME
)
INSERT @CreatedOn (CreatedOn)
VALUES ('2017-03-04 04:59:57.010'),
('2017-03-04 17:39:50.460'),
('2017-03-04 05:28:22.610'),
('2017-03-04 20:54:39.257'),
('2017-03-04 17:33:19.107'),
DECLARE @index INT = (SELECT COUNT(1) FROM @CreatedOn)
DECLARE @testDate DATETIME
WHILE @index >= 1
BEGIN
SELECT
@testDate = CreatedOn
FROM @CreatedOn
WHERE id = @index
IF @testDate BETWEEN @StartDate AND @EndDate
PRINT CAST(@testDate AS VARCHAR) + ' Yes'
ELSE
PRINT CAST(@testDate AS VARCHAR) + ' No'
SET @index = @index - 1
END
但是,DateTime值取决于区域。如果您使用CreatedOn
或YYYYMMDD
格式的YYYY-MM-DD
变量/字段值,则它们与语言无关。
如果使用其他格式,则可能只会得到不同的结果。例如,如果您要验证'04.03.2017 18:00'
的日期范围,则会失败,因为它将在英语区域设置中被解释为2017年3月4日。
这是一个小型测试脚本。
SET LANGUAGE 'German'
DECLARE @testDateRegion DATETIME = '04.03.2017 15:24'
PRINT CAST(@testDateRegion AS VARCHAR)
GO
SET LANGUAGE 'English'
DECLARE @testDateRegion DATETIME = '04.03.2017 15:24'
PRINT CAST(@testDateRegion AS VARCHAR)
,输出为,
Die Spracheneinstellung wurde auf Deutsch geändert.
Mär 4 2017 3:24PM
Changed language setting to us_english.
Apr 3 2017 3:24PM