Ernio Ernio - 12 days ago 5
SQL Question

Check if (during insertion) building has always same adress

I am writing TRIGGER INSTEAD OF INSERT which validates data before insertion.

To simplify my problem:
Consider this as my insertion:

INSERT INTO Event VALUES
('A', 'building1', 'adress1'),
('B', 'building2', 'adress2'),
('C', 'building1', 'adress3')


I need to catch case in which INSERTED table contains same building with different adresses - which is not possible.

Some IF statement snippet would really help me here.

Answer

Best solution is provided by Gordon. If normalizing the structure is not an option, you can consider an Unique Index on combination of 2 columns building, address. If this is also not an option and you really need to create a trigger:

if exists(select building 
          from inserted 
          group by building 
          having count(distinct address) > 1)
begin
    --your logic here
end
Comments