在 SQL 服务器中查找导致类型转换错误的行

Finding row causing error in type conversion in SQL Server

我正在尝试将 varchar 中的列转换为 smalldatetime。有些行包含错误,如何找到它们?

SELECT 
    PA.EAR_TAG 
    ,ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE) as HB_Date
    ,Y.[DATE OF MOVEMENT] as Y_Date
    ,DATEDIFF(DAY, ISNULL(B.DISPOSAL_DATE, H.DISPOSAL_DATE), cast(Y.[DATE OF MOVEMENT] as smalldatetime))
FROM
    DairyTelomere.dbo.PROJECT_ANIMALS AS PA
LEFT JOIN 
    Langhill.dbo.YOUNG_STOCK_BULL AS B ON Pa.EAR_TAG = B.EAR_TAG
LEFT JOIN      
    Langhill.dbo.YOUNG_STOCK_HEIFER AS H ON PA.EAR_TAG = H.EAR_TAG
LEFT JOIN      
    DairyTelomere.dbo.Young_Stock_culls AS Y ON PA.EAR_TAG = Y.Ear_Tag

我得到的错误是:

Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.

我知道如果该列是日期格式,我可以使用 ISDATE() 检查它,但不幸的是我无法更改列类型(没有权限)。

任何想法将不胜感激。

您可以使用 isdate 获取所有未为您转换的列表。您不需要更改列类型即可使用它,所以我对您的陈述感到困惑

if the column was in a date format I could check it by using ISDATE() but unfortunately I can't change the column type (don't have permissions)

如果你能澄清的话会有更多帮助,但这个查询应该给你一个包含错误日期值的行的列表。

select table.date_as_varchar
from table
where isdate(table.date_as_varchar) = 0

添加到@workabyte 答案你也可以尝试使用 TRY_PARSETRY_CASTTRY_CONVERT,如果转换失败,全部 return NULL , 这样你就可以知道是哪几行导致了错误。

TRY_PARSE

正如 documentation 所说:

Use TRY_PARSE only for converting from string to date/time and number types. For general type conversions, continue to use CAST or CONVERT. Keep in mind that there is a certain performance overhead in parsing the string value.

用法示例:

SELECT TRY_PARSE(your_date  AS DATETIME USING 'es-ES') as date
FROM your_table

es-ES是一个文化参数,不同的文化参数在你的转换中会产生不同的结果,你可以在文档中找到完整的参数列表

TRY_CONVERT

正如 documentation 所说:

TRY_CONVERT takes the value passed to it and tries to convert it to the specified data_type. If the cast succeeds, TRY_CONVERT returns the value as the specified data_type; if an error occurs, null is returned. However if you request a conversion that is explicitly not permitted, then TRY_CONVERT fails with an error.

用法示例:

SELECT TRY_CONVERT(DATETIME,your_date,103) as date
FROM your_table

103 是您要转换的日期的 style/format,here 您可以找到可用格式的列表

TRY_CAST

正如 documentation 所说:

TRY_CAST takes the value passed to it and tries to convert it to the specified data_type. If the cast succeeds, TRY_CAST returns the value as the specified data_type; if an error occurs, null is returned. However if you request a conversion that is explicitly not permitted, then TRY_CAST fails with an error.

用法示例:

SELECT TRY_CAST(your_date AS DATETIME) as date
FROM your_table