Today I was working in SQL Server 2008. I need to use a function similar to Oracle's LAST_DAY in my scripts, but I cannot find an equivalent function, so I decided to perform a new one.
This is the script to build the function in SQL Server:
CREATE FUNCTION
[dbo].[LAST_DAY] ( @pInputDate
DATETIME )
RETURNS DATETIME
BEGIN
DECLARE @vOutputDate DATETIME
SET @vOutputDate = CAST(YEAR(@pInputDate)
AS VARCHAR(4)) + '/' +
CAST(MONTH(@pInputDate)
AS VARCHAR(2)) + '/01'
SET @vOutputDate = DATEADD(DD, -1,
DATEADD(M, 1, @vOutputDate))
RETURN @vOutputDate
END
These are the test scripts in SQL Server and Oracle:
- SELECT dbo.LAST_DAY(getdate())
- SELECT LAST_DAY(TRUNC(SYSDATE)) FROM dual
The result row in both scripts was: 2012-10-31 00:00:00.000