-1

I try to convert the column [policyeffective_date] which looks like YYYYMMDD (for example 20190430) into a date in SQL Server.

I tried a few solutions find on the forum, but none worked. Currently I have the following code and errors:

SELECT 
    CONVERT(DATETIME, policyeffective_date, 104) AS test 
FROM 
    [DATAWAREHOUSE].[dbo].[blabla]

Error:

Arithmetic overflow error converting expression to data type datetime.

I also tried:

SELECT 
    CONVERT(DATE, CONVERT(NVARCHAR(8), policyeffective_date), 104)    
FROM 
    [DATAWAREHOUSE].[dbo].[blabla]

Error:

Operand type clash: int is incompatible with date

Thank you for your help

4

2 回答 2

1

您似乎在该列中有错误的数据。鉴于您收到的是运行时错误而不是编译时错误,这些类型似乎是正确的。

最简单的解决方案是try_convert()

SELECT try_convert(datetime, policyeffective_date, 104) AS test 
FROM [DATAWAREHOUSE].[dbo].[blabla];

但是要找到问题,您可以使用:

SELECT policyeffective_date
FROM [DATAWAREHOUSE].[dbo].[blabla]
WHERE try_convert(datetime, policyeffective_date, 104) IS NULL AND
      policyeffective_date IS NOT NULL
于 2019-07-20T00:09:49.773 回答
-1

这在 SQL Server 2017 中适用于我:

select cast(cast(20190430 as nvarchar) as DATE) AS DateResult

输出:

DateResult
2019-04-30
于 2019-07-19T23:38:55.613 回答