Click here to Skip to main content
15,902,114 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friend i have a column in my table which store date in dd/MM/yyyy formate......in varchar
i want to extract only Year from this in yyyy formate how can i do ....give me query for this.
Posted

I would firast convert the string (the varchar) to Datetime (Google is your friend[^]) and then extract the YEAR part[^].
 
Share this answer
 
Comments
Peter Leow 17-Dec-13 4:01am    
Good advice. +5.
Maciej Los 17-Dec-13 4:04am    
+5!
First things first: never store dates as string values - it makes live a lot, lot more complex than it needs to be, because different systems use different string representations of dates:
MM/dd/yyyy
MM/dd/yy
dd/MM/yyyy
dd/MM/yy
yyyy-MM-dd
yyMMdd
dd MMM yyyy
Among others. If you store date values as DateTime columns, then your database is always using a valid value that is a genuine date, rather than a "might be a date, might not, might be '34th Feb 2213', might be 'the date'". This complicates your software to a stupid degree!

But...if you can't get round it:
SQL
SELECT SUBSTRING(MyDateColumnAsAString, 7, 4) FROM MyTable
But don't be surprised when it crashes in production!
 
Share this answer
 
Comments
Peter Leow 17-Dec-13 4:00am    
Good advice.+5.
Maciej Los 17-Dec-13 4:07am    
+5
Another way to accede to your request is:

SELECT RIGHT(thedateinstringcolumnname, 4) from tablename


But do take note of advice from OriginalGriff and CPallini.
 
Share this answer
 
v2
Comments
Maciej Los 17-Dec-13 4:07am    
+5!
All above solutions are good.
I would suggest to use CONVERT[^] with YEAR[^] function:
SQL
SET DATEFORMAT dmy;
SELECT YEAR(CONVERT(DATETIME,'12/02/2013')) AS MyYear
 
Share this answer
 
Comments
Peter Leow 17-Dec-13 4:13am    
Good suggestion too. +5.
Maciej Los 17-Dec-13 4:14am    
Thank you, Peter ;)

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