views:

78

answers:

2
+3  Q: 

SQLServer triggers

Please help me to write trigger that, adds new rows in table

I have 3 tables in my database.

  1. Regions (id, name); id - primary
  2. Technics (id, name); id - primary
  3. Availability (id, region, technic, count); id - primary, region - foreign on Regions.id, Technik - foreign on technics.id

I want to add new row in Availability for each Technics row on adding row in Regions.

Somethink like:

procedure void OnAddNewRegion(int region)
{
    foreach (Row r in Technic)
    {
        Availability.Rows.Add(new Row(id, region, r.Id, 0));
    }
}

But in SQL trigger. Same I want to do on the adding new Technics row

+4  A: 

try something like this (assuming Availability.id is an identity), which will also handle multiple rows being inserted at one time:

CREATE TRIGGER TR_Regions ON Regions 
FOR INSERT
AS
INSERT INTO Availability 
        (region, technic, count)
    SELECT
        i.id, t.id, 0
        FROM INSERTED            i
            CROSS JOIN Technics  t

GO

you don't say how Regions joins with Technics, so I cross joined them (every inserted Regions, gets one row for every Technics).

KM
I guess the JOIN is via the Availability table, so cross join seems correct
devio
+1  A: 

In my opinion a cleaner solution for implementing this specific business/insert logic would be to use a Stored Procedure.

Simply create a stored procedure to handle the logic for inserting records to the Region table.

John Sansom
Why do you feel that? A trigger is really nothing more than a stored procedure that runs automatically under certain conditions. Using a trigger prevents someone forgetting/failing to run the stored procedure, thus enforcing the business rules the procedure is intended to address.
Dave
On the other hand, triggers act as surprise stored procedures. When you call a sproc, you know it might be inserting accessory rows; it's not as clear with a simple insert statement. Of course, if you used a sproc, you would have to take away insert permissions on that table.
WCWedin