Reputation: 5
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.
Also this trigger should see that if I insert an Elephant without a number, it just goes and picks 3 as number.
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.
Any ideas?
Upvotes: 0
Views: 106
Reputation: 1270391
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;
Upvotes: 0
Reputation: 13571
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.
Upvotes: 1
Reputation: 175
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. Your better off redesigning the table to have a unique key, use the ANIMALSPECIES as a field and count the number by Animal Species. You may also want to add a field like ACTIVE and filtering by the value in ACTIVE. This way you can see the keep the data for further purposes.
I do not recommend what you are requesting.
Upvotes: 0