简体   繁体   中英

sql - add a column to table whose value is greater than specified value

CREATE TABLE Article
(
     ArCode CHAR(5) LIKE A% PRIMARY KEY, 
     ArName VARCHAR2(30) NOT NULL,  
     Rate NUMBER(8, 2), 
     Quantity NUMBER(4) >= 0 DEFAULT 0, 
     Class CHAR(1) CHECK(Class IN('A', 'B', 'C'))
);

Here I want to add a column named Quantity whose values must be greater than or equal to zero or default to zero. Also, a column ArCode which should start with A ; Is the above code syntactically correct?

It probably depends on your db backend. But I'd say you would need a CHECK function like for the Class column.

My guess (untested as I don't have an SQL db handy right now) would be something like this:

CREATE TABLE Article
(
     ArCode CHAR(5) PRIMARY KEY CHECK (ArCode LIKE 'A%'),
     ArName VARCHAR2(30) NOT NULL,  
     Rate NUMBER(8, 2), 
     Quantity NUMBER(4) DEFAULT 0 CHECK (Quantity >= 0), 
     Class CHAR(1) CHECK(Class IN('A', 'B', 'C'))
);

You didn't specify the RDBMS that you're using - but in general, in ANSI SQL you can use check constraints to limit the allowed values.

You can find some general information about it in this link: https://en.wikipedia.org/wiki/Check_constraint

and you can look for your specifics for the RDBMS that you're using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM