1

I have a column which contains data but the problem is that this column has data type of varchar(50) and it has to be this due to some reasons,now what i want to do is while selecting data from table , i want to treat this column as date so that i can use it in where clause. i am using the code below for converting it yo date , but it converts some values and then gives an error this is my sample data

8/1/2002
6/9/2001
14/9/2001
26/7/2001
14/12/2001
21/1/2002
29/4/2001
7/5/2001
9/11/2001
16/7/2001


select CONVERT(date,sowingDate,103) from tblAgriculture_staging

I have tried which differnt version of date format e.g 103,105 etc

but still it converts some values but error comes on some values and query execution stops

4

4 回答 4

1

尝试这个:

SET DATEFORMAT dmy;
select case when isdate(sowingDate) = 1 then CONVERT(date,sowingDate,103) end [date] from tblAgriculture_staging

或(如果您使用的是 sql 2012)

SET DATEFORMAT dmy;
select case when TRY_CONVERT(date, sowingDate) IS NOT NULL then CONVERT(date,sowingDate,103) end [date] from tblAgriculture_staging

但此解决方案隐藏(转换为 NULL)所有错误的日期。您可以先反转条件并查找/修复所有日期不正确的行(即 2013 年 2 月 31 日),然后使用此查询仅显示有效日期

SQLFiddle

于 2013-11-13T15:00:37.813 回答
0

这有点糟糕,但将日期存储为 varchar 也是如此。

这是过去对我有用的代码,我有一些日期是 4 位数年份,有些日期是 2 位数年份。

 where  (TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),1)>=@From
            AND TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),1)<=@To)
        OR (TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),101)>=@From
            AND TRY_CONVERT(Datetime2,LTRIM(RTRIM([INVC DTE])),101)<=@To)

仅限 SQL Server 2012 +

这假设你已经清理了任何实际上不是约会的东西......

于 2013-11-13T15:09:17.423 回答
0

但它会转换一些值然后给出错误这是我的示例数据

因为某些数据格式无效或包含不正确的符号。
尝试这个:

select CONVERT(date,ltrim(rtrim(sowingDate)), 103) from tblAgriculture_staging

或检查您的价值观:

select ISDATE(sowingDate) as IsDate, sowingDate, CASE WHEN ISDATE(sowingDate)=1 THEN CONVERT(date,ltrim(rtrim(sowingDate)), 103) ELSE NULL END from tblAgriculture_staging
于 2013-11-13T15:01:59.197 回答
0

这将返回所有不是实际日期的日期。

select sowingDate from tblAgriculture_staging where isdate(sowingDate)=0
于 2013-11-13T15:03:27.117 回答