任務描述
本關任務:
jdxx數(shù)據(jù)表有四個字段,分別是省份(sf)、城市(cs)、區(qū)縣(qxmc)、街道(name)。
例如,查詢天心區(qū)(qxmc)的所有字段的值結果如圖所示
任務要求
建立存儲過程
tjdq(in sf varchar(10))
輸入省份的名稱,將該省份所有城市的所有地區(qū)的
鄉(xiāng)x、鎮(zhèn)z和街道jd和其他的個數(shù)插入到數(shù)據(jù)表dqtj中。
dqtj數(shù)據(jù)表已經(jīng)建立在數(shù)據(jù)庫中,有城市(cs),區(qū)縣名稱(qxmc)、縣(x)、街道(jd)、鎮(zhèn)(z)、其他(qt)六個字段。分別存儲指定省份的城市、區(qū)縣名稱和縣、街道、鎮(zhèn)、其他的個數(shù)。
以湖南省為參數(shù),調用tjdq過程后
dqtj數(shù)據(jù)表部分數(shù)據(jù)如圖所示
調用過程
以安徽省為參數(shù),調用過程
提示:該過程先要刪除dqtj數(shù)據(jù)表的所有數(shù)據(jù)
然后將指定省份的城市和區(qū)縣的唯一信息值存入游標
然后將游標的各條信息依次取出循環(huán),根據(jù)游標中的城市和區(qū)縣名稱,在jdxx數(shù)據(jù)表查出對應的鄉(xiāng)、街道、鎮(zhèn)和其他的個數(shù),然后插入到dqtj數(shù)據(jù)表。
相關知識
聲明游標
命令格式:
DECLARE 游標名 CURSOR FOR select語句
打開和關閉游標
命令格式:
open 游標名
close 游標名
讀取游標信息
命令格式:
FETCH 游標名 INTO var1,var2[,…]
將游標聲明時的查詢結果逐條存放在變量中
每執(zhí)行一次fetch將指針指向下一條結果
變量必須在聲明游標前定義文章來源:http://www.zghlxwxcb.cn/news/detail-422114.html
遍歷游標
文章來源地址http://www.zghlxwxcb.cn/news/detail-422114.html
代碼
use province;
#代碼開始
delimiter $$
create procedure tjdq(in sm varchar(10))
begin
declare flag int default 1;
declare city varchar(10);
declare qx varchar(10);
declare jd int;
declare x int;
declare z int;
declare qt int;
declare dq cursor for select distinct cs, qxmc from jdxx where sf = sm;
declare continue handler for not found set flag = 0;
delete from dqtj;
open dq;
fetch dq into city, qx;
while flag = 1 do
select count(*) from jdxx where cs = city and qxmc = qx and name like "%街道" into jd;
select count(*) from jdxx where cs = city and qxmc = qx and name like "%鄉(xiāng)" into x;
select count(*) from jdxx where cs = city and qxmc = qx and name like "%鎮(zhèn)" into z;
select count(*) from jdxx where cs = city and qxmc = qx and name not like "%鎮(zhèn)" and name not like "%街道" and name not like "%鄉(xiāng)" into qt;
insert into dqtj values(city, qx, x, jd, z, qt);
fetch dq into city, qx;
end while;
close dq;
end $$
delimiter ;
call tjdq("安徽省");
#代碼結束
select * from dqtj;
到了這里,關于數(shù)據(jù)庫實驗 | 第5關:使用游標的存儲過程的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!