Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a scalar-valued function, i need the function to return the year.. but it doesn't work. My code looks like this:

SQL
ALTER FUNCTION [Anketa_MPI].[GetYear]
(
    @Date datetime
)
RETURNS datetime
AS
BEGIN

  RETURN YEAR(@Date)

END



When i execute the function select [Anketa_MPI].[GetYear](getdate()) as YearToday

I get this output 1905-07-08 00:00:00.000


But when i just query select YEAR(getdate()) it works correctly .. what is it wronkg with my code?
Posted

If you are only looking for the year to be returned.
Change your return type to integer.

... hope it helps.


SQL
ALTER FUNCTION [Anketa_MPI].[GetYear]
(
    @Date datetime
)
RETURNS INT
AS
BEGIN
 
  RETURN YEAR(@Date)
END
 
Share this answer
 
v2
Comments
King Fisher 24-Nov-14 6:01am    
my 5 :)
hypermellow 24-Nov-14 6:41am    
Thanks :)
Voley 24-Nov-14 6:50am    
Thanks :) (otherwise Helpful)
Solution 1 is good ,you have return as Int

Quote:
when i just query select YEAR(getdate()) it works correctly .. what is it wronkg with my code?


Because Year is the Built-in Functions in sql to select the Year part of Datetime

http://msdn.microsoft.com/en-IN/library/ms186313.aspx[^]
 
Share this answer
 
v3
Comments
hypermellow 24-Nov-14 6:42am    
... and my 5 for the explanation which I omitted from my solution. :)
King Fisher 24-Nov-14 7:27am    
Thank you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900