1

我想用序列号更新表,我不能创建过程或序列对象,所以需要一个更新查询。我有一个带有日期列的表,根据我需要生成一个数字的最小日期。

表数据:-

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
4

2 回答 2

4
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 演示:http ://sqlfiddle.com/#!4/d8cc5/2

于 2012-10-26T11:02:32.773 回答
2

您的示例显示您使用自定义表示将日期存储为字符串 - 不符合日期格式。因此,我们需要将您的日期转换为日期数据类型,以便能够相应地对它们进行排序。

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
于 2012-10-26T11:36:46.510 回答