블로그 이미지
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 31

Notice

'T-SQL'에 해당되는 글 2

  1. 2011.08.10 [T-SQL] MERGE 문을 사용한 IUD
  2. 2010.07.14 SQL Server 2008 T-SQL Enhancements
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
2010. 7. 14. 14:03 Brain Trainning/DataBase

'Brain Trainning > DataBase' 카테고리의 다른 글

SQL Server 2005 DBCC Command Quick Reference  (0) 2010.07.16
Top 10 SQL Server 2008 Features for ISV Applications  (1) 2010.07.14
SQL Patch 정보  (0) 2010.06.18
MSSql 2005 SP 적용  (0) 2010.06.18
DBA 일간 체크리스트  (0) 2010.06.03
posted by LifeisSimple
prev 1 next