SQL

[MSSQL]DML 트리거 만들기

하루종일v 2017. 12. 14. 15:54

DML 트리거 만들기Create DML Triggers

이 항목에서는 Transact-SQLTransact-SQLSQL Server Management StudioSQL Server Management Studio CREATE TRIGGER 문을 사용하여 Transact-SQLTransact-SQL DML 트리거를 만드는 방법에 대해 설명합니다.This topic describes how to create a Transact-SQLTransact-SQL DML trigger by using SQL Server Management StudioSQL Server Management Studio and by using the Transact-SQLTransact-SQL CREATE TRIGGER statement.

시작하기 전 주의 사항 Before You Begin

제한 사항Limitations and Restrictions

DML 트리거 생성과 관련한 제한 사항 목록은 CREATE TRIGGER(Transact-SQL)를 참조하세요.For a list of limitations and restrictions related to creating DML triggers, see CREATE TRIGGER (Transact-SQL).

사용 권한 Permissions

트리거를 생성할 테이블 또는 뷰에 대한 ALTER 권한이 필요합니다.Requires ALTER permission on the table or view on which the trigger is being created.

DML 트리거를 만드는 방법 How to Create a DML Trigger

다음 중 하나를 사용할 수 있습니다.You can use one of the following:

SQL Server Management Studio 사용 Using SQL Server Management Studio

  1. 개체 탐색기에서 데이터베이스 엔진Database Engine 의 인스턴스에 연결한 다음 해당 인스턴스를 확장합니다.In Object Explorer, connect to an instance of 데이터베이스 엔진Database Engine and then expand that instance.
  2. 데이터베이스, AdventureWorks2012AdventureWorks2012 데이터베이스, 테이블Purchasing.PurchaseOrderHeader테이블을 차례로 확장합니다.Expand Databases, expand the AdventureWorks2012AdventureWorks2012 database, expand Tables and then expand the table Purchasing.PurchaseOrderHeader.
  3. 트리거를 마우스 오른쪽 단추로 클릭한 다음 새 트리거를 선택합니다.Right-click Triggers, and then select New Trigger.
  4. 쿼리 메뉴에서 템플릿 매개 변수 값 지정을 클릭합니다.On the Query menu, click Specify Values for Template Parameters. 또는 (Ctrl-Shift-M)을 눌러 템플릿 매개 변수 값 지정 대화 상자를 열 수 있습니다.Alternatively, you can press (Ctrl-Shift-M) to open the Specify Values for Template Parameters dialog box.
  5. 템플릿 매개 변수 값 지정 대화 상자에 표시된 매개 변수에 대해 다음 값을 입력합니다.In the Specify Values for Template Parameters dialog box, enter the following values for the parameters shown.
    매개 변수Parameter Value
    작성자Author Your nameYour name
    만든 날짜Create Date Today's dateToday's date
    설명Description 공급업체의 새 PO를 삽입하기 전에 공급업체의 신용 등급을 확인합니다.Checks the vendor credit rating before allowing a new purchase order with the vendor to be inserted.
    Schema_NameSchema_Name PurchasingPurchasing
    Trigger_NameTrigger_Name NewPODetail2NewPODetail2
    Table_NameTable_Name PurchaseOrderDetailPurchaseOrderDetail
    Data_Modification_StatementData_Modification_Statement 목록에서 UPDATE 및 DELETE를 제거합니다.Remove UPDATE and DELETE from the list.
  6. 확인을 클릭합니다.Click OK.
  7. 쿼리 편집기에서 -- Insert statements for trigger here 주석을 다음 문으로 바꿉니다.In the Query Editor, replace the comment -- Insert statements for trigger here with the following statement:
    IF @@ROWCOUNT = 1   BEGIN      UPDATE Purchasing.PurchaseOrderHeader      SET SubTotal = SubTotal + LineTotal      FROM inserted      WHERE PurchaseOrderHeader.PurchaseOrderID = inserted.PurchaseOrderID    END   ELSE   BEGIN         UPDATE Purchasing.PurchaseOrderHeader      SET SubTotal = SubTotal +          (SELECT SUM(LineTotal)         FROM inserted         WHERE PurchaseOrderHeader.PurchaseOrderID          = inserted.PurchaseOrderID)      WHERE PurchaseOrderHeader.PurchaseOrderID IN         (SELECT PurchaseOrderID FROM inserted)   END;   
  8. SQL
  9. 구문이 올바른지 확인하려면 쿼리 메뉴에서 구문 분석을 클릭합니다.To verify the syntax is valid, on the Query menu, click Parse. 오류 메시지가 반환되면 필요에 따라 위의 정보와 문을 비교하여 수정하고 이 단계를 반복합니다.If an error message is returned, compare the statement with the information above and correct as needed and repeat this step.
  10. DML 트리거를 만들려면 쿼리 메뉴에서 실행을 클릭합니다.To create the DML trigger, from the Query menu, click Execute. DML 트리거가 데이터베이스 개체로 만들어집니다.The DML trigger is created as an object in the database.
  11. 개체 탐색기에 나열된 DML 트리거를 보려면 트리거 를 마우스 오른쪽 단추로 클릭하고 새로 고침을 선택합니다.To see the DML trigger listed in Object Explorer, right-click Triggers and select Refresh.
  12. 시작하기 전 주의 사항Before You Begin

Transact-SQL 사용 Using Transact-SQL

  1. 개체 탐색기에서 데이터베이스 엔진Database Engine 의 인스턴스에 연결한 다음 해당 인스턴스를 확장합니다.In Object Explorer, connect to an instance of 데이터베이스 엔진Database Engine and then expand that instance.
  2. 메뉴에서 파일 메뉴에서 새 쿼리를 클릭합니다.From the File menu, click New Query.
  3. 다음 예를 복사하여 쿼리 창에 붙여 넣고 실행을 클릭합니다.Copy and paste the following example into the query window and click Execute. 이 예에서는 위와 동일한 저장된 DML 트리거를 만듭니다.This example creates the same stored DML trigger as above.
    -- Trigger valid for multirow and single row inserts   -- and optimal for single row inserts.   USE AdventureWorks2012;   GO   CREATE TRIGGER NewPODetail3   ON Purchasing.PurchaseOrderDetail   FOR INSERT AS   IF @@ROWCOUNT = 1   BEGIN      UPDATE Purchasing.PurchaseOrderHeader      SET SubTotal = SubTotal + LineTotal      FROM inserted      WHERE PurchaseOrderHeader.PurchaseOrderID = inserted.PurchaseOrderID    END   ELSE   BEGIN         UPDATE Purchasing.PurchaseOrderHeader      SET SubTotal = SubTotal +          (SELECT SUM(LineTotal)         FROM inserted         WHERE PurchaseOrderHeader.PurchaseOrderID          = inserted.PurchaseOrderID)      WHERE PurchaseOrderHeader.PurchaseOrderID IN         (SELECT PurchaseOrderID FROM inserted)   END;   
  4. SQL

 

반응형