soha mahmoud
soha mahmoud

Reputation: 129

How to convert Varchar into Date

I'm trying to create a Trial Balance Report ,

and i have a field named : 'PERIOD_NAME' which stores the accounting period name,

and my question is : is it possible to convert the 'PERIOD_NAME' which is a "VARCHAR2" into "DATE" in order to sort the months ASC , To give me this Result

jan- 16
jan- 17
Feb- 16
Feb- 17

Upvotes: 0

Views: 1004

Answers (2)

Ramesh
Ramesh

Reputation: 1484

I think this is what you are after? Basically, I have used to_date to convert the period name to a date and then extracted the month and year separately to use in the sort. Hope this helps!

Data

CREATE TABLE my_table 
(
  col1 VARCHAR2(10)
)  ;
INSERT INTO my_table VALUES ('jan- 16');
INSERT INTO my_table VALUES ('jan- 17');
INSERT INTO my_table VALUES ('Feb- 16');
INSERT INTO my_table VALUES ('Feb- 17');

Solution

SELECT t.*
  FROM my_table t
 ORDER BY to_char(to_date(col1, 'mon- yy'), 'mm'),
          to_char(to_date(col1, 'mon- yy'), 'yy')

Result

COL1

jan- 16

jan- 17

Feb- 16

Feb- 17

Upvotes: 1

MT0
MT0

Reputation: 167822

Use TO_DATE( string, format_model, nls_settings ) assuming your PERIOD_NAME is like jan-17 (but it is unclear from your question what the exact format is):

SELECT TO_DATE( period_name, 'MON-YY', 'NLS_DATE_LANGUAGE=English' )
FROM   your_table;

If you want to sort by month then year then you can use EXTRACT to get the month or year and sort on that:

SELECT *
FROM   (
  SELECT TO_DATE( period_name, 'MON-YY', 'NLS_DATE_LANGUAGE=English' ) AS period_date
  FROM   your_table
)
ORDER BY EXTRACT( MONTH FROM period_date ),
         EXTRACT( YEAR FROM period_date );

Upvotes: 2

Related Questions