MSSQL T-SQL 의 새로운 기능인 Merge에 대한 간단한
사용예입니다.
알고만 있다가 사용하는건 이번이 처음이군요...
테스트 코드는 다음과 같습니다.
간단히 타겟과 타겟에 Merge를
할 Source 테이블을 생성합니다.
create table TSource (songID int not null, songType char(1) not null, lstCnts int default (0))
create table TTarget (songID int not null, songType char(1) not null, lstCnts int default (0))
insert into TTarget (songID, songType, lstCnts) values (1, 'A', 20)
insert into TTarget (songID, songType, lstCnts) values (1, 'C', 22)
insert into TTarget (songID, songType, lstCnts) values (1, 'B', 11)
insert into TTarget (songID, songType, lstCnts) values (2, 'A', 20)
insert into TTarget (songID, songType, lstCnts) values (2, 'C', 22)
insert into TSource (songID, songType, lstCnts) values (1, 'A', 20)
insert into TSource (songID, songType, lstCnts) values (2, 'B', 21)
insert into TSource (songID, songType, lstCnts) values (1, 'C', 15)
데이터를 입력합니다.
merge TTarget
as T
using TSource as S on (T.songID = S.songID and T.songType = S.songType)
when not matched by target
then Insert (songID, songType, lstCnts) values (S.songID, S.songType, s.lstCnts)
when matched
then Update set T.lstCnts = isnull(T.lstCnts, 0) + isnull(S.lstCnts, 0)
output $action
;
select * from TTarget order by songID, songType
결과는 아래와 같습니다.
1 A 40
1 B 11
1 C 37
2 A 20
2 B 21
2 C 22
'Brain Trainning > DataBase' 카테고리의 다른 글
[SSIS] Integration Services Data Types 참고자료.. (0) | 2011.08.13 |
---|---|
[MSSQL] SSIS Package Configuration File 설정방법 (0) | 2011.08.12 |
[MSSQL] Transactional Replication - Handling Data Consistency Errors (펌) (0) | 2011.08.09 |
[MSSQL] T-SQL 문자열 Split 예제 (0) | 2011.08.09 |
[MSSQL] Replication Row 에러 대처법 (0) | 2011.08.05 |