-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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
nimavancouver
  • 97
  • 1
  • 8

2 Answers2

1

You would seem to have bad data in the column. Given that you are getting a run-time error and not a compile-time error, the types seem correct.

The simplest solution is try_convert():

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

But to find the problem, you can use:

SELECT policyeffective_date
FROM [DATAWAREHOUSE].[dbo].[blabla]
WHERE try_convert(datetime, policyeffective_date, 104) IS NULL AND
      policyeffective_date IS NOT NULL
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

This works for me in SQL Server 2017:

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

Output:

DateResult
2019-04-30
Ken White
  • 123,280
  • 14
  • 225
  • 444