为oracle中的列添加分数约束
我使用的是oracle 10gr2。我试图对名为“分数”的列强制实施约束,以便只能输入分数。
更具体地说,格式应在分子中包含一位数字,在分母中包含一位数字,这样用户只能输入分数,例如 3/4
、2/5
代码>,或<代码>7/8。该列仅接受数字作为输入。谁能告诉我要使用的 SQL?
I am using oracle 10gr2. I am trying to enforce a constraint on a column called "score" such that only fractions can be entered.
More specifically, a the format should contain one digit in the numerator and one digit in the denominator, such that a user can only enter a fraction such as 3/4
,2/5
,or 7/8
. The column only accepts numbers as the input. Can anyone show me the SQL to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确,我认为正确的方法是将数据存储在两列中。如果顶部数字是用户在某个问题上的实际分数,而底部数字是可能的分数(这听起来像是您正在做的事情),那么这尤其有意义。这将使您能够使用 Oracle 中内置的数字函数而不是解析字符串来汇总分数。然后,使用
NUMBER(1,0)
类型将每列的大小限制为 (0-9)。例如:如果分数列中已有数据,则可以将值从该列复制到新列中。最后,您删除该列。
另外,我会搜索“Oracle 小于约束”,因为您可能不希望实际分数超过可能的分数,并且可能会执行类似的约束以使可能的分数大于零。
If I understand correctly, I think the proper way to do this is to store the data in two columns. This especially makes sense if the top number is a user's actual score on a problem and the bottom number is the possible score, which is what it sounds like you are doing. This will enable you to sum up scores using the built in number functions in Oracle rather than parsing strings. Then, you limit the size of each column to (0-9) by using the type
NUMBER(1,0)
. For example:If you have data in the score column already, you then copy your values over from there to your new columns. Finally, you drop that column.
Also, I'd do a search on "Oracle less than constraint", because you probably don't want the actual score to exceed the possible, and probably do a similar constraint to make the possible score greater than zero.
我没有要测试的 Oracle 实例,但这里有一些指针和一些未经测试的代码:
指针:
请阅读此处 可能会使用 REGEX_LIKE ,它看起来像这样:
需要注意的是:上面的正则表达式将认为
1/0
有效,但我们都知道它不应该如此。有一种方法可以了解分数的第二部分。阅读正则表达式链接,您需要知道的一切都在那里。I don't have an instance of Oracle to test against, but here are some pointers and some untested code:
Pointers:
You are probably going to use
REGEX_LIKE
and it would look like something like this:A caveat:
1/0
will be considered valid by the Regex above, but we all know it should not be. There's a way you can know about the second part of the fraction. Read the Regex link, everything you need to know is there.有效值的范围是有限且小的。因此,请考虑将它们全部放入一个表中,使用固定宽度的文本列(即三个字符)并创建对此查找表的外部引用,而不是
CHECK
约束。The domain of valid values is finite and small. Therefore, consider putting them all in a table, using a fixed width text column (i.e. three characters) and a create a foreign reference to this lookup table, rather than a
CHECK
constraint.