簡體   English   中英

相同表中的插入觸發器更新列后的sql

[英]sql after insertion trigger update column within the same 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" "or"出現"incorrect syntax near" "or"以及"incorrect syntax near" "as"

有人可以幫我嗎

我想通過(插入速度/ max(速度))* 100)更新BlueToothscore

當有更快版本的藍牙進入時,得分值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

現在您無需擔心觸發器或更新例程-結果始終是正確的,因為它們是根據真實數據計算得出的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM