Pravin Satav
Pravin Satav

Reputation: 702

Update entire table with sequence number in oracle

I want to update table with sequence number, I cant create procedure or sequence object so need a update query for this. I have a table with date column, based on minimum date I need to generate a number.

Table Data:-

Date_Value
----------
5th Feb 11
2nd Jan 11
11th Jan 11

After Update :- 
SrNo     Date_Value
------------------- 
1   2nd Jan 11
2   11th Jan 11
3   5th Feb 11

Upvotes: 1

Views: 6077

Answers (2)

Nick Krasnov
Nick Krasnov

Reputation: 27261

Your example shows that you store dates as a string using custom representation - not compliant with dates format. So we need to convert your dates to date datatype to be able to order them accordingly.

SQL> create table TB_DATES
  2  (
  3    DATE_VALUE VARCHAR2(11)
  4  )
  5  /

Table created

SQL> 
SQL> insert into tb_dates(date_value)
  2    select '5th Feb 11' from dual union all
  3    select '2nd Jan 11' from dual union all
  4    select '6th Feb 11' from dual union all
  5    select '11th Jan 11' from dual
  6  ;

4 rows inserted

SQL> commit;

Commit complete

SQL> select * from tb_dates;

DATE_VALUE
-----------
5th Feb 11
2nd Jan 11
6th Feb 11
11th Jan 11

SQL> alter table tb_dates add srno number;

Table altered

QL> select * from tb_dates;

DATE_VALUE        SRNO
----------- ----------
5th Feb 11     null  
2nd Jan 11     null
6th Feb 11     null
11th Jan 11    null

SQL> merge into  tb_dates t
  2  using(
  3  select rownum rn
  4       , Date_value
  5       , rid
  6    from ( select to_date(concat(lpad(dy, 2, '0'), tr), 'dd Mon yy') dt
  7                , Date_value
  8                , rid
  9             from (select regexp_substr(substr(Date_value, 1, regexp_instr(date_value, '[[:space:]]') - 1), '[[:digit:]]+') dy
 10                        , substr(Date_value, regexp_instr(date_value, '[[:space:]]'), length(Date_value)) tr
 11                        , Date_value
 12                        , rowid rid
 13                    from tb_dates)
 14   order by 1
 15  ) ) q
 16  on (q.rid = t.rowid)
 17  when matched
 18  then update set t.srno = q.rn
 19  ;

Done

SQL> commit;

Commit complete

select * from tb_dates;

DATE_VALUE        SRNO
----------- ----------
5th Feb 11           3
2nd Jan 11           1
6th Feb 11           4
11th Jan 11          2

SQL> select * from tb_dates order by srno;

DATE_VALUE        SRNO
----------- ----------
2nd Jan 11           1
11th Jan 11          2
5th Feb 11           3
6th Feb 11           4

Upvotes: 2

user330315
user330315

Reputation:

merge into foo
using
(
   select rowid as rid,
          row_number() over (order by date_value) as seqno
   from foo
) t on (foo.rowid = t.rid)
when matched then update
   set srno = t.seqno;

SQLFiddle demo: http://sqlfiddle.com/#!4/d8cc5/2

Upvotes: 4

Related Questions