在 table1(SQL 服务器)中插入任何行后,如何自动更新 table1 中的某些列 table2?

How can I update some columns table2 from table1 automatically after insert any row in table1 (SQL Server)?

我有 table1:

id  name    ranking energy   
-------------------------------
222    tom      15      f            
333    sara     11      f    
333    sara     2       a      
111    jhon     4       h       
111    jhon     16      f    
333    sara     13      g    
222    tom      12      j    

table2

id  name    ranking
-------------------
111 jhon    2
222 tom     1
333 sara    0

我希望插入到 table1 的任何行自动更新 table2 中的列 ranking

我想我应该使用触发器,但我不知道如何使用?

我使用下面的代码但没有用:

CREATE TRIGGER Table1Trigger   
ON Table1 
AFTER INSERT
BEGIN
    UPDATE Table2 
    SET ranking = Table1.ranking 
    WHERE Table1.id = Table2.id;
END;

想必你真的想要这个:

CREATE TRIGGER dbo.Table1Trigger
ON dbo.Table1
AFTER INSERT
AS --AS was missing
BEGIN

    UPDATE T2
    SET ranking = i.ranking
    FROM dbo.Table2 T2 
         JOIN inserted i ON T2.id = i.id;

END;

Table1 您的尝试没有上下文;定义为 Table1 的查询中没有对象。但是,您也不太可能希望在 table Table1 中使用 every 行,而是只使用插入的行(位于伪 table inserted).

我们可以使用输出子句来代替触发器

DECLARE @TmpTable TABLE (ID INT, ranking VARCHAR(100))

INSERT TestTable (ID, TEXTVal)
OUTPUT Inserted.ID ,Inserted.TEXTVal INTO @TmpTable
VALUES (2,'SecondVal')

UPDATE T2
  SET ranking = i.ranking
  FROM dbo.Table2 T2 
     JOIN @TmpTable i ON T2.id = i.id;