Reputation:
I want to write a script that will insert the month and date consistently but use the current year. I have tried this:
DECLARE @startDateVar DATETIME = '31/7/'+year(getdate())
But it doesn't work with error
Conversion failed when converting the varchar value '31/7/' to data type int.
Ideally I can capture the current year and pass it to the constructor for the DATETIME
variable. What is the best way to do this?
Upvotes: 1
Views: 585
Reputation: 26450
Use the proper date-format YYYY-MM-DD
to avoid ambiguity, and use CONCAT()
to join the strings together (as YEAR()
returns an int, you need to either use CONCAT()
to concatenate it, or cast it to a string before you can add it to your other string).
DECLARE @startDateVar DATETIME = CONCAT(YEAR(GETDATE()), '-07-31')
Upvotes: 1
Reputation: 95561
You could use DATEFROMPARTS
:
SELECT DATEFROMPARTS(YEAR(GETDATE()),7,31);
Upvotes: 1
Reputation: 13237
SELECT GETDATE()
will return as 2019-05-16 08:35:03.257
, so if you are assign the value in yyyy-mm-dd
format it will accept.
So using CONCAT()
with the yyyy-mm-dd
format helps:
DECLARE @startDateVar DATETIME = CONCAT(year(getdate()), '-07-31')
SELECT @startDateVar
the output will be 2019-07-31 00:00:00.000
Upvotes: 0