目錄
- 什么是存儲函數
- 存儲函數和存儲過程的區別
- 創建存儲函數
- 調用存儲函數
- 刪除存儲函數
- 定義與實現完整性約束
1、什么是存儲函數
存儲函數與存儲過程一樣,是由SQL語句和過程式語句組成的代碼片段
2、存儲函數和存儲過程的區別
存儲函數 | 存儲過程 |
不能擁有輸出參數 | 可以擁有輸出參數 |
可以直接調用存儲函數,不需要call語句 | 需要call語句調用存儲過程 |
必須包含一條return語句 | 不允許包含return語句 |
3、創建存儲函數
示例:在數據庫中mysql_test中創建一個存儲函數,要求該函數能根據給定的客戶id號返回客戶的性別,如果數據庫中沒有給定的客戶id號,則返回"沒有該客戶".
用例表:customer(cust_id,cust_sex,cust_name); ->use mysql_test; ->delimiter $$ ->create function fn_name(cid int) //創建一個存儲函數,題目要求我們輸入id號判斷性別,所以是int -> returns char(2) //返回性別,所以char類型 -> deterministic //為了提高where子句的性能加的 ->begin //接下來要寫函數體了 -> declare sex char(2); //聲明局部變量用來裝性別 -> select cust_sex into sex from customer //把這個性別放進局部變量 -> where cust_id = cid; //判斷id相符 -> if sex is null then //判斷這個局部變量性別對應的屬性 -> return(select '沒有該客戶'); -> else if sex = '女' then -> return(select "女"); -> else return(select "男"); -> end if; //用來結束else if的語句 -> end if; //用來結束if的語句 ->end $$ //用來結束存儲函數
3、調用存儲函數
//調用存儲函數,舉上面的例子
customer表的數據
(1,"男","zhangsan")
(2,"女","wangwu")
(3,"女","lisi")
(4,null,"wowo")
這里我有4條數據
->select fn_name(1)$$
->男 //輸出結果
->select fn_name(2)$$
->女 //輸出結果
->select fn_name(4)$$
->null //輸出結果
4、刪除存儲函數
->drop function if exists fn_name $$ //指定要刪除的存儲函數的名稱
5、定義與實現完整性約束
示例:在數據庫mysql_test中創建一個商品訂單表orders,該表包含訂單號order_id,商品名order_product,商品類型order_product_type,客戶id號cust_id,
訂購時間order_date,價格order_price,數量order_amount。要求商品訂單表orders中的所有訂購客戶信息均已在表costomers中記錄在冊 ->use mysql_test ->cretate table orders ->( -> order_Id int not null auto_increment, -> order_product char(50) not null, -> cust_id int not null, -> order_date datetime not null, -> order_price double not null, -> order_amount int not null, -> primary key(order_id), -> foreign key(cust_id) -> references customers(cust_id) -> on delete restrict -> on update restrict ->); //restrict 限制策略 //cascade 級聯策略 //set null 置空策略 //no action 不采取實施策略