[英]Adding a unique constraint on calculated value of a column
I'm not exactly sure how to phrase this, but here goes... We have a table structure like the following: 我不确定如何表达这个,但是这里......我们有一个如下表结构:
Id | Timestamp | Type | Clientid | ..others..
001 | 1234567890 | TYPE1 | CL1234567 |.....
002 | 1234561890 | TYPE1 | CL1234567 |.....
Now for the data given above... I would like to have a constraint so that those 2 rows could not exist together. 现在对于上面给出的数据...我想有一个约束,以便这两行不能一起存在。 Essentially, I want the table to be
基本上,我希望桌子是
Unique for (Type, ClientId, CEIL(Timestamp/10000)*10000)
I don't want rows with the same data created within X time of each other to be added to the db, ie would like a constraint violation in this case. 我不希望将在彼此的X时间内创建的相同数据的行添加到db中,即在这种情况下想要约束违规。 The problem is that, the above constraint is not something I can actually create.
问题是,上述约束不是我实际可以创建的。
Before you ask, I know, I know.... why right? 在你问之前,我知道,我知道......为什么对吧? Well I know a certain scenario should not be happening, but alas it is.
我知道某种情况不应该发生,但唉。 I need a sort of stop gap measure for now, so I can buy some time to investigate the actual matter.
我现在需要一种止损措施,所以我可以花一些时间来调查实际问题。 Let me know if you need additional info...
如果您需要其他信息,请告诉我......
Yes, Oracle supports calculated columns: 是的,Oracle支持计算列:
SQL> alter table test add calc_column as (trunc(timestamp/10000));
Table altered.
SQL> alter table test
add constraint test_uniq
unique (type, clientid, calc_column);
Table altered.
should do what you want. 应该做你想做的事。
AFAIK, Oracle does not support computed columns like SQL Server does. AFAIK,Oracle不支持像SQL Server那样的计算列。 You can mimic the functionality of a computed column using Triggers.
您可以使用触发器模拟计算列的功能。
Here are the steps for this 以下是此步骤
CEILCalculation
to your table. CEILCalculation
的列。
CEILCalculation
with the value from CEIL(Timestamp/10000)*10000
CEIL(Timestamp/10000)*10000
的值更新CEILCalculation
(Unique for (Type, ClientId, CEILCalculation)
(Unique for (Type, ClientId, CEILCalculation)
If you do not want to modify the table structure, you can put a BEFORE INSERT TRIGGER
on the table and check for validity over there. 如果您不想修改表结构,可以在表上放置一个
BEFORE INSERT TRIGGER
,并检查那里的有效性。
http://www.techonthenet.com/oracle/triggers/before_insert.php http://www.techonthenet.com/oracle/triggers/before_insert.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.