Which user/db setting would cause the date conversion here to fail with Conversion failed when converting date and/or time from character string?
SELECT
-- This works:
CONVERT(datetime2, '01 ' + LEFT([MonthName], 3) + ' ' + CAST([Year] as char(4)), 106)
-- This doesn't:
,CONVERT(datetime2, '01 ' + LEFT([MonthName], 3) + ' 2018', 106)
[Year] is of type int NOT NULL.
[MonthName] is of type nvarchar(100) NOT NULL and its collation is SQL_Latin1_General_CP1_CI_AS.
DBCC USEROPTIONS shows this:
language | us_english
dateformat | mdy
I tried creating another table with seemingly the same settings and the query works there. Something is obviously different but I can't figure out what.
EDIT
Doing a SELECT DISTINCT [Year], [MonthName] reveals that there's data only for 'December', 2017. So yes, the month name is in English.
Leap years can't be the problem because of the previous point but also because I'm forcing the day to be 1.
Interestingly, TRY_CONVERT doesn't return NULL for any row. I did a
WHERE TRY_CONVERT(datetime2, '01 ' + LEFT([MonthName], 3) + ' 2018', 106) IS NULL
I'm suspecting that inputting the ' 2018' causes the resulting string to be of some other collation (or something) which makes SQL Server expect the date format to be something different.
Here's the weird part. The query works if it's like this:
SELECT DISTINCT
CONVERT(datetime2, + LEFT([MonthName], 3) + '01 2018', 106)
,CONVERT(datetime2, '01 ' + LEFT([MonthName], 3) + ' 2018', 106)
,[Year]
But removing either the [Year] or the DISTINCT will again produce the same error.
The query has only two tables joined in the FROM clause and no WHERE clause. The [MonthName] comes from the second table and the [Year] from the first.
select...statements for eachCONVERT()what error message do you receive for the second statement? – John K. N. May 11 '18 at 07:11CONVERT()is the only statement in theSELECTstatement, I get theConversion failed when converting date and/or time from character stringerror. – Kim May 11 '18 at 09:27TRY_CONVERTinstead ofCONVERTand including the base columns of your select might reveal something with your data.TRY_CONVERTwill returnNULLif the conversion fails. – Scott Hodgin - Retired May 11 '18 at 09:33MonthNamecolumn? Are you using English month names or possibly another language? – John K. N. May 11 '18 at 09:38SELECTcomes almost last in the logical processing order and certainly afterFROM. See: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql?view=sql-server-2017#logical-processing-order-of-the-select-statement – Kim May 11 '18 at 12:20