0

I have a members table with field DataNa type date.

I would like to make a query like:

Select DateDiff (year, datana, dateserial (year,12,31)) as years, ....
from members ... etc ...

Year is a parametric value. But the system tells me that DateSerial is not a recognized value of default function name.

I also tried to do:

Select DateDiff (year, datana, datevalue ('31/12/' + year)) as years, ....
from members ... etc ...

It says it also is not a DateValue recognized default function name

I'm using SQL Server 2008R2

2
  • 2
    What do you want to accomplish? Commented Aug 5, 2013 at 9:07
  • what format is year ? Commented Aug 5, 2013 at 9:08

2 Answers 2

2

Are you looking for something like this?

SELECT DATEDIFF(YEAR, datana, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, -1)) years
  FROM members

This part

DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, -1) 

returns last day of the current year (e.g. 2013-12-31)

Here is SQLFiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

so why would you pick the last date of last year ? It doesn't matter which date of the year you pick when using datediff(year, x,y)
1

If you want to create 31-12-YYYY out from @Year int parameter for YYYY - you can do it like this:

DATEADD(DD,-1,DATEADD(YY,@year - 1899,0))

But if you want to get difference in years between two dates - it's not important to have it 31.12, 1.1 of same year will give identical result, which you can get with:

SELECT DATEDIFF (YEAR, datana, DATEADD(YY,@year - 1900,0))

SQLFiddleDEMO

2 Comments

Tanks far all. But the DateSerial function there is SqlServer2088R2??
@Antony No. Such function does not exits. SQL Server 2012 introduced something similar with DATEFROMPARTS function, but in 2008R2 you have to use alternatives like shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.