我是SQL Server触发器的陌生人。 我最终遇到了这样的问题。请看看。
我有两张桌子'用户'和& '测试'
CREATE TABLE users(
email VARCHAR(250),
rank FLOAT
);
CREATE TABLE test(
score INT,
total INT
);
我需要创建一个触发器;
2.1更新用户按平均值排名(avg = test.score / test.total)
2.2这是我到目前为止所尝试的内容:
CREATE TRIGGER auto_rank ON dbo.test FOR INSERT
BEGIN
DECLARE @sc INT
DECLARE @tot INT
DECLARE @avg FLOAT
@tot = SELECT inserted.total FROM dbo.test
@sc = SELECT inserted.score FROM dbo.test
SET @avg=@sc/@tot
UPDATE dbo.users SET rank=@avg WHERE email=inserted.email
END
答案 0 :(得分:0)
您从表格设计中遗漏了测试中的电子邮件,但根据您的代码,它应该包含此列:
UPDATE dbo.users SET rank=@avg WHERE email=inserted.email
然后在这种情况下你需要一个视图而不是触发器:
Create view user as (select email, score/total as rank from test group by email);
希望得到这个帮助。
答案 1 :(得分:0)
您需要修改表格,以便测试表包含电子邮件列:
CREATE TABLE test(score INT,
total INT,
email varchar(250)
);
然后你可以像这样创建trgiger:
CREATE TRIGGER [dbo].[auto_rank] ON [dbo].[test]
FOR INSERT
AS
BEGIN
DECLARE MyCursor CURSOR FOR
SELECT score, total, email FROM Inserted
DECLARE @sc INT
DECLARE @tot INT
DECLARE @email VARCHAR(30)
DECLARE @avg FLOAT
DECLARE @MSG VARCHAR(50)
OPEN MyCursor;
FETCH NEXT FROM MyCursor INTO @sc, @tot, @email
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @avg=@sc/@tot
UPDATE users SET rank=@avg WHERE users.email=@email
SELECT @MSG = 'email Updated ' + @email + '. New Rank is ' + Str(@avg, 25, 5);
PRINT @MSG
FETCH NEXT FROM MyCursor
END;
CLOSE MyCursor;
DEALLOCATE MyCursor;
END
答案 2 :(得分:0)
试试这个:
CREATE TRIGGER auto_rank ON dbo.test FOR INSERT
BEGIN
UPDATE a SET a.rank=b.rn
from
users a
inner join
(select email,inserted.score/inserted.total rn from inserted)b
on a.email=b.email
END
我没有对此进行测试,但这应该可以正常工作。
答案 3 :(得分:-1)
很抱歉继续这个帖子已经很晚了,但我很高兴地说我找到了答案。这是因为你们所有人。
所以,这就是我所做的;
第一
CREATE TABLE users(
email VARCHAR(250),
rank FLOAT,
constraint pk_users PRIMARY KEY(email)
);
CREATE TABLE test(
email VARCHAR(250),
score INT,
total INT,
constraint pk_test PRIMARY KEY(email),
constraint fk_from_users FOREIGN KEY(email) references users(email)
);
create trigger trig_ex02 on dbo.test
after insert
as
begin
declare @score FLOAT
declare @total FLOAT
declare @average FLOAT
declare @msg varchar(100)
declare @email varchar(250)
set @email = (select email from inserted)
set @score = (select score from inserted)
set @total = (select total from inserted)
set @average =(@score/@total)
select @msg = 'SCORE IS'+ str(@score)+'TOTAL IS'+str(@total)+' AVERAGE IS ' +str(@average,25,5)+' END '
print @msg
UPDATE users SET rank=@average WHERE users.email=@email
end;