블로그 이미지
LifeisSimple

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Notice

2011. 8. 10. 12:22 Brain Trainning/DataBase

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

posted by LifeisSimple