[작업로그] DB Data Migration

DECEMBER 08, 2020

#. 동일한 구조의 테이블 또는 다른 구조의 테이블에 select 한 내용을 insert 하는 방법

1. select 한 내용의 전체 컬럼 insert

  • select 테이블과 insert할 테이블의 구조가 일치해야 한다.

    INSERT INTO [table] SELECT * FROM [table] WHERE [조건];

2. 원하는 컬럼만 select 해서 insert

  • 특정 컬럼을 직접 선택해서 insert하는 방법

    INSERT INTO [table] (column1, colum2, colum3) 
    SELECT column1, colum2, colum3 FROM [table] WHERE [조건];


#. 조건에 따라 값을 지정해주는 Case 문

1. 여러 조건 비교

//Case
//    WHEN 조건1 THEN 출력1 
//    WHEN 조건2 THEN 출력2
//    ELSE 출력3
//END

SELECT 
    case 
        when sal >=0 and sal <= 1000 then 'E'
        when sal > 1000 and sal <= 2000 then 'D'
        when sal > 2000 and sal <= 3000 then 'C'
        when sal > 3000 and sal <= 4000 then 'B'
        when sal > 4000 and sal <= 5000 then 'A'
    end as sal_rank 
FROM table_name;

2. 특정 컬럼의 값으로 비교

//Case 컬럼명
//    WHEN 값1 THEN 출력1 
//    WHEN 값2 THEN 출력2
//    ELSE 출력3
//END

SELECT 
    case department
        when 'back-end' then 'BE'
        when 'front-end' then 'FE'
        when 'user-interface' then 'UI'
        else 'ETC'
    end as department_alias 
FROM table_name;


#. 작업내용

변경사항이 없는 테이블의 경우

insert into autocrypt_v2g_prod.table_name 
select * from autocrypt_v2g_1208.table_name order by created
;

CA_CERT 테이블 Migration

  • 컬럼에 변경사항이 있는 경우, 각 컬럼을 명시
  • case 문으로 타입이 변경 된 컬럼 해결
  • bulk insert 가 되므로 한 row가 insert 될때마다 commit이 되지 않으므로 자신 테이블의 id를 참조하는 issuer_id는 NULL로 insert/commit 후 update문 실행
insert into autocrypt_v2g_prod.ca_cert
	(created, created_by, updated, updated_by,
	actor, cert, not_after, not_before, serial, subject_dn, ak_id, sk_id, path_length, provider_id, 
	
	wca_id,
	
	valid,
	last_issued,
	
	issuer_id )
select
	s.created, '' as created_by, s.updated, '' as updated_by,
	s.actor, s.cert, s.not_after, s.not_before, s.serial, s.subject_dn, s.ak_id, s.sk_id, s.path_length, s.provider_id,
	
    s.id as wca_id,
	
	case s.status when 'VALID' then true else false end as valid ,
	case s.last_issued when '1' then true else false end as last_issued,	
	
    NULL as issuer_id
from autocrypt_v2g_1208.ca_cert s order by s.created
;

update 
autocrypt_v2g_prod.ca_cert target,
(select
	s.id as id,
	(select t.id from autocrypt_v2g_prod.ca_cert t where t.wca_id = s.issuer_id) as issuer_id
from autocrypt_v2g_1208.ca_cert s order by s.created) result
set target.issuer_id = result.issuer_id
where target.wca_id = result.id
;

값이 잘못 들어 갔을 경우 id의 sequence 까지 (autoincrement) 초기화 하기 위해 truncate문 사용

truncate autocrypt_v2g_prod.tableName;

작업 기록 블로그