I have a relational table with two foreign-keys pointing to same table.
The first foreign-key column should always be the minimum of a foreign property and the second one the maximum.
I am new to SQL Server and I read that a insert using the inserted temporary table should be used but how should I set the minimum and maximum relational childs not using a loop to iterate over the inserted entries.
Tables:
table Child
{
int id;
int value;
}
table Parent
{
int id;
// foreign-keys A enforce minimum child value!
int childA;
int childB;
}
MySql Trigger
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;
Solved it using conditional select query.
Not so elegant, especially if many properties need to set but it works.