The values of one column cannot be greater than another

喜夏-厌秋 提交于 2020-01-12 07:45:12

问题


I am trying to create a table where the values in one column can't be greater than the next column over. For example, I am creating the following table.

CREATE TABLE Price (
    PriceID INT PRIMARY KEY IDENTITY (1,1),
    OriginalPrice FLOAT NOT NULL,
    CurrentPrice FLOAT NOT NULL,
    Discount FLOAT,
    ShippingCost FLOAT NOT NULL,
    Tax FLOAT NOT NULL);

And Current Price cannot be greater than OriginalPrice.

So what I tried doing was

CurrentPrice FLOAT CHECK (CurrentPrice <= OriginalPrice) NOT NULL,

But this gives me the following error:

Msg 8141, Level 16, State 0, Line 1
Column CHECK constraint for column 'CurrentPrice' references another column, table 'Price'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

Am I not allowed to reference a column in the same table?


回答1:


Just change it to a table-level constraint instead of a column constraint.

CREATE TABLE Price (
    PriceID INT PRIMARY KEY IDENTITY (1,1),
    OriginalPrice FLOAT NOT NULL,
    CurrentPrice FLOAT NOT NULL,
    Discount FLOAT,
    ShippingCost FLOAT NOT NULL,
    Tax FLOAT NOT NULL,
    CHECK (CurrentPrice <= OriginalPrice));

You can also add it after, e.g.

ALTER TABLE Price ADD CHECK (CurrentPrice <= OriginalPrice);
--or
ALTER TABLE Price ADD CONSTRAINT CK_Price_Current_vs_Original
    CHECK (CurrentPrice <= OriginalPrice);


来源:https://stackoverflow.com/questions/13390490/the-values-of-one-column-cannot-be-greater-than-another

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