Link to home
Start Free TrialLog in
Avatar of James Murphy
James MurphyFlag for Australia

asked on

Stored Procedure to return difference in Months between 2 given dates.

Hi,

Thank you experts for taking a look at my question.

Basically I have the below stored proc I am trying to create, The query itself works, but for some reason it is not letting my create a stored proc.

Could you please help me work out why?

USE [cv_masterdb]
GO

/****** Object:  StoredProcedure [dbo].[spdatereturn]    Script Date: 15/02/2019 10:37:03 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[spmonthdiffnew]
	-- Add the parameters for the stored procedure here
	@monthfrom date,
	@monthto date
	
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
--DECLARE @firstDayOfListedMonth DATE = CONVERT(DATE, DATEADD(DAY, -DAY(GETDATE()) + 1, DATEADD(MONTH, - @monthsBack, GETDATE())));
--DECLARE @lastDayOfListedMonth DATE = CONVERT(DATE, DATEADD(DAY, -DAY(GETDATE()), DATEADD(MONTH, - @monthsBack + 1, GETDATE())));

select case when  DATEPART(DAY, @monthfrom) <=  DATEPART(DAY, @monthto) 
    then datediff(month, @monthfrom, @monthto)  
    else datediff(month, @monthfrom, @monthto) -1  
    END
GO

Open in new window


Basically it is a stored proc to return back the number of months in between 2 given dates.

many thanks for your help!
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of James Murphy

ASKER

doh!! always the simple things!  Your help is very much appreciated!