Oracle

게시글 보기
작성자 유건데이타 등록일 2015-05-20
제목 다른 테이블을 근거로 한 행 갱신 예제
==================================
다른 테이블을 근거로 한 행 갱신 예제
==================================

두 개의 Table에서 일정한 값에 근거를 해서 다른 table에 해당 값을
update하려는 경우가 있을 수 있는데, 본 샘플은 그런 경우에
활용할 수 있다.

본 예제가 적용가능한 table 구조는 다음과 같다.

create table school1
(id number(7),
name varchar2(20));

create table school2
(id number(7),
name varchar2(20));

table school1에는 school명 만이 들어가 있고, id에는 null 값이 들어가 있으며,
table school2에는 id 항목과 name 항목에 모두 특정 값이 들어가 있다. 아래의
pl/sql block을 수행하면 위와 같은 값이 table에
들어가게 될 것이다.

begin
insert into school1
values(null, 'A');

insert into school1
values(null, 'B');

insert into school1
values(null, 'B');

insert into school1
values(null, 'C');

insert into school1
values(null, 'C');

insert into school1
values(null, 'C');

insert into school1
values(null, 'D');
end;
/

begin
insert into school2
values(11, 'A');

insert into school2
values(22, 'B');

insert into school2
values(33, 'C');

insert into school2
values(44, 'D');
end;
/

그 후 아래와 같은 script를 순차적으로 수행하면 된다.

=================================================
set heading off
set feedback off

create table student_temp(update_string varchar2(80));

begin
declare
cursor student_cursor is
select id, name
from school2;

begin
for student_agg in student_cursor loop
insert into student_temp
values ('update school1 set id = '|| student_agg.id ||
'where name = '||''''||student_agg.name||''''||';');
end loop;
end;
end;
/

spool insert.sql
select * from student_temp;
spool off
drop table student_temp;
start insert.sql

출처:오라클블루틴

유건데이타
Comment
등록된 코멘트가 없습니다.