環境情況:
表1:residential_building,住宅樓表:id,community(所屬社群),countfloor(樓層數),countunit(單元數),counthomesinunit(每單元戶數),buildingname(樓棟名稱)
表2:homenumber,住戶表 id,buildingid(表1的id),homenumber
根據表1樓棟資訊,自動填充表2中每個房間號的內容
建立表1:
droptable
ifexists
residential_building;
create
table
residential_building(
id int
notnull auto_increment primary
key,
community
varchar(20
),countfloor
tinyint
,countunit
tinyint
,counthomesinunit
tinyint
,buildingname
varchar(50))
character
set utf8;
建立表2:
droptable
ifexists
building_home;
create
table
building_home(
id int
notnull auto_increment primary
key,
buildingid
int,
homenumber
varchar(50))
character
set utf8;
insert觸發器,表一插入內容時,表2根據樓層單元資訊生成房間號
droptrigger
ifexists
createhomenumber;
delimiter $$
create
trigger createhomename after insert
onresidential_building
foreach row
begin
declare
floor
intdefault1;
declare num int
default1;
declare roomnumber varchar(50) character
set utf8 default
"";
while
floor
<=
new.countfloor do
while num <= new.countunit *
new.counthomesinunit do
if num<
10then
set roomnumber = concat(new.buildingname,floor,"0
",num);
else
set roomnumber = concat(new.buildingname,floor
,num);
endif
;
insert
into building_home (buildingid,homenumber) values
(new.id,roomnumber);
set num = num +1;
endwhile
;
setfloor
=floor+1
;
set num =1;
endwhile
;end
$$delimiter ;
del觸發器,當表一中樓棟被刪除時,表2相應記錄被刪除
droptrigger
ifexists
delhomenumber;
delimiter $$
create
trigger delhomenumber after delete
onresidential_building
foreach row
begin
delete
from building_home where buildingid =
old.id;
end$$
delimiter ;
update 觸發器,當表1中樓棟資訊被修改時,表2重新建立
droptrigger
ifexists
updateroomnumber;
delimiter $$
create
trigger updateroomnumber after update
onresidential_building
foreach row
begin
declare
floor
intdefault1;
declare num int
default1;
declare roomnumber varchar(50) character
set utf8 default
"";
delete
from building_home where buildingid =
old.id;
while
floor
<=
new.countfloor do
while num <= new.countunit *
new.counthomesinunit do
if num<
10then
set roomnumber = concat(new.buildingname,floor,"0
",num);
else
set roomnumber = concat(new.buildingname,floor
,num);
endif
;
insert
into building_home (buildingid,homenumber) values
(old.id,roomnumber);
set num = num +1;
endwhile
;
setfloor
=floor+1
;
set num =1;
endwhile
;end
$$delimiter ;
積分觸發器 mysql 觸發器的使用
將多個資料庫中的某列資料同步時需要用到mysql觸發器,以下可做參考,已簡單測試ok.修改紅棗的積分時觸發 drop trigger if exists u hongzaocount delimiter create trigger u hongzaocount after update on ho...
mysql 觸發器 觸發器使用
1 了解什麼是觸發器?mysql 的觸發器和儲存過程一樣,都是嵌入到mysql的一段程式,觸發器 是由事件觸發某個動作,這些事件包括,插入 更新 刪除等語句。如果定義了觸發程式,觸發器就會觸發執行相應的操作。觸發器 trigger 是個特殊的儲存過程,不同的是,執行儲存過程要使用call語句來呼叫,...
觸發器 mysql觸發器
觸發器是一種特殊的儲存過程,它在插入 刪除或修改特定表中的資料時觸發執行,它比資料庫本身標準的功能有更精細和更複雜的資料控制能力。和儲存過程一樣,很少使用。1 觸發器的作用 2 建立觸發器 建立測試環境 mysql create database test db query ok,1 row aff...