我想创建一个Insert触发器,如果它们为null,则更新所有插入行的值,新值应根据插入表中的另一列从不同的表中获取。
我试过了:
UPDATE INSERTED
SET TheColumnToBeUpdated =
(
SELECT TheValueCol FROM AnotherTable.ValueCol
WHERE AnotherTable.ValudCol1 = INSERTED.ValueCol1
)
WHERE ValueCol IS NULL
但是我收到了这个错误:
Msg 286, Level 16, State 1, Procedure ThisTable_INSERT, Line 15
The logical tables INSERTED and DELETED cannot be updated.
我该怎么做?
答案 0 :(得分:44)
您需要更新目标表,而不是逻辑表。但是,您可以使用逻辑表连接以确定要更新的行:
UPDATE YourTable
SET TheColumnToBeUpdated =
(
SELECT TheValueCol FROM AnotherTable.ValueCol
WHERE AnotherTable.ValudCol1 = INSERTED.ValueCol1
)
FROM YourTable Y
JOIN Inserted I ON Y.Key = I.Key
WHERE I.ValueCol IS NULL
答案 1 :(得分:20)
您可以将触发器更改为INSTEAD OF INSERT。这将允许您检查传入的值,如果需要,可以使用其他表中的值替换它们。
CREATE TRIGGER CoolTrigger
ON MyAwesomeTable
INSTEAD OF INSERT
AS
BEGIN
INSERT MyAwesomeTable (TheValueCol)
SELECT ISNULL(INSERTED.TheValueCol, AnotherTable.TheValueCol) AS TheValueCol
FROM INSERTED
JOIN AnotherTable ON INSERTED.ValueCol1 = AnotherTable.ValueCol1
END
注意:INSTEAD OF触发器不会导致递归。
答案 2 :(得分:0)
insert into output
(SELECT t1.ts - INTERVAL (SECOND(t1.ts)%10) SECOND,
t1.ts - INTERVAL (SECOND(t1.ts)%10) SECOND + INTERVAL 10 SECOND ,sum(t1.data),
FROM (select * from input
where unix_timestamp(ts) >= unix_timestamp('2000-01-01 00:00:10')
and unix_timestamp(ts) < unix_timestamp('2000-01-01 00:01:20')
)
as t1
GROUP BY UNIX_TIMESTAMP(t1.ts) DIV 10 );
这是我的输出表的来源。 因此插入不是值。
我很抱歉,但我无法从这里(办公室)访问我的帐户,