oracle update 几种方法容易理解和使用的更新命令

来源:互联网 发布:上古世纪saber捏脸数据 编辑:程序博客网 时间:2024/05/02 15:32

      习惯了SQL server的update写法,感觉如此优雅和简便,近期要用oracle,是如此的不方便。经过努力发现三种写法还是很不错的,真不愧是大佬。

    例子:两个表,结构相同,都有编号和名称。

          create table tb1(
              id int not null primary key,
              name varchar(100)
          );
          create table tb2(
              id int not null primary key,
              name varchar(100)
          );

插入测试数据:
insert into tb1
 select 1,'武汉' from dual union all select 2, '郑州' from dual
  union all select 3, '上海' from dual union all select 4, '广州' from dual

insert into tb2
 select 1,'' from dual union all select 2, '' from dual
  union all select 3, '' from dual union all select 4, '' from dual union all select 5, '' from dual

第一个表数据  select * from tb1

编号  名称

1 武汉
2 郑州
3 上海
4 广州

第二个表数据  select * from tb2

编号  名称

1
2
3
4
5


现在开始更新tb2中的name字段。

SQLserver的写法 update a set a.name = b.name from tb2 a, tb1 b where a.id = b.id

oracle的写法:

写法一:update (select a.id, a.name namea, b.name nameb from tb1 a, tb2 b where a.id = b.id) t
set t.nameb = t.namea

写法二:update tb2 b set name = (select a.name from tb1 a where a.id = b.id)

写法三:merge into tb2 b
using(select a.id, a.name namea from tb1 a )t
on (b.id = t.id)
when matched then update set b.name = t.namea
二和三在更新时都没问题,能成功。但是写法一经常会报错误“无法修改与非键值保存表对应的列”。

正在分析产生的原因及正确的写法。

0 0
原创粉丝点击