SQLServer触发器

发布于 2024-08-28 06:57:14 字数 479 浏览 4 评论 0原文

请帮助我编写一个向表中添加新行的触发器。

我的数据库中有 3 个表:

  1. Regions (id, name); id - 主要;
  2. 技术(ID、姓名); id - 主要;
  3. 可用性(ID、区域、技术、计数); id - 主要,区域 - Regions.id 上的外国,Technik - technics.id 上的外国。

我想在区域中添加行时为每个技术行在可用性中添加新行。

有点像:

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

但是在 SQL 触发器中。 我想在添加新的技术行时执行相同的操作。

Please help me to write a trigger that adds new rows to a 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 a SQL trigger.
I want to do the same on adding new Technics row.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山田美奈子 2024-09-04 06:57:14

尝试这样的事情(假设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

你没有说区域如何与技术连接,所以我交叉连接它们(每个插入的区域,获取一行对于每项技术)。

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).

晨曦慕雪 2024-09-04 06:57:14

在我看来,实现此特定业务/插入逻辑的更清晰的解决方案是使用存储过程。

只需创建一个存储过程来处理将记录插入到 Region 表的逻辑。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文