添加对值的约束,Mysql
Add constraint on values , Mysql
我的table
CREATE TABLE STUDENT (
BCN INT not null,
Stname varchar(50) not null,
Sex char(1) not null ,
primary key (BCN));
我想让 Sex 属性只接受两个值 'F' 或 'M'
我试过 'check' 子句:
Sex char(1) not null check (Sex = 'F' or Sex ='M' )
但不起作用,“性别”列仍然接受其他值,例如 ('B') !
我已经尝试创建触发器:
DELIMITER $$ CREATE TRIGGER SexCheck BEFORE INSERT ON student
FOR EACH ROW
BEGIN
IF Sex <> 'M' and Sex <> 'F' THEN
SIGNAL SQLSTATE '10000'
SET MESSAGE_TEXT = 'check constraint on Student.Sex failed';
END IF;
END$$
DELIMITER ;
它不会产生任何语法错误,但性别列甚至不接受任何值 'M' 或 'F'!它显示了我设置的消息。
我该如何解决?
-我正在使用 mysql workbench 6.3.
提前致谢
来自CREATE TABLE
:
The CHECK
clause is parsed but ignored by all storage engines.
第二个:
CREATE TRIGGER SexCheck BEFORE INSERT ON STUDENT
FOR EACH ROW
BEGIN
IF New.Sex NOT IN('F', 'M') THEN
SIGNAL SQLSTATE '10000'
SET MESSAGE_TEXT = 'check constraint on Student.Sex failed';
END IF;
END;
INSERT INTO STUDENT(Sex) VALUES ('B');
-- check constraint on Student.Sex failed
使用 MySQL ENUM 类型。 "An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time."
sex ENUM ('M', 'F')
我的table
CREATE TABLE STUDENT (
BCN INT not null,
Stname varchar(50) not null,
Sex char(1) not null ,
primary key (BCN));
我想让 Sex 属性只接受两个值 'F' 或 'M'
我试过 'check' 子句:
Sex char(1) not null check (Sex = 'F' or Sex ='M' )
但不起作用,“性别”列仍然接受其他值,例如 ('B') !
我已经尝试创建触发器:
DELIMITER $$ CREATE TRIGGER SexCheck BEFORE INSERT ON student
FOR EACH ROW
BEGIN
IF Sex <> 'M' and Sex <> 'F' THEN
SIGNAL SQLSTATE '10000'
SET MESSAGE_TEXT = 'check constraint on Student.Sex failed';
END IF;
END$$
DELIMITER ;
它不会产生任何语法错误,但性别列甚至不接受任何值 'M' 或 'F'!它显示了我设置的消息。
我该如何解决?
-我正在使用 mysql workbench 6.3.
提前致谢
来自CREATE TABLE
:
The
CHECK
clause is parsed but ignored by all storage engines.
第二个:
CREATE TRIGGER SexCheck BEFORE INSERT ON STUDENT
FOR EACH ROW
BEGIN
IF New.Sex NOT IN('F', 'M') THEN
SIGNAL SQLSTATE '10000'
SET MESSAGE_TEXT = 'check constraint on Student.Sex failed';
END IF;
END;
INSERT INTO STUDENT(Sex) VALUES ('B');
-- check constraint on Student.Sex failed
使用 MySQL ENUM 类型。 "An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time."
sex ENUM ('M', 'F')