简体   繁体   English

用于编号的 INSERT DELETE 后的 SQL 触发器

[英]SQL Trigger After INSERT DELETE for Numbering

I have a table with two columns, and together they make up the primary key for this table:我有一个包含两列的表,它们一起构成了该表的主键:

    Column A | Number
   ----------+--------
    Elephant | 1
    Elepahnt | 2
    Giraff   | 1
    Giraff   | 2
    Giraff   | 3

Now, I want a trigger that if you delete Giraff 2, then Giraff 1 stays the same, but Giraff 3 becomes Giraff 2.现在,我想要一个触发器,如果​​你删除 Giraff 2,那么 Giraff 1 保持不变,但 Giraff 3 变成 Giraff 2。

Also this trigger should see that if I insert an Elephant without a number, it just goes and picks 3 as number.这个触发器也应该看到,如果我插入一个没有数字的大象,它只会选择 3 作为数字。

So I am thinking a trigger after insert, delete所以我想在插入后触发,删除

but I need a if statement/loop that goes through each row re-evaluating the numbers and updating if necessary.但我需要一个 if 语句/循环来遍历每一行,重新评估数字并在必要时进行更新。

Any ideas?有任何想法吗?

Two things.两件事情。

This is a terrible idea, I can't urge you enough not to do it.这是一个糟糕的主意,我不能敦促你不要这样做。 Whatever reason you think you have for this is wrong.无论你认为你有什么理由都是错误的。

That said, yes, you could do this with triggers.也就是说,是的,你可以用触发器来做到这一点。 Although you don't need to be deleting the record and renumbering, you could instead just delete from the end.虽然您不需要删除记录并重新编号,但您可以从末尾删除。 Which gives you a better solution than a trigger.这为您提供了比触发器更好的解决方案。 Use stored procedures instead.请改用存储过程。

That said, this is a terrible idea, please don't do it.也就是说,这是一个糟糕的主意,请不要这样做。 Please ask another question, giving the reason why you think you should do this.请提出另一个问题,并说明您认为应该这样做的原因。 Get a better opinion.获得更好的意见。

The re-evaluation that you are requesting seems like a lot can go wrong.您要求的重新评估似乎很多都可能出错。 In very small amounts of data it wouldn't be as much of a problem but as the data grows and multiple users are working in it you will see problems.在非常少量的数据中,这不会是一个很大的问题,但是随着数据的增长和多个用户在其中工作,您会看到问题。

You should consider the reason why you would want the PK to change.您应该考虑希望更改 PK 的原因。 Your better off redesigning the table to have a unique key, use the ANIMALSPECIES as a field and count the number by Animal Species.您最好重新设计表格以具有唯一键,使用 ANIMALSPECIES 作为字段并按 Animal Species 计算数量。 You may also want to add a field like ACTIVE and filtering by the value in ACTIVE.您可能还想添加一个字段,如 ACTIVE 并按 ACTIVE 中的值进行过滤。 This way you can see the keep the data for further purposes.通过这种方式,您可以查看保留数据以供进一步使用。

I do not recommend what you are requesting.我不推荐你所要求的。

Don't do this.不要这样做。 Instead, have an auto-incrementing column.相反,有一个自动递增的列。 This looks like:这看起来像:

create table animals (
    animal_id int generated always as identity,  -- depends on database
    a varchar(255)
);

Then create a view to calculate the value you want:然后创建一个视图来计算你想要的值:

create view v_animals as
    select animal,
           row_number() over (partition by a order by animal_id) as number
    from animals;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM