0

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.

2
  • 1
    where date_of_service between cast(@yearstart + '-10-01' as date) and cast(@yearend+'-09-30' as date) You need to use CAST() Commented Jan 31, 2023 at 14:58
  • T-SQL is a compiled language and doesn't support variable replacement like a scripting language. '@yearstart-10-01' isn't read as a literal string consisting of the value of the variable @yearstart and 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. Commented Jan 31, 2023 at 15:12

1 Answer 1

4

Use numeric parameters and DATEFROMPARTS instead :

DECLARE @yearstart int = 2022
DECLARE @yearend int= 2023

....

where date_of_service 
between DATEFROMPARTS(@yearstart,10,1) and DATEFROMPARTS(@yearend,9,30)

Parameters aren't format placeholders. Their values never become part of the query itself. The server compiles the SQL query into a reusable execution plan with parameters and only then executes it passing the parameter values to it. Next time the same query is encountered the server reuses the already compiled execution plan.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.