SQL 约束最小值/最大值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1736630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL constraint minvalue / maxvalue?
提问by Shimmy Weitzhandler
Is there a way to set a SQL constraint for a numeric field that min value should be 1234 and max value should be 4523?
有没有办法为最小值应为 1234 且最大值应为 4523 的数值字段设置 SQL 约束?
回答by yfeldblum
SQL Server syntax for the check
constraint:
SQL Server的语法的check
约束:
create table numbers (
number int not null
check(number >= 1234 and number <= 4523),
...
)
create table numbers (
number int not null,
check(number >= 1234 and number <= 4523),
...
)
create table numbers (
number int not null,
constraint number_range_check
check(number >= 1234 and number <= 4523),
...
)
回答by Jonathan Leffler
CREATE TABLE WhatEver
(
...
NumericField INTEGER NOT NULL CHECK(NumericField BETWEEN 1234 AND 4523),
...
);
Note that 'BETWEEN AND' provides a range inclusive of the quoted limit values.
请注意,“BETWEEN AND”提供的范围包括引用的限制值。
回答by steveschoon
If you are using SQL Server, you want to use a CHECK constraint like this:
如果您使用的是 SQL Server,您希望使用这样的 CHECK 约束:
CREATE TABLE foo (
someint INT NOT NULL CHECK (someint >= 1234 AND someint <= 4523)
)
回答by Fry Simpson
If you are using SQL Server by means of SQL Server Management Studio, the most convenient way to add a Check Constraint is to right click the Constraints folder in the tree view (Object Explorer) and then, from the popup menu, select New Constraint.
如果您通过 SQL Server Management Studio 使用 SQL Server,添加检查约束的最便捷方法是右键单击树视图(对象资源管理器)中的约束文件夹,然后从弹出菜单中选择新建约束。
A Check Constraint windows pops up with a new empty constraint named CK_tableName*
检查约束窗口弹出一个名为 CK_tableName* 的新空约束
You can edit such a proposed name, and insert the code of the check constraint in the Expression field.
您可以编辑这样的建议名称,并在“表达式”字段中插入检查约束的代码。
Then the new constraint appears in the Constraint folder (after you select the folder and hit the refresh icon) in Object Explorer and you can edit it right clicking it and selecting Modify from the popup menu.
然后新约束出现在对象资源管理器的约束文件夹中(在您选择文件夹并点击刷新图标后),您可以右键单击它并从弹出菜单中选择修改。
回答by Gabriel Borges Oliveira
FYI
供参考
When you need a constraint for a range of values:
当您需要一个值范围的约束时:
ALTER TABLE package_subscription ADD CONSTRAINT check_discount_amount CHECK (discount_amount BETWEEN 0.0000 AND 1.0000);