0

此查询工作正常:

select CONVERT(DATETIME, GroupAdminEffectiveDate, 101) from ExchangeSmallGroupEnrollment
group by GroupAdminEffectiveDate

并返回以下内容:

1900-01-01 00:00:00.000
2012-06-30 00:00:00.000
2012-07-01 00:00:00.000
2012-07-11 00:00:00.000
2012-07-23 00:00:00.000
2012-07-25 00:00:00.000
2012-08-01 00:00:00.000
2012-08-14 00:00:00.000
2012-08-26 00:00:00.000
2012-09-01 00:00:00.000
2012-09-03 00:00:00.000

但是,以下查询:

select CONVERT(DATETIME, GroupAdminEffectiveDate, 101) from ExchangeSmallGroupEnrollment

我得到以下错误:

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

有任何想法吗?非常感激。

更新:

询问:

select distinct GroupAdminEffectiveDate from ExchangeSmallGroupEnrollment

结果:

(empty string)
06/30/2012
07/01/2012
07/11/2012
07/23/2012
07/25/2012
08/01/2012
08/14/2012
08/26/2012
09/01/2012
09/03/2012
4

4 回答 4

1

我无法重现你的错误,所以我怀疑我们对“空字符串”的定义不同,或者还有其他事情你没有透露。同时,由于您使用的是 SQL Server 2012,因此您可以使用TRY_PARSE它,例如以下表达式之一:

SELECT TRY_PARSE(GroupAdminEffectiveDate AS DATETIME USING N'en-us') 
  FROM dbo.ExchangeSmallGroupEnrollment;

SELECT TRY_PARSE(GroupAdminEffectiveDate AS DATETIME USING N'en-us') 
  FROM dbo.ExchangeSmallGroupEnrollment
  GROUP BY GroupAdminEffectiveDate;

SELECT TRY_PARSE(GroupAdminEffectiveDate AS DATETIME USING N'en-us') 
  FROM dbo.ExchangeSmallGroupEnrollment
  GROUP BY TRY_PARSE(GroupAdminEffectiveDate AS DATETIME USING N'en-us');

如果您真的希望 1900-01-01 成为有效输出,则:

SELECT COALESCE(TRY_PARSE(GroupAdminEffectiveDate AS DATETIME USING N'en-us'),
    '19000101') 
  FROM dbo.ExchangeSmallGroupEnrollment
  GROUP BY TRY_PARSE(GroupAdminEffectiveDate AS DATETIME USING N'en-us');
于 2012-08-15T16:15:59.763 回答
0

您首先将您的varchar列转换为Datetime然后转换。

Declare @testvarchar VARCHAR(15) = '08/27/2012'
select CONVERT(datetime, Cast(@testvarchar as datetime), 101)

那应该可以解决您的转换错误

于 2012-12-03T18:42:44.850 回答
0

您的数据库中可能存在更多“非日期”字段。一个可以"",另一个" "。当您按或区分时,所有最终都""意味着NULL,这很好转换。否则它会失败" "(空间)。

检查select length( GroupAdminEffectiveDate ) from ExchangeSmallGroupEnrollment 也许它会给你一些线索?

于 2012-08-15T22:34:20.147 回答
-2

检查这个:

select CONVERT(DATETIME, ISDATE( GroupAdminEffectiveDate), 101) from ExchangeSmallGroupEnrollment
于 2012-08-15T15:34:30.930 回答