在 SQL Server 2005 中,如何设置整数列以确保值大于 0?
这可能是一个简单的答案,但我找不到它。 我有一个包含整数列的表,我想确保插入行时该列中的值大于零。 我可以在代码方面执行此操作,但认为最好在桌面上强制执行。
谢谢!
我上次的评论是错误的,现在一切都很好。
This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.
Thanks!
I was in error with my last comment all is good now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在列上使用检查约束。 IIRC 的语法如下所示:
正如下面的海报所说(感谢 Constantin),您应该在表定义之外创建检查约束并给它一个有意义的名称,以便很明显它适用于哪一列。
您可以从
sys.check_constraints
中的系统数据字典中获取检查约束的文本:You can use a check constraint on the column. IIRC the syntax for this looks like:
As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name so it is obvious which column it applies to.
You can get out the text of check constraints from the system data dictionary in
sys.check_constraints
:创建数据库约束:
您也可以有非常复杂的约束,涉及多个列。 例如:
Create a database constraint:
You can have pretty sophisticated constraints, too, involving multiple columns. For example:
我相信您想向表字段添加一个 CONSTRAINT:
可选的 NOCHECK 用于防止将约束应用于现有的数据行(可能包含无效数据)& 允许添加约束。
I believe you want to add a CONSTRAINT to the table field:
That optional NOCHECK is used to keep the constraint from being applied to existing rows of data (which could contain invalid data) & to allow the constraint to be added.
创建表时添加
CHECK
约束Add a
CHECK
constraint when creating your table您可以更改表并添加新的约束,如下所示。
you can alter your table and add new constraint like bellow.