sql - How to add Constraint to Table's Column,so value cannot be other than default -
recently 1 issue came db,the same db been shared multiple application.
my first application uses 1 table insert row having column
productiondate of datatype datetime
datecreated of datatype datetime default getdate()
as know datecreated, have time,when row inserted table when no values passed in insert statement
but 1 of collegues used same column datecreated application insert other value (date ) product inspite of using productiondate (he misleaded name),
i found issue when reports misleading (select based on datecreated).
how can force column avoid accepting ,except contain getdate(), ie
insert mytablename(.....,datecreated,......) values (.....,'2015-07-15 14:06:42.250',......) should throw exception/error!! using sql server 2012
exception:i have update/insert trigger fill datemodified column :(
i rename existing table (say underscore prefix) , replace view using original name , performing trivial computation on datecreated column becomes computed , therefore readonly:
create table dbo._t ( id int not null, datecreated datetime not null constraint df_created default (current_timestamp)) go create view dbo.t schemabinding select id,coalesce(datecreated,datecreated) datecreated dbo._t go insert dbo.t (id) values (1) go insert dbo.t(id,datecreated) values (1,'20150101') produces:
(1 row(s) affected) msg 4406, level 16, state 1, line 1 update or insert of view or function 'dbo.t' failed because contains derived or constant field. and can see second insert failed:
select * dbo.t id datecreated ----------- ----------------------- 1 2015-07-07 14:22:48.840 and give other user/application permission talk view, not base table.
Comments
Post a Comment