How to set gender constraints in SQL Server?

In SQL Server, you can use check constraints to enforce gender constraints. The specific steps are as follows:

  1. Create a table with a gender column.
CREATE TABLE Person (
    ID INT PRIMARY KEY,
    Name VARCHAR(50),
    Gender CHAR(1) CHECK (Gender IN ('M', 'F'))
);

Please note that the data type of the column Gender in the above code is CHAR(1), and a CHECK constraint is used to restrict input to only ‘M’ or ‘F’.

  1. If the gender does not meet the constraints when inserting data, an error will be triggered.
INSERT INTO Person (ID, Name, Gender) VALUES (1, 'John', 'M'); -- 正确
INSERT INTO Person (ID, Name, Gender) VALUES (2, 'Jane', 'F'); -- 正确
INSERT INTO Person (ID, Name, Gender) VALUES (3, 'Alex', 'O'); -- 错误,超出约束条件

After setting the gender constraint as explained above, only ‘M’ or ‘F’ can be entered when inserting data. Any other value inputted will trigger a constraint error.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds