I'm looking to take a variable (in this case, a 4-digit year value) and pass it into a query where we're searching for rows based on a date, yet SQL Server seems to be having trouble taking that 4-digit year and putting it into the date field.
Here's an example:
DECLARE @yearstart AS VARCHAR(10) = '2022'
DECLARE @yearend AS VARCHAR(10) = '2023'
....
WHERE date_of_service BETWEEN '@yearstart-10-01' AND '@yearend-09-30'
SQL Server throws an error:
Conversion failed when converting date and/or time from character string.
Can anyone assist? Thank you in advance.
I was expecting 2022 to be passed in as plaintext to the query and just fill in the @yearstart and @yearend with 2022 and 2023 respectively.
where date_of_service between cast(@yearstart + '-10-01' as date) and cast(@yearend+'-09-30' as date)You need to use CAST()'@yearstart-10-01'isn't read as a literal string consisting of the value of the variable@yearstartand the literal value'-10-01', it's just interpreted as the literal value'@yearstart-10-01'. That literal, unsurprisingly, isn't a valid date and time value.