DATEDIFF Getting the previous month

I want to get the previous month relative to the current date

SELECT Datiff (mm, -1.2-2-2011)

This query gives 67 , which is the wrong value .. where did I go wrong?

+3
source share
5 answers

You can use DATEADD

eg.

SELECT DATEADD(month, -1, GETDATE())
+11
source

This is 2-2-2011not a valid date literal - you subtract 2 from 2, and then 2011 from the result - the corresponding date literals '2-2-2011'and #2-2-2011#. You can use GETDATE()to get the current date instead of relying on a literal.

And you should not use DATEDIFF- it gives you the difference between dates.

DATEADD .

:

SELECT DATEADD(mm,-1, GETDATE())

.

, DATEPART:

SELECT DATEPART(mm, SELECT DATEADD(mm,-1, GETDATE()))
+7
SELECT datepart(mm, dateadd(mm,-1,'2011/1/1') )
+4

, , SELECT MONTH(DATEADD(mm, -1, GETDATE()))

, , SELECT DATEADD(mm, -1, GETDATE())

BTW, SELECT datediff(mm,-1,2-2-2011) -1 ​​-2011, 67 (2010/30). , .

+2

DATEADD - not DATEDIFF

DATEDIFF - ​​ ....

, : '2-2-2011' 2-2-2011.

And finally: I would highly recommend using the ISO-8601 YYYYMMDD date format (here:) 20110202- it will work regardless of the language and regional settings on your SQL Server - the date format will be BREAK on many servers due to the language settings.

+1
source

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


All Articles