Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
i want to divide months and years in to two seperate colums.


TranDate
31/01/2013
31/02/2013
31/03/2013

i want to creat sql query which will seperate month and year from one column and put months into one column and year in to other column.
so in total there will be three column.

eg:

TranDate month year
31/12/2013 12 2012
31/01/2013 01 2013
31/02/2013 02 2013
Posted

Hi Try This


SQL
SELECT TranDate, MONTH(TranDate) 'TranMonth', YEAR(TranDate) 'TranYear' 
FROM table_name


Check all System Date Functions

Date and Time Functions (Transact-SQL)[^]

Regards,
GVPrabu
 
Share this answer
 
v2
SQL
SELECT TranDate, MONTH(TranDate) as 'month', YEAR(TranDate) as 'year' FROM TableName


OP has come back with an error that indicates his TranDate column is not a datetime so he can either convert it to a datetime

SQL
SELECT TranDate, MONTH(convert(datetime, TranDate, 103)) as 'month', YEAR(convert(datetime, TranDate, 103)) as 'year' FROM TableName

or use SUBSTRING to get the parts he wants

SELECT TranDate, SUBSTRING(TranDate, 4,2), SUBSTRING(TranDate, 7,4)


Each have their pros and cons, depending on how sure you are that the data on thr database is correct
 
Share this answer
 
v3
Comments
ByakuyaKuchiki 22-Feb-13 7:23am    
i am getting "Conversion failed when converting date and/or time from character string" error.
i want to convert my date field in to date and time, its currently varchar(50) using sql Query.
Chris Reynolds (UK) 22-Feb-13 7:46am    
I have updated the solution for you.
ByakuyaKuchiki 25-Feb-13 1:42am    
Thank you its working.
1. Change your Datatype by following statement

ALTER TABLE Table_Name ALTER COLUMN TranDate DateTime


2. USE SubString(Expression, Start, End)

SELECT TranDate, substring(TranDate,4,5) AS Month, substring(TranDate,7,10) AS Year
FROM Table_Name
 
Share this answer
 
v2

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