Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

DateTime --

$
0
0
Hi All ,

I wrote a function , which takes datetime as a input and returns last day(date) of the month.

Function Code:
Create FUNCTION FX_LDAYOFMONTH(@DATETIME DATETIME)
RETURNS DATETIME
AS
BEGIN
IF ISDATE(@DATETIME) = 1 
BEGIN
SET @DATETIME = DATEADD(DAY,-1,
(DATEADD(MONTH,1,
DATEADD(DAY,-(DAY(@DATETIME)-1),@DATETIME))))
END
ELSE 

SET @DATETIME = 'ENTER VALID DATE FORMAT'

RETURN @DATETIME
END

After That : SELECT dbo.FX_LDAYOFMONTH(1984-09-22)
-- Result : 1905-05-31 00:00:00.000

But it should give 1984-09-30 --

I did same code with select statement as below 
DECLARE @DATETIME VARCHAR(30) = '1984-09-22'
SELECT DATEADD(DAY,-1,
(DATEADD(MONTH,1,
DATEADD(DAY,-(DAY(@DATETIME)-1),@DATETIME))))

-- Result --1984-09-30 00:00:00.000. It is giving the correct result.

Please help me to find out the bug in the code.

Thanks..!!
Mahesh

 


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>