插入后的sql触发更新列在同一个表中

时间:2015-06-04 07:09:47

标签: sql sql-server triggers insertion

我尝试编写一个触发器,在插入完成时更新同一个表中的列

我的桌子是

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"

有人可以帮助我吗

我想更新BlueToothscore列(插入速度/最大(速度))* 100)

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

2 个答案:

答案 0 :(得分:1)

语法错误

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

答案 1 :(得分:1)

而不是存储得分,而不是在查询点计算它。因此,在这种情况下,视图应该完成这项工作:

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

现在您不必担心触发器或更新例程 - 结果总是正确的,因为它们是根据真实数据计算的