问题
I have used the LAST_DAY() function in Oracle like this:
Last_Day( to_date( '$pay_first_day' , 'YYYY-mm-dd') )
What do i have to do in SQL server 2008 R2 database to achieve the same result?
回答1:
Try this one -
DECLARE @Date DATETIME
SELECT @Date = GETDATE()
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date) + 1, 0) - 1
回答2:
-- Wrapping the answer in a function for seamless transition.
CREATE FUNCTION [dbo].[LAST_DAY]
(
@inDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MONTH, DATEDIFF(MONTH, 0, @inDate) + 1, 0) - 1
END
-- TO TEST: SELECT dbo.LAST_DAY(getDate()) as LastDayOfThisMonth
-- note: Please mark as answer if this helps you better then the one before.
回答3:
SQL Server 2012 introduces a new date function called EOMONTH which returns the last day of the month that contains the specified date, with an optional offset.
EOMONTH ( <start_date> [, <month_to_add> ] )
For instance
select EOMONTH('01/07/2018')Would return
2018-01-31
回答4:
Could you please try this, it should work as expected :
SELECT DATEADD (DAY, -1, DATEADD (MONTH, DATEDIFF (MONTH, 0, '$pay_first_day') + 1, 0))
It would return the last day equivalent of the given date in this format : '2013-02-28 00:00:00.000' if your $pay_first_day is in February, and it would return '2013-04-30 00:00:00.000' if your $pay_first_day is in April.
回答5:
Here are two UDF for begin and end of month.
CREATE FUNCTION dbo.End_of_month (@Date datetime)
RETURNS datetime AS
BEGIN
DECLARE @ret datetime
SET @Ret=DATEADD(DAY,-DAY(@Date)+1,@Date);
SET @Ret=DATEADD(Month,1,@Ret);
SET @Ret=DATEADD(Day,-1,@Ret);
RETURN(@Ret)
END
CREATE FUNCTION dbo.Begin_of_month (@Date datetime)
RETURNS datetime AS
BEGIN
DECLARE @ret datetime
SET @Ret=DATEADD(DAY,-DAY(@Date)+1,@Date);
RETURN(@Ret)
END
来源:https://stackoverflow.com/questions/16277504/what-is-the-equivalent-of-oracles-last-day-function-in-sql-server-2008