我有两张桌子。当我为特定列插入新值时,我想更新第二个表中的另一列。我怎么能这样做?
这是一个简单的示例,但它提供了“关键字'插入'附近的语法错误。”错误如预期。
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 :(得分: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
答案 1 :(得分: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的值。 使用table2中的主键和table1更改ID列,将col1更改为要在table2中更新的列