sql trigger to stop duplicates across row

后端 未结 2 1547
悲哀的现实
悲哀的现实 2021-01-16 03:18

I have a table with multiple records:

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

i

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-16 03:36

    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
    

提交回复
热议问题