删除 SQL 服务器中的行只有一列为零

Delete row in SQL Server only a column is zero

我在 SQL Server 2012 中有 2 个 table 的数据库。

table一个

aid, (used), max_count

TableB

bid, aid, x

In table B bid 是主键,aid 是 table A 的外键。

在tableA中,aid是主键,used是计算列,统计在tableB中使用aid的个数。

我想要在 table A 总是 used <= max_count.

如何控制 table A 的更新 max_count 不低于 used

如何控制添加到 table B used 不大于 max_count

这个触发器适用于插入 B 和更新 A。您可能还需要其他触发器来更新 B。

CREATE TRIGGER tr_A 
   ON  dbo.A 
   INSTEAD OF UPDATE
AS 
BEGIN
    SET NOCOUNT ON;

    IF EXISTS (
        SELECT TOP 1 *
        FROM inserted
        WHERE used>max_count
    )
        RAISERROR('used cannot be higher than mox_count', 16, 1)
    ELSE
        UPDATE A SET
            A.max_count = I.max_count
        FROM A
        INNER JOIN inserted I ON I.aid = A.aid 

END;
GO

CREATE TRIGGER tr_B
   ON  dbo.B
   INSTEAD OF INSERT
AS 
BEGIN
    SET NOCOUNT ON;

    IF (
        SELECT TOP 1 A.max_count-A.used
        FROM inserted I
        INNER JOIN dbo.A ON I.aid = A.aid
    )<=0
        RAISERROR('used cannot be higher than mox_count', 16, 1)
    ELSE
        INSERT INTO dbo.B (bid, aid, x)
        SELECT bid, aid, x
        FROM inserted;
END;
GO