資料庫完整性——MySQL新增約束
阿新 • • 發佈:2021-01-08
一. 實驗環境:
1、 作業系統:window10
2、 MySQL 5.7
二. 實驗內容與完成情況:
1.建立一個教工表teacher(tno,tname,tadd,telphone,tsex,id),將教工號tno設為主鍵,性別預設值為“男”:
create table teacher(
tno char(7) primary key,
tname char(10),
tadd char(10),
telphone char(10),
tsex char(2) default '男',
id int
)engine =InnoDB
2.根據教工表teacher完成以下任務。
- 設定telphone預設值為00000000:
alter table teacher modify telphone char(10) default '00000000';
2) 設定tsex的check檢查約束為:輸入值只能為“男”或“女”:
ALTER TABLE teacher modify tsex enum('男','女') default '男' ;
3) 設定id的位數為15位或18位,每位都是數字:
先建立一個判斷數字的函式IsNum:
delimiter $$
drop function if exists IsNum $$
create function IsNum(str varchar(25))
returns int
begin
declare iResult int default 0;
if isnull(str) then return 0;end if;
if str='' then return 0;end if;
select str REGEXP '^[0-9]*$' into iResult;
if iResult=1 then
return 1;
else
return 0;
end if;
end $$
alter table teacher modify id char (20);
delimiter //
create trigger TR_ID_IN after insert on teacher
for each row
begin
if (length(new.id)!=15 and length(new.id)!=18) or (IsNum(new.id)!=1) then
signal sqlstate '45000'
set message_text='Insert Error';
end if;
end;//
delimiter ;
delimiter //
create trigger TR_ID_UP after update on teacher
for each row
begin
if (length(new.id)!=15 and length(new.id)!=18) or (IsNum(new.id)!=1) then
signal sqlstate '45000'
set message_text='Update Error';
end if;
end;//
delimiter ;