Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 - Setting a column as readonly

I have a "InsertTime" field in a table in a SQL Server 2005 database which is defaulted to "getDate()" when the record is first inserted into the database. I want to ensure that this column is not updated again.

Can this column be set to readonly or is there a better way to do this without writing all of the sql for the developers?

like image 998
GordyII Avatar asked Jan 20 '10 02:01

GordyII


People also ask

How do I make a column not editable in SQL?

Grant SELECT/INSERT/UPDATE/DELETE (as needed) on the view to APP . Create an INSTEAD OF trigger on the view to translate inserts, updates and deletes to the underlying table. The PL/SQL in the trigger can ignore that column for updates, or raise an exception if you want it to detect an attempt to modify the column.

What is read only column?

Indicates whether you can tab to a browse column but not edit it.

How do I make a SQL database read only?

Make Database Read/Write If you face an error that if the database is already in use, you can resolve the same by making database in single user mode – here is the guideline SQL SERVER – ALTER DATABASE dbname SET SINGLE_USER WITH ROLLBACK IMMEDIATE.


1 Answers

You can implement a 'read-only' field by creating an UPDATE trigger that checks for updates to that column and then rolls them back.

IF EXISTS (SELECT name FROM sys.objects
      WHERE name = 'ReadOnlyInsertTime_tr' AND type = 'TR')
   DROP TRIGGER dbo.ReadOnlyInsertTime_tr;
GO

CREATE TRIGGER ReadOnlyInsertTime_tr
ON dbo.MyTable
AFTER UPDATE 
AS 
IF (UPDATE(InsertTime))
BEGIN
ROLLBACK
-- Raise an informative error
-- RAISERROR (50009, 16, 10)
END;
GO
like image 79
Mitch Wheat Avatar answered Oct 27 '22 01:10

Mitch Wheat