sql 在同一 table 内插入触发更新列后

sql after insertion trigger update column within the same table

我正在尝试编写触发器以在插入完成后更新同一个 table 中的列

我的 table 是

create table BlueTooth (
ID int Primary Key NOT NULL ,
version varchar(45) NOT NULL,
score float null,
speed float 
);

我的触发器是

create or replace trigger BlueToothsc
ON BlueTooth 
after insert 
as 
begin 
update BlueTooth set score((select speed from inserted)/(select max(speed) from BlueTooth ) * 100)
END 
GO

但我在第一行的 "incorrect syntax near" "or" 关键字中遇到错误 和 "incorrect syntax near" "as"

有人可以帮我解决这个问题

我想通过 (inserted speed / max(speed) ) * 100)

更新 BlueTooth tables score

当出现更快版本的蓝牙时,分数值应为 100,所有其他分值应分别获得较低的值。

语法错误是

1) You have to create or alter the trigger seperately
2) missed = while assigning the value to score in update statement

试试这个触发器。

create trigger BlueToothsc
ON BlueTooth 
after insert 
as 
begin 
update BlueTooth set score = ((select speed from inserted)/
             (select max(speed) from BlueTooth ) * 100)
where ID = (SELECT ID FROM INSERTED)
END 
GO

与其存储分数,不如在查询时计算它。因此,在这种情况下,视图应该可以完成工作:

create table BlueTooth (
ID int Primary Key NOT NULL ,
version varchar(45) NOT NULL,
speed float 
);
go
create view BlueToothScores
as
   select
       ID,
       version,
       speed,
       speed * 100 / MAX(speed) OVER () as score
   from
       BlueTooth

现在您无需担心触发器或更新例程 - 结果始终正确,因为它们是根据真实数据计算得出的