SQL constraint minvalue / maxvalue?

随声附和 提交于 2019-11-26 16:30:54

问题


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?


回答1:


SQL Server syntax for the check constraint:

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),
    ...
)



回答2:


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.




回答3:


If you are using SQL Server, you want to use a CHECK constraint like this:

CREATE TABLE foo (
  someint INT NOT NULL CHECK (someint >= 1234 AND someint <= 4523)
)



回答4:


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.

A Check Constraint windows pops up with a new empty constraint named 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.




回答5:


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);


来源:https://stackoverflow.com/questions/1736630/sql-constraint-minvalue-maxvalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!