システム開発 備忘録









SQLサーバー トリガ関連

*** *** *** *** ***


トリガで更新日付をセットする
M_EMPLOYEEというテーブルのUPDATE_TIMEというdatetime型のテーブルに
更新時に自動的に更新日時をセットする場合

-- =============================================
-- テーブル作成
-- =============================================
CREATE TABLE [dbo].[M_EMPLOYEE](
[EMPLOYEE_CODE] [char](5) COLLATE Japanese_CI_AS NOT NULL,
[EMPLOYEE_NAME] [varchar](20) COLLATE Japanese_CI_AS NULL,
[UPDATE_TIME] [datetime] NOT NULL CONSTRAINT [DF_M_EMPLOYEE_UPDATE_TIME] DEFAULT (getdate()),
CONSTRAINT [PK_M_EMPLOYEE] PRIMARY KEY CLUSTERED (
[EMPLOYEE_CODE] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

-- =============================================
-- UPDATE時、更新日時を自動登録するトリガ作成
-- =============================================

CREATE TRIGGER [TRG_M_EMPLOYEE]
ON [dbo].[M_EMPLOYEE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;

/*更新日時をセットする*/
update M_EMPLOYEE
set M_EMPLOYEE.UPDATE_TIME = GETDATE()
from INSERTED
where INSERTED.EMPLOYEE_CODE = M_EMPLOYEE.EMPLOYEE_CODE

END



Copyright (C) 2009- station-t.com All Rights Reserved , Link Free