SQL:如何比较nvarchar数据类型中的日期值

时间:2009-09-26 18:24:25

标签: sql sql-server tsql

如何构建这样的查询语句:

select * from men where Tdate between 01/01/01 and 02/02/02

Tdate列的类型为nvarchar

我正在使用SQL Server Compact Edition(sqlCE)

由于

2 个答案:

答案 0 :(得分:4)

SELECT 
  * 
FROM
  men 
WHERE
  CONVERT(DATETIME, Tdate) BETWEEN '01/01/01' and '02/02/02'

取决于日期格式和当前DATEFORMAT seting CONVERT()是否有效。

建议将列转换为实际的DATETIME数据类型。

答案 1 :(得分:1)

您可能在CAST列的WHERE子句中寻找CONVERTnvarchar语句。

SELECT * 
FROM Men 
WHERE CAST(Tdate AS Datetime) 
BETWEEN '01/01/09' and '02/02/09'

以下是概念证明:

declare @sample table
(
   TDate nvarchar(100)
)

Insert into @sample (TDate )  --yes, this INSERT work on SQL 2008 only :)
Values ('jan 1 2009'),('jan 10 2009'), ('feb 8 2009'),('feb 12 2009')

SELECT * 
FROM @sample 
WHERE CAST(Tdate AS Datetime) BETWEEN '01/01/09' AND '02/10/09'