0

我对 SQL Server 触发器很陌生。我最终遇到了这样的问题。请看一看。

  1. 我有两个表“用户”和“测试”

       CREATE TABLE users( 
                 email VARCHAR(250),
                 rank FLOAT
          );
    
        CREATE TABLE test(
              score INT,
             total INT
        );
    
  2. 我需要创建一个触发器;

    2.1 根据 avg (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
    
4

4 回答 4

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

我没有对此进行测试,但这应该可以正常工作。

于 2013-03-12T09:07:16.090 回答
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);

希望这有帮助。

于 2013-03-12T06:51:41.493 回答
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
于 2013-03-12T06:51:50.447 回答
-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;
于 2013-03-18T10:07:08.057 回答