如何将约束添加到 Table 的列,因此值只能是默认值

How to add Constraint to Table's Column,so value cannot be other than default

最近我的数据库出现了一个问题,同一个数据库被多个应用程序共享。

我的第一个应用程序使用一个 Table 来插入具有 A 列的行

ProductionDate DataType DateTime
DateCreatedDataType DateTime Default GetDate()

众所周知DateCreated,会有这样的时候,当Row被插入到table的时候,Insert语句中没有传递任何值

但是我的一位同事使用他的应用程序中的同一列 DateCreated 为产品插入一些其他值(日期),尽管使用 ProductionDate(他被名称误导了),

我发现这个问题是因为我的报告具有误导性(Select 基于 DateCreated)。

我怎样才能强制我的专栏避免接受任何内容,除非它只包含 Getdate(), 即

 INSERT INTO MyTableName(.....,DateCreated,......)
 VALUES (.....,'2015-07-15 14:06:42.250',......)

应该投Exception/Error!!我正在使用 SQL SERVER 2012

异常:我已经有一个 update/Insert 触发器来填充我的 DateModified 列 :(

您可以添加触发器来设置创建日期。以下代码取自 here

CREATE TRIGGER tr[TableName]CreateDate ON [TableName]
FOR INSERT 
AS
UPDATE [TableName] SET [TableName].Created=getdate()
FROM [TableName] INNER JOIN Inserted ON [TableName].[UniqueID]= Inserted.[UniqueID]

两种方式: 1)您可以使用 UPDATE TRIGGER 将 DateCreated 的值重新设置为以前的值 2) 你可以用绳子把你的同事绑在下一棵树上,教他 "DateCreated" 的意思:-)

编辑:发现这个:

我会重命名现有的 table(例如使用下划线前缀)并用使用原始名称的视图替换它并对 DateCreated 列执行简单的计算,以便它成为计算因此只读:

create table dbo._T (
    ID int not null,
    DateCreated datetime not null constraint DF_Created DEFAULT (CURRENT_TIMESTAMP))
go
create view dbo.T
with schemabinding
as
    select ID,COALESCE(DateCreated,DateCreated) as DateCreated
    from dbo._T
go
insert into dbo.T (ID) values (1)
go
insert into dbo.T(ID,DateCreated) values (1,'20150101')

生产:

(1 row(s) affected)

Msg 4406, Level 16, State 1, Line 1
Update or insert of view or function 'dbo.T' failed because it contains a derived or constant field.

我们可以看到第二次插入失败:

select * from dbo.T
ID          DateCreated
----------- -----------------------
1           2015-07-07 14:22:48.840

现在只允许其他 user/application 与此视图交谈,而不是基础 table。