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

      習慣了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
二和三在更新時都沒問題,能成功。

但是寫法一經常會報錯誤“無法修改與非鍵值保存表對應的列”,要求B表必須有主鍵且返回唯一行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章