SQL 检查值是否为日期并将其转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16353411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 15:05:19  来源:igfitidea点击:

Check if value is date and convert it

sqlsql-serversqldatetime

提问by Inus C

I receive data in a certain format. Dates are numeric(8,0). For example 20120101 = YYYYMMDD

我以某种格式接收数据。日期是数字(8,0)。例如20120101 = YYYYMMDD

There exists rows with values like (0,1,2,3,6)in that date field, thus not a date.

存在具有与(0,1,2,3,6)该日期字段类似的值的行,因此不是日期。

I want to check if it is a date and convert it, else it can be null.

我想检查它是否是日期并将其转换,否则它可以为空。

Now the following code works, but I was hoping there is a better way.

现在以下代码有效,但我希望有更好的方法。

(CASE WHEN [invoice_date] LIKE '________' --There are 8 underscores
 THEN convert(datetime, cast([invoice_date] as char(8)))
 END) AS Invoice_Date

Any help will be appreciated.

任何帮助将不胜感激。

回答by Deniyal Tandel

use isdate function like ..

使用 isdate 函数,如 ..

  (CASE WHEN ISDATE (invoice_date) = 1 
             THEN convert(datetime, cast([invoice_date] as char(8)))
             END) AS Invoice_Date

回答by von v.

You can use the ISDATE function, but what would do for non-date values? In my suggested solution you can choose to return a null:

您可以使用 ISDATE 函数,但是对于非日期值会怎样呢?在我建议的解决方案中,您可以选择返回空值:

select 
    (case 
        when ISDATE (invoice_date)=1
        then convert(datetime, invoice_date)
    else null end) AS Invoice_Date
from your_table

回答by von v.

ISDATE

伊斯达特

Returns 1 if the expression is a valid date, time, or datetime value; otherwise, 0. ISDATE returns 0 if the expression is a datetime2 value.

如果表达式是有效的日期、时间或日期时间值,则返回 1;否则,0。如果表达式是 datetime2 值,ISDATE 返回 0。

Please visit

请拜访

回答by kiriloff

You can go with TRYCATCH

你可以去 TRYCATCH

DECLARE @Source             char(8)
DECLARE @Destination        datetime

set @Source='07152009'
BEGIN TRY
    SET @Destination=CONVERT(datetime,RIGHT(@Source,4)        -- YYYY
                                      +LEFT(@Source,2)        -- MM
                                      +SUBSTRING(@Source,3,2) -- DD
                             )
END TRY
BEGIN CATCH
    PRINT 'ERROR!!!'  
END CATCH

SELECT @Source AS Source, @Destination AS Destination