sql触发器可以跨行停止重复

时间:2011-08-18 02:17:22

标签: sql sql-server tsql triggers

我有一张包含多条记录的表格:

  • User_Name(例如'TOM')
  • Question_ID(例如'q002')
  • 答案(例如'D')

我想创建一个触发器,这样任何人都无法两次提交相同问题的答案。 必须只是一个触发器

CREATE TRIGGER trigger_Check_Duplicates

ON submit_Answer

FOR INSERT
AS

IF SELECT???

PRINT 'duplicate'

raiserror('cant submit answer to same question twice')

ROLLBACK

End

2 个答案:

答案 0 :(得分:4)

Create trigger

CREATE TRIGGER dbo.uniqueUserQuestion 
ON dbo.submit_Answer
INSTEAD OF INSERT
AS
BEGIN
    SET NOCOUNT ON
    IF EXISTS 
    (
        SELECT 1 
        FROM dbo.submit_Answer T 
        INNER JOIN INSERTED I 
        ON T.user_name = I.user_name 
            AND T.question_id = I.question_id
    )
    BEGIN
        -- Do dupe handling here
        PRINT 'duplicate'
        raiserror('cant submit answer to same question twice')
        return
    END

    -- actually add it in
    INSERT INTO
        dbo.submit_Answer
    SELECT
        *
    FROM
        INSERTED I
END
GO

答案 1 :(得分:1)

MySql不支持INSTEAD OF触发器,这是您在此处需要使用的内容。在SQL Server中,您将使用INSTEAD OF INSERT触发器,在插入发生之前触发,您可以在其中写入重复的检查。但是,如果您可以避免触发,为什么不使用Stored Routine并在插入之前检查副本?

当然,如果你真的,真的不能使用约束。

编辑:更新MSSQL的答案。

以下是right from MSDN示例:

CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If there is no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
      FROM Person P, inserted I
      WHERE P.SSN = I.SSN))
   INSERT INTO Person
      SELECT SSN,Name,Address,Birthdate
      FROM inserted
ELSE
-- Log an attempt to insert duplicate Person row in PersonDuplicates table.
   INSERT INTO PersonDuplicates
      SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
      FROM inserted
-- Check for duplicate Employee. If no there is duplicate, do an INSERT.
IF (NOT EXISTS (SELECT E.SSN
      FROM EmployeeTable E, inserted
      WHERE E.SSN = inserted.SSN))
   INSERT INTO EmployeeTable
      SELECT EmployeeID,SSN, Department, Salary
      FROM inserted
ELSE
--If there is a duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
   UPDATE EmployeeTable
      SET EmployeeID = I.EmployeeID,
          Department = I.Department,
          Salary = I.Salary
   FROM EmployeeTable E, inserted I
   WHERE E.SSN = I.SSN
END

你显然需要修改/简化你的情况,但基本的背景就在那里。