Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: How to deny update on one column of a table via trigger?

Question:
In our SQL-Server 2005 database, we have a table T_Groups.
T_Groups has, amongst other things, the fields ID (PK) and Name.

Now some idiot in our company used the name as key in a mapping table...
Which means now one may not alter a group name, because if one does, the mapping is gone...
Now, until this is resolved, I need to add a restriction to T_Groups, so one can't update the group's name.
Note that insert should still be possible, and an update that doesn't change the groupname should also be possible.

Also note that the user of the application & the developers have both dbo and sysadmin rights, so REVOKE/DENY won't work.

How can I do this with a trigger ?

like image 792
Stefan Steiger Avatar asked Oct 26 '12 07:10

Stefan Steiger


People also ask

How do you execute a trigger only when a specific column is updated?

In SQL Server, you can create DML triggers that execute code only when a specific column is updated. The trigger still fires, but you can test whether or not a specific column was updated, and then run code only if that column was updated. You can do this by using the UPDATE() function inside your trigger.

How do I restrict a column in SQL?

The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a column it will allow only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

Can insert or UPDATE be performed on complex views using triggers?

Yes ,you can insert,update,delete using trigger. view is nothing but a table. Like creating another table to the main table.


1 Answers

CREATE TRIGGER dbo.yournametrigger ON T_Groups
FOR UPDATE
AS
BEGIN
  IF UPDATE(name)
  BEGIN
    ROLLBACK
    RAISERROR('Changes column name not allowed', 16, 1);
  END
  ELSE
  BEGIN
  --possible update that doesn't change the groupname
  END
END
like image 52
Aleksandr Fedorenko Avatar answered Nov 15 '22 08:11

Aleksandr Fedorenko