Constraint on table to limit number of records to be stored

前端 未结 2 1217
青春惊慌失措
青春惊慌失措 2021-01-12 22:21

I have a database and there are two tables Ads and Images. There is a primary key adid in Ads table which is a foreign ke

2条回答
  •  半阙折子戏
    2021-01-12 22:48

    There is no constaint to enforce that rule, but a trigger like the following can do it:

    CREATE TRIGGER Images_not_more_than_five_per_add
    ON Images FOR INSERT
    AS
    DECLARE @RowCount int
    SET @RowCount = @@ROWCOUNT
    SET NOCOUNT ON
    IF @RowCount = 1
    BEGIN
        IF (SELECT COUNT(*) FROM Images WHERE Images.addid = (SELECT addid FROM inserted)) > 5
        BEGIN
            RAISERROR('No more than five images per add are allowed', 16, -1)
            ROLLBACK
            RETURN
        END
    END
    ELSE
    BEGIN
        IF EXISTS (
            SELECT *
            FROM
                Images
                INNER JOIN (
                    SELECT DISTINCT addid FROM inserted
                ) I ON Images.addid = I.addid
            GROUP BY
                Images.addid
            HAVING COUNT(*) > 5
        )
        BEGIN
            RAISERROR('No more than five images per add are allowed', 16, -1)
            ROLLBACK
            RETURN  
        END
    END
    

提交回复
热议问题