简体   繁体   English

如何在列上添加检查约束以进行更新

[英]How to add a check constraint on column for update

I'm adding a column to a table, and want to set a constraint on it, that it's not allowed to be updated until a given date, stored in the same table row. 我正在向表中添加一列,并希望对此设置一个约束,即在给定日期之前不允许将其更新存储在同一表行中。

This is what I've got so far: 到目前为止,这是我得到的:

ALTER TABLE sometable 
    ADD somecolumn BIT NOT NULL DEFAULT 0;

ALTER TABLE sometable 
    ADD CONSTRAINT somedate_before_now 
        CHECK (somedatecolumn < GETDATE()); 

How do I get this to work, for updates of somecolumn only? 我如何才能使用此功能,仅适用于somecolumn更新? Inserts and updates of other columns should be allowed. 应该允许其他列的插入和更新。

I'm testing this on an in memory H2 database, but it will have to work with SQL Server as well. 我正在内存H2数据库中对此进行测试,但它也必须与SQL Server一起使用。

I think the safe way to do this is using a trigger. 我认为执行此操作的安全方法是使用触发器。

A constraint such as this: 这样的约束:

CHECK (somedatecolumn < GETDATE())

doesn't really make sense from a relational point of view. 从关系的角度来看并没有任何意义。 It can guarantee the values are true on an update or insert . 它可以保证值在updateinsert为true。 However, the database cannot guarantee that the values are true in general. 但是,数据库不能保证这些值通常是正确的。 You should use CHECK constraints for things that you always want to be true in a row. 您应该将CHECK约束用于您一直希望连续成真的事物。

(The problem is that GETDATE() changes with no changes on the row.) (问题是GETDATE()更改了,而行上没有任何更改。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM