当A列等于B列时创建触发器

时间:2018-11-29 14:35:47

标签: sql sql-server

我试图在SQL Server中创建一个触发器,以在A列等于B列时在另一列中自动插入一个值,否则,在其中插入另一个值。

例如,如果colA不等于colB,则在“分数”列中插入“错误”。如果colA等于colB,则在“分数”列中插入“正确”。

我在下面尝试过此方法,它不起作用。

如何更改它的工作原理?

CREATE TABLE testtrigger(
ID INT identity(1,1) primary key,
ColA varchar(50),
ColB varchar(50),
Score varchar(50)
);
GO

CREATE TRIGGER trgAfterInsertUpdate 
   ON testtrigger
   AFTER INSERT, UPDATE
AS
BEGIN
   SET NOCOUNT ON;
   IF UPDATE, INSERT
   BEGIN
      UPDATE testtrigger
      SET Score = correct
      WHERE ColA = ColB
   ELSE
      SET Score = wrong
      WHERE ColA <> ColB
   END
END

谢谢。

4 个答案:

答案 0 :(得分:4)

Score计算列设为

CREATE TABLE testtrigger(
ID INT identity(1,1) primary key,
ColA varchar(50),
ColB varchar(50),
Score AS CASE WHEN ISNULL(ColA, 0) = ISNULL(ColB, 0) THEN 'Correct' ELSE 'Wrong' END
);

INSERT INTO Testtrigger(ColA, ColB) VALUES
('A', 'B'),
('A', 'A');

SELECT *
FROM Testtrigger;

更新:

如果您已经创建了表格,则可以进行

ALTER TABLE testtrigger
DROP COLUMN Score;

ALTER TABLE testtrigger
ADD Score AS CASE WHEN ISNULL(ColA, 0) = ISNULL(ColB, 0) THEN 'Correct' ELSE 'Wrong' END PERSISTED;

答案 1 :(得分:2)

您不能在int Score列中设置varchar值,但是可以设置01值。 0表示错误,1表示正确。 让我举个例子:

CREATE TRIGGER trgAfterInsertUpdate 
   ON testtrigger
   AFTER INSERT, UPDATE
AS
BEGIN
   SET NOCOUNT ON;
   IF UPDATE(ColA)   
   BEGIN      
      UPDATE t
      SET score = CASE 
                    WHEN t.ColA = i.ColB THEN 1
                    ELSE 0
                  END
      FROM dbo.testtrigger t
      INNER JOIN INSERTed i ON t.ID = i.ID    
   END
END

或仅将您的Score列更改为VARCHAR(20)

CREATE TABLE testtrigger(
ID INT identity(1,1) primary key,
ColA varchar(50),
ColB varchar(50),
Score varchar(20)
);

答案 2 :(得分:2)

您可以在SQL Server中使用CASE或IIF()尝试

   CREATE TRIGGER trgAfterInsertUpdate 
   ON testtrigger
   AFTER INSERT, UPDATE
   AS
   BEGIN
   SET NOCOUNT ON;

      UPDATE t
      SET t.Score = (CASE WHEN t.ColA = t.ColB THEN  'Correct' 
                          WHEN  t.ColA <> t.ColB THEN 'Wrong' END)
      FROM testtrigger t
      INNER JOIN  inserted i ON t.ID=i.ID


      -- UPDATE t
      -- SET t.Score = (IIF( t.ColA = t.ColB,'Correct','Wrong'))
      -- FROM testtrigger t
      -- INNER JOIN  inserted i ON t.ID=i.ID

   END

INSERT INTO Testtrigger(ColA, ColB) VALUES
('G', 'G'),
('H', 'A');

SELECT *
FROM Testtrigger

结果

ID  ColA    ColB    Score
-------------------------
1   A        B      wrong
2   A        A      correct
3   G        G      correct
4   H        A      wrong

答案 3 :(得分:1)

我认为您只是想念集合中的'

CREATE TABLE testtrigger(
ID INT identity(1,1) primary key,
ColA varchar(50),
ColB varchar(50),
Score varchar(50)
);
GO

CREATE TRIGGER trgAfterInsertUpdate 
   ON testtrigger
   AFTER INSERT, UPDATE
AS
BEGIN
   SET NOCOUNT ON

   UPDATE testtrigger
   SET Score = 'correct'
   WHERE ColA = ColB

   UPDATE testtrigger
   SET Score = 'wrong'
   WHERE ColA <> ColB

END