2

我有一个关系表,其中两个外键指向同一个表。

第一个外键列应该始终是外部属性的最小值,第二个是最大值。

我是 SQL Server 的新手,我读到inserted应该使用使用临时表的插入,但是我应该如何设置最小和最大关系子项而不使用循环来迭代inserted条目。

表:

table Child
{
    int id;

    int value;
}

table Parent    
{
    int id;

    // foreign-keys A enforce minimum child value!
    int childA;
    int childB;
}

MySql 触发器

CREATE TRIGGER parent_beforeInsert
BEFORE INSERT ON Parent
    FOR each ROW
    BEGIN
        DECLARE childAValue AS INT;
        DECLARE childBValue AS INT;

        SET childAValue = (SELECT value FROM Child WHERE ID = NEW.childA);
        SET childBValue = (SELECT value FROM Child WHERE ID = NEW.childB);

        -- only check if b > a since reverse is wished behavior
        IF childBValue > childAValue
        BEGIN
            -- swap values              
            DECLARE newChildA AS INT = NEW.childA
            SET NEW.childA = NEW.childB;
            SET NEW.childB = newChildA;
        END;
    END;
4

1 回答 1

0

使用条件选择查询解决了它。不是那么优雅,特别是如果需要设置许多属性但它可以工作。

INSERT INTO Parent (childA_ID, childB_ID) 
    SELECT CASE WHEN childA.value <= childB.value THEN childA.ID ELSE childB.ID END AS childA_ID,
            CASE WHEN childA.value > childB.value THEN childA.ID ELSE childB.ID END AS childB_ID
        FROM inserted AS p, 
            Child AS childA, 
            Child AS childB,
        WHERE childA.ID = p.childA 
            AND childB.ID = p.childB;
于 2012-06-29T14:53:19.973 回答