在where子句中使用char类型的日期

时间:2010-10-27 22:38:44

标签: sql sql-server date char where-clause

我有一个SQL Server数据库表,其中一个名为“DATE”的char列(我知道,非常糟糕,但我没有创建数据库),其日期以此格式存储为字符串:YYMMDD。我需要在这些日期之间返回记录,所以将它们视为实际日期,我已经尝试了我知道的每一个组合,但仍然会出错。任何帮助深表感谢。我已经尝试了所有这些但没有运气:

SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), [DATE], 112) AS datetime) BETWEEN '100401' AND '101001'
SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), [DATE], 12) AS datetime) BETWEEN '100401' AND '101001'
SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), "DATE", 112) AS datetime) BETWEEN '100401' AND '101001'
SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), "DATE", 12) AS datetime) BETWEEN '100401' AND '101001'
SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), [DATE], 112) AS datetime) >= 100401 AND CAST(CONVERT(char(8), [DATE], 112) AS datetime) <= 101001
SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), [DATE], 12) AS datetime) >= 100401 AND CAST(CONVERT(char(8), [DATE], 12) AS datetime) <= 101001
SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), "DATE", 112) AS datetime) >= 100401 AND CAST(CONVERT(char(8), "DATE", 112) AS datetime) <= 101001
SELECT * FROM caddb..INCIDENT WHERE CAST(CONVERT(char(8), "DATE", 12) AS datetime) >= 100401 AND CAST(CONVERT(char(8), "DATE", 12) AS datetime) <= 101001
SELECT * FROM caddb..INCIDENT WHERE CAST([DATE] AS INT) >= 100401 AND CAST([DATE] AS INT) < 101001
SELECT * FROM caddb..INCIDENT WHERE CAST("DATE" AS INT) >= 100401 AND CAST("DATE" AS INT) < 101001
SELECT * FROM caddb..INCIDENT WHERE CAST([DATE] AS INT) BETWEEN 100401 AND 101001
SELECT * FROM caddb..INCIDENT WHERE CAST("DATE" AS INT) BETWEEN 100401 AND 101001

2 个答案:

答案 0 :(得分:1)

这里有几件事:

  • 您可以选择CAST和CONVERT,但不能同时选择
  • 在您的情况下,CONVERT更合适,因为您可以指定确切的格式(12)。如果字符串没有像101231这样的世纪,则使用12;如果字符串具有像20101231这样的世纪,则使用112;
  • 使用CONVERT时,指定所需的数据类型,而不是原始var的数据类型
  • 如果您键入字符串文字,如“2010-10-28”yyyy-MM-dd
  • ,MS SQL可以将字符串文字识别为日期时间

所以,你可以做类似

的事情
convert(datetime, [DATE], 12) between '2010-10-01' and '2010-10-10'

答案 1 :(得分:0)

试一试。您需要将所有字段和常量转换为DATETIME数据类型。

SELECT * 
FROM caddb..INCIDENT 
WHERE CONVERT(datetime, "DATE", 112) BETWEEN CONVERT(datetime, '100401', 112) and CONVERT(datetime, '101001', 112)