Home > SQL Server > Get Difference between two Dates using SQL Server

Get Difference between two Dates using SQL Server


Hi all,

try this example to Create Stored Procedure to Get Difference between two Dates in Years , Months and Days

So try this SQL Query to Create Stored Procedure which Take two Parameters (FromDate and ToDate)

create proc CalculateDifference
(
@FromDate datetime,
@ToDate datetime
)
as
begin 
DECLARE @thisYear datetime
DECLARE @years int, @months int, @days int  
SELECT @thisYear = DATEADD(year, DATEDIFF(year, @FromDate, @ToDate), @FromDate) 
SELECT @years = DATEDIFF(year, @FromDate, @ToDate) - (CASE WHEN @thisYear > @ToDate THEN 1 ELSE 0 END) 
SELECT @months = MONTH(@ToDate - @thisYear) - 1 
SELECT @days = DAY(@ToDate - @thisYear) - 1 
SELECT @years as years, @months as months, @days as days
end

and To execute this Stored Procedure write this Query

exec CalculateDifference '01/21/1984','03/24/2011'

Hope this helps,

Good Luck

Advertisements
Categories: SQL Server
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: