[SQL] select 한 결과로 update 처리, SQL한문장,

How to UPDATE from SELECT in SQL Server

Under most circumstances, SQL updates are performed using direct references to a particular table (UPDATE books SET books.title = 'The Hobbit' WHERE books.id = 1). Yet, on occasion, it may prove beneficial to alter the contents of a table indirectly, by using a subset of data obtained from secondary query statement.

Performing an UPDATE using a secondary SELECT statement can be accomplished in one of two ways, primarily depending upon which version of SQL Server you are using. We’ll briefly explore both options so you can find what works best for you.

Using INNER JOINS

For all SQL Server installations, the most basic method of performing this action is to use an INNER JOIN, whereby values in the columns of two different tables are compared to one another.

UPDATE
  books
SET
  books.primary_author = authors.name
FROM
  books
INNER JOIN
  authors
ON
  books.author_id = authors.id
WHERE
  books.title = 'The Hobbit'

In the above example, we’re UPDATING the books.primary_author field to match the authors.name for ‘The Hobbit’ by JOINING both tables in the query to their respective, matching values of authors.id and books.author_id.

Using MERGE to UPDATE and INSERT Simultaneously

For SQL Server 2008 and newer, Microsoft introduced the exceptionally useful MERGE operation which is similar to the above INNER JOIN method, but MERGE attempts to perform both an UPDATE and an INSERT command together. This effectively synchronizes the two tables based on the query performed, updating and inserting records as necessary for the two to match.

MERGE INTO
  books
USING
  authors
ON
  books.author_id = authors.id
WHEN MATCHED THEN
  UPDATE SET
    books.primary_author = authors.name
WHEN NOT MATCHED THEN
  INSERT
    (books.author_id, books.primary_author)
  VALUES
    (authors.id, authors.name)

The full query when using MERGE is certainly a bit more complex then that of a basic INNER JOIN, but once you grasp how the operation functions, you’ll quickly understand how powerful this capability can truly be.

The first few lines are rather self-explanatory:

MERGE INTO
  books
USING
  authors
ON
  books.author_id = authors.id

We want to MERGE INTO (UPDATE/INSERT) the books table by using the secondary authors table, and we’re matching the two based on the same books.author_id = authors.id comparison.

Where the MERGE command differs is in the branching logic that follows.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

WHEN MATCHED THEN
  UPDATE SET
    books.primary_author = authors.name

Here we’re asking SQL to perform an action only when records MATCHED – when an existing record is found. In that case, we perform a standard UPDATE just as we did before, setting the books.primary_author field to equal the authors.name field.

Finally, if the query discovers a matching comparative record that doesn’t exist, we instead perform an INSERT.

WHEN NOT MATCHED THEN
  INSERT
    (books.author_id, books.primary_author)
  VALUES
    (authors.id, authors.name)

Here we’re simply asking SQL to INSERT a new record into the books table and passing along the values for the author_id and primary_author fields, grabbed from the associated authors table record.

The end result of our MERGE statement is that for every author in the authors table, we verify whether a corresponding book exists in books. If a record is found, we ensure books.primary_author is set using UPDATE, and where no match is found, we add a new record to books.

With that, you should have a solid understanding of two different methods that can be used to UPDATE records in SQL by using secondary, comparative SELECT statements.

 

[출처] https://chartio.com/resources/tutorials/how-to-update-from-select-in-sql-server/

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86979
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 79241
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95978
51 오라클 Select 해서 Update 하기 졸리운_곰 2018.01.22 1218
50 디폴트 세팅의 함정과 오라클 파라미터 file 졸리운_곰 2017.07.15 1690
49 그림으로 배우는 ‘공정쿼리와 인덱스 생성도’ file 졸리운_곰 2017.07.15 1549
48 오라클 랜덤 함수와 사용자 정의 함수 file 졸리운_곰 2017.07.15 3236
47 개발자들이 자주 접하는 오라클 에러 메세지 file 졸리운_곰 2017.07.15 4014
46 오라클 DICTIONARY를 활용한 DB툴 프로그램 ‘FreeSQL’ file 졸리운_곰 2017.07.15 1194
45 알면 유용한 오라클 기능들 file 졸리운_곰 2017.07.15 1574
44 알면 유용한 오라클 기능 ‘GATHER_PLAN_STATISTICS’ file 졸리운_곰 2017.07.15 1864
43 개발자들의 영원한 숙제 ‘NULL 이야기’ file 졸리운_곰 2017.07.15 4350
42 오라클 플랜을 보는 법 file 졸리운_곰 2017.07.15 1893
41 반드시 알아야 하는 오라클 힌트절 7가지 file 졸리운_곰 2017.07.15 1568
40 그림으로 배우는 ‘오라클 조인의 방식’ 이야기 file 졸리운_곰 2017.07.15 1925
39 오라클 옵티마이저 ‘CBO와 RBO’ 이해하기 file 졸리운_곰 2017.07.09 1807
38 만능 쿼리와 한 방 쿼리 file 졸리운_곰 2017.07.09 1522
37 퀴리 최적화 및 튜닝을 위한 오라클 공정쿼리 작성법 file 졸리운_곰 2017.07.09 1597
36 누구도 알려주지 않았던 ‘오라클 쿼리 작성의 비법’ file 졸리운_곰 2017.07.09 1315
35 누구도 알려주지 않았던 ‘오라클 인덱스 생성도’의 비밀 file 졸리운_곰 2017.07.09 1601
34 oracle 패스워드 유효기간 만료 복구 졸리운_곰 2017.05.06 1664
33 Oracle Instant Client 이용하여 Toad 사용하기 file 졸리운_곰 2017.05.06 1227
32 [Oracle] 1. 각 테이블 코멘트 조회하기 / 2. 테이블의 컬럼정보 조회하기 졸리운_곰 2017.04.17 1192
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED