[英]String to date in MS Access SQL statement gives type mismatch error
Currently doing a data migration from a Microsoft Access database to a Microsoft SQL Server database using C#. 当前正在使用C#将数据从Microsoft Access数据库迁移到Microsoft SQL Server数据库。 I am trying to create a query to pull data from the Access database and order by two columns: Surname
and Date
. 我正在尝试创建一个查询,以从Access数据库中提取数据并按两列进行排序: Surname
和Date
。 The challenge is that Date
is a string in the following sample format: 12.01.13
(ie YY.MM.DD), which is supposed to represent the 13th of January 2012. So I tried the following query in Access: 挑战在于Date
是以下示例格式的字符串: 12.01.13
(即YY.MM.DD),应该表示2012年1月13日。因此,我在Access中尝试了以下查询:
SELECT * FROM [Contacts 2012]
order by Surname, CDate(Format(Date, "0000-00-00"));
However, I receive this error: 但是,我收到此错误:
Data type mismatch in criteria expression 条件表达式中的数据类型不匹配
So I figure I am getting close. 所以我想我越来越近了。 I tried a few different formats, plus maybe DateValue, but to be honest I can't remember. 我尝试了几种不同的格式,也许还有DateValue,但说实话我不记得了。 I have looked at other posts both in and outside of stackoverflow, but to no avail. 我看过stackoverflow内部和外部的其他帖子,但无济于事。
You said your dates are strings in YY.MM.DD format. 您说您的日期是YY.MM.DD格式的字符串。 If that is correct for all the stored [Date]
values ... which means Len([Date]) = 8
for all rows ... those values will sort in the same order whether you sort them as text or transform them to Date/Time values. 如果这对于所有存储的[Date]
值都是正确的...这意味着所有行的Len([Date]) = 8
...无论您将其作为文本排序还是将其转换为Date,这些值将以相同的顺序排序/时间值。
So I'll suggest this query ... 所以我建议这个查询...
SELECT *
FROM [Contacts 2012]
ORDER BY Surname, [Date];
If that returns what you want, you can avoid the data type error you're getting when attempting to transform the strings to actual dates. 如果返回所需的内容,则可以避免在将字符串转换为实际日期时遇到的数据类型错误。 Also, with an index on the [Date]
column, the query will execute significantly faster. 同样,使用[Date]
列上的索引,查询将明显更快地执行。
Note this approach is not suitable if some of your [Date]
values are not in YY.MM.DD format, eg "12.1.13" . 请注意,如果您的某些[Date]
值不是 YY.MM.DD格式,例如“ 12.1.13” ,则此方法不合适。
使用Regex.Replace
设置日期格式,并使用Regex.Split
将2位数字添加到年份。
不确定我最终如何解决这个问题,但是如果可以使用内存,我实际上是通过自然访问打开数据库来手动对数据库进行排序,然后按姓氏列按字母顺序进行排序,然后按日期列进行手动或通过select语句进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.