hopefully a quick one this.
The below doesn't work:
DECLARE @stringDate nvarchar(50)
SET @stringDate = '0001-01-01T12:00:00'
SELECT
@stringDate AS StringDate,
CONVERT(datetime, @stringDate, 126) AS ConvertedDate
Produces the error: The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
What's the simplest way of achieving the conversion?
Thanks
As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)
The T-SQL language offers two functions to convert data from one data type to a target data type: CAST and CONVERT. In many ways, they both do the exact same thing in a SELECT statement or stored procedure, but the SQL Server CONVERT function has an extra parameter to express style.
You can convert a DATETIME to a DATE using the CONVERT function. The syntax for this is CONVERT (datetime, format).
Type Datetime
does not support the year 0001. Supported range is 1753 to 9999.
As a workaround you can use type DateTime2
instead
SELECT
@stringDate AS StringDate,
CONVERT(datetime2, @stringDate, 126) AS ConvertedDate
It doesn't work because for DATETIME
data type the
Date range [is] January 1, 1753, through December 31, 9999.
You have to use the new data type DATETIME2
:
SET ANSI_WARNINGS OFF; --Not recommended
SET ARITHABORT OFF; --Not recommended
DECLARE @stringDate nvarchar(50)
SET @stringDate = '0001-01-01T12:00:00'
SELECT
@stringDate AS StringDate,
CONVERT(datetime, @stringDate, 126) AS Converted_DATETIME,
CONVERT(datetime2, @stringDate, 126) AS Converted_DATETIME2_A,
CONVERT(datetime2(0), @stringDate, 126) AS Converted_DATETIME2_B
Results:
StringDate Converted_DATETIME Converted_DATETIME2_A Converted_DATETIME2_B
------------------- ------------------ ---------------------- ----------------------
0001-01-01T12:00:00 NULL 0001-01-01 12:00:00.00 0001-01-01 12:00:00
Arithmetic overflow occurred.
Note: you may change the default precision for DATETIME2
data type if your date/time values doesn't have "fractional seconds precision": DATETIME2(0)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With