sql trigger to stop duplicates across row

2019-02-20 12:05发布

问题:

I have a table with multiple records:

  • User_Name ( e.g. 'TOM')
  • Question_ID (eg 'q002')
  • Answer (e.g. 'D')

i want to create a trigger so that no one can submit an answer to the same question twice. It has to be a trigger only.

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

回答1:

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


回答2:

MySql does not support INSTEAD OF triggers, which is what you'd need to use here. In SQL Server, you'd use an INSTEAD OF INSERT trigger that will fire before the insert occurs, where you can write a check for the duplicate. However, if you can avoid a trigger, why not use a Stored Routine and just check for the duplicate before inserting?

This is, of course, if you really, really cannot use a constraint.

Edit: Updating answer for MSSQL.

Here's an example 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

You'll obviously need to modify/simplify for your situation, but the basic context is there.