开发者

SQL constraint minvalue / maxvalue?

开发者 https://www.devze.com 2022-12-11 06:03 出处:网络
Is 开发者_如何学Gothere a way to set a SQL constraint for a numeric field that min value should be 1234 and max value should be 4523?SQL Server syntax for the check constraint:

Is 开发者_如何学Gothere a way to set a SQL constraint for a numeric field that min value should be 1234 and max value should be 4523?


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


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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消