把握できないトリガーに問題があります。
Stu_Table2 と Stu_log という 2 つのテーブルがあるとします。Stu_table2 にはいくつかの列があり、そのうちの 1 つは自動的に生成された主キー [stu_id] です。2 つのテーブル間のリンクは [stu_name]=[user_id] です。
以下のコードは、更新と削除に対して正常に機能します (主キーが既に存在するため)。しかし、挿入に行き詰まっています - まだ生成されていない場合、自動生成された主キーを stu_name からログ テーブルに挿入するにはどうすればよいですか?
Stu_name 列、[stu_id] [Stu_name] [Stu_class]
Stu_log 列、[user_id] [stu_name]
明らかに、これは実際の例ではなく、概念実証をテストしているだけです。
ALTER TRIGGER [dbo].[stu_testtrigger]
ON [dbo].[Stu_Table2] FOR INSERT, UPDATE, DELETE
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries SELECT statements.
-- If an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;
--
-- Variables Needed for this Trigger
--
DECLARE @stu_ID int
DECLARE @stu_name varchar(15)
DECLARE @stu_class int
--
-- Determine if this is an INSERT,UPDATE, or DELETE Action
--
DECLARE @Action as char(1)
DECLARE @Count as int
SET @Action = 'I' -- Set Action to 'I'nsert by default.
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
BEGIN
SET @Action = 'D' -- Set Action to 'D'eleted.
SELECT @Count = COUNT(*) FROM INSERTED
IF @Count > 0
SET @Action = 'U' -- Set Action to 'U'pdated.
END
if @Action = 'D'
-- This is a DELETE Record Action
--
BEGIN
SELECT @Stu_id =[stu_id]
,@Stu_name = [stu_name]
FROM DELETED
DELETE [dbo].[stu_log]
WHERE [user_id]=@stu_id
END
Else
BEGIN
--
-- Table INSERTED is common to both the INSERT, UPDATE trigger
--
SELECT @stu_id =[stu_id]
,@stu_name = [stu_name]
FROM INSERTED
if @Action = 'I'
-- This is an Insert Record Action
--
--THIS IS WHERE I'm STUCK i think!!!
BEGIN
INSERT INTO [stu_log]
([user_id]
,[description])
VALUES
(@stu_id
,@stu_name)
END
else
-- This is an Update Record Action
--
BEGIN
UPDATE [stu_log]
SET [user_id] = @stu_id
,[description] = @Stu_name
WHERE [user_id]=@stu_id
END
END
ヘルプ!