Building dates in TSQL

Trying to build a date:

CAST('9/1/' + YEAR(GETDATE()) AS Datetime) AS test2

But does it not work?

Would you like to get something like "9/1/2010"?

+3
source share
4 answers

you cannot concatenate string '9/1'with number: YEAR(GETDATE())so try the following:

select CAST ('9/1 /' + CONVERT (varchar (4), YEAR (GETDATE ())) AS Datetime) AS test2

+4
source
SELECT 
 CAST( '9/1/' + CAST( YEAR(GETDATE()) AS VARCHAR ) AS Datetime) AS test2 

You need to pass YEAR (integer) to VARCHAR before you can add it.

+1
source

try the following:

Select DateAdd(month, 
           dateDiff(month, 0, getdate()) + 9 - MONTH(getdate()),
           0)
+1
source

You can use the string format YYYYMMDD.

0
source

Source: https://habr.com/ru/post/1731090/


All Articles