I'm trying to pin down a failing query and it is related to dates. I have managed to reproduce the issue in a fairly simple script (see below). In order to eliminate any potential language and region issues related to date formats we created a clean VM with Windows and SQL Server installed all using UK/British English options where availble.
My script is below:
set language 'british'
go
declare @datetimeYMD_T datetime = '2022-10-31T12:34:56.123' -- WORKS (expected)
declare @datetimeYMD datetime --= '2022-10-31 12:34:56.123' -- FAILS (NOT expected) 'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
declare @dateYMD date = '2022-10-31' -- WORKS (expected)
declare @datetimeYDM datetime = '2022-31-10 12:34:56.123' -- WORKS (NOT expected)
declare @dateYDM date -- = '2022-31-10' -- FAILS (expected) 'Conversion failed when converting date and/or time from character string.'
select @@LANGUAGE as Language, @datetimeYMD_T as 'YMD_T DateTime', @datetimeYMD as 'YMD DateTime', @dateYMD as 'YMD Date', @datetimeYDM as 'YDM DateTime', @dateYDM as 'YDM Date'
What I don't understand is why a YYYY-MM-DD format works for date
datatype work but not a datetime
datatype (without the T
).
Also if I changed the script to have a us_english
language then as I would expect the YMD formats work and the YDM fail.
I appreciate just adding a T
would resolve things but that would involve updating lots of scripts, etc. and it's something I'd rather avoid. I'm also concerned this would be masking a deeper issue that could be manifesting itself in other, as yet unnoticed ways and/or could be a ticking time bomb.
This is being run on Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64) on a Windows Server 2019 OS.