Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL how to prevent deletion first row in table

I have a table like this:

CREATE TABLE Users
(

    idUser int IDENTITY(1,1) PRIMARY KEY,
firstName varchar(40) NOT NULL,
secondName varchar(40),
lastName varchar(70) NOT NULL,
position varchar(80),
section varchar(80) NOT NULL
)

And someone need to delete only one of the Users. How can I prevent first row being deleted? I can't reinsert it, first row must have idUser = 1.

like image 775
Maggie Avatar asked Oct 21 '22 21:10

Maggie


1 Answers

You can create a Trigger on table [Users] that watch when a register from this table is being deleted. So you check if deletion is userId:1 then you don't delete it, else.. you delete it, here is the code:

CREATE TRIGGER sampleTrigger
    ON [Users]
    INSTEAD OF DELETE
AS
    IF EXISTS(SELECT * FROM deleted WHERE idUser IN (1))
    BEGIN
        RAISERROR ('Is not allowed to delete idUser: 1',16, 1)  
    END
    ELSE
    BEGIN
        DELETE [Users] WHERE idUser IN (SELECT idUser FROM deleted)
    END
GO
like image 85
Wagner Leonardi Avatar answered Oct 23 '22 16:10

Wagner Leonardi