Search
 
SCRIPT & CODE EXAMPLE
 

SQL

How to get number of months between 2 dates sql server

CREATE FUNCTION FullMonthsSeparation 
(
    @DateA DATETIME,
    @DateB DATETIME
)
RETURNS INT
AS
BEGIN
    DECLARE @Result INT

    DECLARE @DateX DATETIME
    DECLARE @DateY DATETIME

    IF(@DateA < @DateB)
    BEGIN
        SET @DateX = @DateA
        SET @DateY = @DateB
    END
    ELSE
    BEGIN
        SET @DateX = @DateB
        SET @DateY = @DateA
    END

    SET @Result = (
                    SELECT 
                    CASE 
                        WHEN DATEPART(DAY, @DateX) > DATEPART(DAY, @DateY)
                        THEN DATEDIFF(MONTH, @DateX, @DateY) - 1
                        ELSE DATEDIFF(MONTH, @DateX, @DateY)
                    END
                    )

    RETURN @Result
END
GO

SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-15') as MonthSep -- =0
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-16') as MonthSep -- =1
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-06-16') as MonthSep -- =2
Comment

PREVIOUS NEXT
Code Example
Sql :: SQL server datetime compare 
Sql :: delete duplicate sql 
Sql :: how to find median of a column sql 
Sql :: subquery in Insert 
Sql :: my sql alter table 
Sql :: what is rownum in oracle 
Sql :: How to display top 50 rows? 
Sql :: mysql order by calculated column 
Sql :: cast float mysql 
Sql :: sequelize with mysql nodejs 
Sql :: parsing float to int in mysql 
Sql :: data structures in sql 
Sql :: SQL Working With Dates 
Sql :: how to subquey to do not load in live database in 
Csharp :: raycast from camera to mouse unity 
Csharp :: unity find objects with tag 
Csharp :: unity cycle children 
Csharp :: loop over object properties c# 
Csharp :: how to edit postprocessing through script 
Csharp :: c# sleep 1 second 
Csharp :: Getting data from selected datagridview row and which event 
Csharp :: check if process is open c# 
Csharp :: c# windows grab screenshot 
Csharp :: c# foreach enum 
Csharp :: how to get the directory of the project in c# 
Csharp :: c# random boolean 
Csharp :: bold caption latex 
Csharp :: convert array from string to int c# 
Csharp :: how to change scenes with button press in unity c# 
Csharp :: unity disable parent gameobject 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =