2016-03-22 71 views
0

我有兩個表格。當我爲特定列插入一個新值時,我想更新第二個表中的另一列。我該怎麼做?插入特定列的觸發器

下面是一個簡單的示例,但它給出了「關鍵字'插入'附近的語法不正確。」錯誤如預期。

Create trigger trigger_Insert_Months 
on [Quantities] 
after Insert 
As 
if Insert([Work Name]) 
begin 
    declare @NewWorkName varchar(200) 
    select @NewWorkName = [Work Name] from inserted 
    insert into [April]([Work Name]) 
    values (@NewWorkName) 
End 

回答

0

試試這個:

CREATE TRIGGER trigger_Insert_Months 
ON [Quantities] 
AFTER INSERT 
AS 
BEGIN 
    INSERT INTO [April]([Work Name]) 
    SELECT [Work Name] from inserted 
    WHERE NOT EXISTS (SELECT 1 FROM [Quantities] WHERE [Quantities].[Work Name] = INSERTED.[Work Name] AND INSERTED.PrimaryKey != [Quantities].[PrimaryKey]) 
End 
+0

消息4104,級別16,狀態1,過程trigger_Insert_Months,行43 多部分標識符「INSERTED .Work Name「無法綁定。 消息4104,級別16,狀態1,過程trigger_Insert_Months,行43 無法綁定多部分標識符「INSERTED.PrimaryKey」。 消息207,級別16,狀態1,過程trigger_Insert_Months,行43 無效的列名'PrimaryKey'。 – Macukadam

+0

您可以顯示「數量」和「四月」的表格定義。通過'PrimaryKey',我的意思是你必須用''Quantities'表中的主鍵列來替換它。 – AKS

+0

我非常感謝! – Macukadam

0

糾正我,如果我錯了。您想要插入table1中的值並使用插入的值更新table2中的值。

create trigger tr1 on Table1 
for insert 
as 
begin 
if exists (select 1 from inserted) 
begin 
update a 
set a.col1 = b.col 
from table2 as a 
inner join (select * from inserted) as b 
on a.id = b.id 
end 
end 

此代碼在Table1中發生插入時激活觸發器,並使用插入的行更新col1的table2的值。 更改ID列與表2中的主鍵和表1和col1與表2中要更新的列