在我的工作中,我尝试创建一个查询以从SQL数据库中获取一些信息。这样做很好,但是当我尝试使用日期范围时,它会停止工作。
我已经找到了DATEPART功能,
SELECT
*
FROM
InlogLog as il
INNER JOIN
ComputerIdentity as ci
ON il.Computer = ci.Description
WHERE ci.Location
LIKE 'E18%'
AND ci.MakeModelID = 9
AND DATEPART(YY,il.Datum) = 2016
AND DATEPART(MM,il.Datum) = 10
AND DATEPART(DD,il.Datum) = 03
ORDER BY il.Computer
在上面的示例中,我无法指定两个日期之间的范围。 我也尝试过使用这个例子
SELECT
*
FROM
InlogLog as il
INNER JOIN
ComputerIdentity as ci
ON il.Computer = ci.Description
WHERE ci.Location
LIKE 'E18%'
AND ci.MakeModelID = 9
AND il.Datum = '2016-06-17 09:57:00.000'
但是这会导致错误消息
将varchar数据类型转换为日期时间数据类型会导致超出范围的值。
如何使下一个示例正常工作?
SELECT
*
FROM
InlogLog as il
INNER JOIN
ComputerIdentity as ci
ON il.Computer = ci.Description
WHERE ci.Location
LIKE 'E18%'
AND ci.MakeModelID = 9
AND il.Datum '2016-06-17 09:57:00.000' BETWEEN '2016-06-18 00:00:00.000'
答案 0 :(得分:2)
问题在于语法(il.Datum '2016-06-17 09:57:00.000' BETWEEN '2016-06-18 00:00:00.000'
),修改你的脚本如下。
如果您的列是varchar,请将其转换为datetime。
SELECT *
FROM
InlogLog as il
INNER JOIN
ComputerIdentity as ci
ON il.Computer = ci.Description
WHERE ci.Location
LIKE 'E18%'
AND ci.MakeModelID = 9
AND CAST(il.Datum as datetime) BETWEEN '2016-06-17 09:57:00.000' AND '2016-06-18 00:00:00.000'
答案 1 :(得分:1)
看起来Datum属于varchar数据类型,它应该是datetime数据类型
试试这个
SELECT
*
FROM
InlogLog as il
INNER JOIN
ComputerIdentity as ci
ON il.Computer = ci.Description
WHERE ci.Location
LIKE 'E18%'
AND ci.MakeModelID = 9
AND il.Datum >='2016-06-17 09:57:00.000' il.Datum<= '2016-06-18 00:00:00.000'
答案 2 :(得分:1)
如果il.Datum是varchar类型,那么你应该按如下方式进行转换:
SELECT
*
FROM
InlogLog as il
INNER JOIN
ComputerIdentity as ci
ON il.Computer = ci.Description
WHERE ci.Location
LIKE 'E18%'
AND ci.MakeModelID = 9
AND CONVERT(DATE, ilDatum) >= CONVERT(DATE, '2016-10-01')
AND CONVERT(DATE, ilDatum) <= CONVERT(DATE, '2016-10-04')
注意:我已将varchar转换为列il.Datum的日期类型。如果没有专门针对varchar类型的转换,则无法过滤日期。
答案 3 :(得分:0)
SELECT * FROM InlogLog as il INNER JOIN
ComputerIdentity as ci
ON il.Computer = i.Description WHERE ci.Location
LIKE 'E18%' AND ci.MakeModelID = 9 AND
DATEDIFF(DAY,ilDatum,'2016-06-17') <= 0 AND
DATEDIFF(DAY,ilDatum,'2016-06-18') >=0