ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • OUTPUT (데이터 변경 분 저장하기)
    SQLServer 2020. 1. 13. 15:03

    테스트 환경

     - OS : Windows 2008 R2 DataCenter

     - DBMS : SQL Server 2012 Enterprise Edition + SP4

     - 참고문서 : https://docs.microsoft.com/ko-kr/previous-versions/sql/sql-server-2012/ms177564(v=sql.110)

     

    내용

     

    개요

     

    INSERT, UPDATE, DELETE, MERGE 문의 영향을 받는 각행의 전후 데이터를 별로 관리 할 수 있습니다.

    과거 트리거의 inserted, deleted 와 유사한 방식입니다.

    예를들어

    INSERT 문의 inserted 는 삽입되는 데이터이며,

    DELETE 문의 deleted 는 삭제된 데이터이며,

    UPDATE 문의 inserted 는 변경 후 데이터이며, deleted 는 변경 후 데이터입니다.

     

    1건의 변경내역 뿐 아니라, 복수건의 변경내역도 확인 가능합니다.

     

    예제

    -- 간단한 INSERT 문과 함께 OUTPUT INTO 사용

    USE AdventureWorks2012;
    GO

    DECLARE @MyTableVar table( NewScrapReasonID smallint,
    Name varchar(50),
    ModifiedDate datetime);
    INSERT Production.ScrapReason
    OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
    INTO @MyTableVar
    VALUES (N'Operator error', GETDATE());


    --Display the result set of the table variable.
    SELECT NewScrapReasonID, Name, ModifiedDate FROM @MyTableVar;

    --Display the result set of the table.
    SELECT ScrapReasonID, Name, ModifiedDate
    FROM Production.ScrapReason;
    GO

     

    -- UPDATE 문과 함께 OUTPUT INTO 사용

    USE AdventureWorks2012;
    GO

    DECLARE @MyTableVar table(
    EmpID int NOT NULL,
    OldVacationHours int,
    NewVacationHours int,
    ModifiedDate datetime);

    UPDATE TOP (10) HumanResources.Employee
    SET VacationHours = VacationHours * 1.25,
    ModifiedDate = GETDATE()
    OUTPUT inserted.BusinessEntityID,
    deleted.VacationHours,
    inserted.VacationHours,
    inserted.ModifiedDate
    INTO @MyTableVar;

    --Display the result set of the table variable.
    SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate
    FROM @MyTableVar;
    GO

    --Display the result set of the table.
    SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate
    FROM HumanResources.Employee;
    GO

    'SQLServer' 카테고리의 다른 글

    SQL Server 2012 에서 지원하는 기본 함수  (0) 2020.01.13
    OFFSET 및 FETCH  (0) 2020.01.13
    MERGE문  (0) 2020.01.13
    CTE (공통 테이블 식)  (0) 2020.01.13
    오브젝트 사용공간 확인 (sp_spaceused)  (0) 2020.01.10
Designed by Tistory.