Is it possible to make one column readonly?
There is no built in declarative support for non updatable columns (except for specific predefined cases such as IDENTITY
)
This Connect item requested it but was rejected. Add DRI to enforce immutable column values
An UPDATE
trigger would probably be the most robust way of achieving this. It could check IF UPDATE(CreatedByUser)
and raise an error and rollback the transaction if true.
I've made my implementation of the UPDATE TRIGGER
approach suggested by Martin Smith's answer as follows:
CREATE TRIGGER trgAfterUpdateAsset ON dbo.Asset
FOR UPDATE AS
IF UPDATE(AssetTypeID) AND EXISTS (SELECT * FROM inserted i JOIN deleted d ON i.ID = d.ID WHERE i.AssetTypeID <> d.AssetTypeID)
BEGIN
RAISERROR ('AssetTypeID cannot change.', 16, 1);
ROLLBACK TRAN
END
(Note: The table has a Primary Key column, called ID).
I'm only rejecting the update if the value of AssetTypeID changes. So the column could be present in an update, and if the value did not change, than it would pass through. (I needed this way)
You could use a view with derived column. Try this
create table ro_test(id int primary key, CreatedByUser int)
go
create view v_ro_test
as
select id, CreatedByUser*1 CreatedByUser from ro_test
go
insert into ro_test values(1,10);
update ro_test
set CreatedByUser =11
where id =1;
select * from v_ro_test;
go
--ERROR--
update v_ro_test
set CreatedByUser =10
where id =1;
--BUT--
update v_ro_test
set id =2
where id =1;
select * from v_ro_test;