SQLServer Triggers

Please help me write a trigger that adds new rows to the table.

I have 3 tables in my database:

  • Regions (id, name); id - primary
  • Technique (id, name); id - primary
  • Availability (id, region, technic, count); id - primary, region - foreign at Regions.id, Technik - foreign at technics.id.

I want to add a new line in “Accessibility” for each line of “Technique” when adding a line to “Regions”.

Sort of:

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

But in a SQL trigger. I want to do the same when adding a new Technics line.

+3
source share
2 answers

- (, Availability.id ), :

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

, Technics, ( , ).

+4

, - .

Region.

+1

Source: https://habr.com/ru/post/1740304/


All Articles