sql – 表上的约束,用于限制要存储的记录数

我有一个数据库,有两个表广告和图像. Ads表中有一个主键adid,它是
Images表中的外键.

我想在表格上创建一个约束图像,不超过5个adid可以存储在Images表格中.

我需要知道调用这种类型的约束以及如何使用SQL Server中的查询来完成此操作.

最佳答案 没有constaint来强制执行该规则,但是像下面这样的触发器可以执行此操作:

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
点赞