Mysql 存儲過程初識

来源:https://www.cnblogs.com/chenjieyouge/archive/2019/10/03/11619342.html
-Advertisement-
Play Games

存儲過程 認識 在一些編程語言中, 如pascal, 有一個概念叫"過程" procedure, 和"函數" function, 如VB中的sub. Java, Python, PHP, 沒有過程, 只有function. 過程(procedure) : 封裝了若幹條語句, 調用時, 這些封裝體執行 ...


存儲過程

認識

在一些編程語言中, 如pascal, 有一個概念叫"過程" procedure, 和"函數" function, 如VB中的sub. Java, Python, PHP, 沒有過程, 只有function.

過程(procedure) : 封裝了若幹條語句, 調用時, 這些封裝體執行.

函數(function): 是一個有返回值的 "過程" (ps: Python函數即可是過程, 也是是函數)

存儲過程(sql_procedure): 將若幹條sql封裝起來, 取一個名字, 即為過程, 把此過程存儲在資料庫中, 即存儲過程.

存儲過程-創建語法

-- 創建
create procedure procedureName()
begin
    SQL語句1;
    SQL語句2;.....
end

-- 調用
call procedureName();

第一存儲過程

helloWorld

-- 第一個存儲過程: 列印hello world
delimiter //
drop procedure if exists p1;
create procedure p1()
begin
    select "hello world!";
    select 1 + 1;
end //
delimiter ;

-- CALL 調用
call p1;
-- 查看: show procedure status;
show show procedure status;

效果

mysql> -- 第一個存儲過程: 列印hello world
delimiter //
drop procedure if exists p1;
create procedure p1()
begin
    select "hello world!";
    select 1 + 1;
end //
delimiter ;
Query OK, 0 rows affected (0.16 sec)

Query OK, 0 rows affected (0.16 sec)

mysql> call p1();
+--------------+
| hello world! |
+--------------+
| hello world! |
+--------------+
1 row in set (0.06 sec)

+-------+
| 1 + 1 |
+-------+
|     2 |
+-------+
1 row in set (0.21 sec)

Query OK, 0 rows affected (0.00 sec)

引入變數-declare 局部

存儲過程是可以編程的, 意味著可以用變數, 表達式, 控制結構來完成各種複雜的功能.

在存儲過程中, 用 declare 變數名 變數類型 [default 預設值].

-- 變數引入
drop procedure if exists p2;
delimiter //
create procedure p2()
begin
    declare age int default 18;
    declare height int default 180;
    -- concat 拼接輸出
    select concat("油哥的年齡是:", age, "身高是:", height);
end //
delimiter ;

call p2();

效果:

call p2();
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+-------------------------------------------------+
| concat("油哥的年齡是:", age, "身高是:", height) |
+-------------------------------------------------+
| 油哥的年齡是:18身高是:180                       |
+-------------------------------------------------+
1 row in set (0.10 sec)

Query OK, 0 rows affected (0.04 sec)

引入運算

在儲存過程中, 變數可以引入sql語句中合法的運算, 如 + - * /, 值的註意的是, 運算的結果,如何賦值給變數?

set 變數名 := expression 在存儲過程中的變數是一個局部變數.

set @變數名 := expression 用戶(會話)變數, 在存儲過程外面也能用, 類似"全局變數".

declare 變數名 變數類型 [default value] 用在過程中的局部變數, 聲明類型.

關於賦值 = 與 := 的區別

:=

  • 標準的賦值符號, 在任何場景都是賦值.

=

  • 只在 set 和 update 是和 := 一樣是賦值, 其他都是等於的作用.
drop procedure if exists p3;
delimiter //
create procedure p3()
begin
    declare age int default 18;

    select concat("現在的年齡是:", age);
    -- 變數運算,賦值
    set age := age + 10;
    select concat("10年後, 年齡變成了:", age); 
end //
delimiter ;
-- out
mysql> call p3();
+------------------------------+
| concat("現在的年齡是:", age) |
+------------------------------+
| 現在的年齡是:18              |
+------------------------------+
1 row in set (0.11 sec)

+------------------------------------+
| concat("10年後, 年齡變成了:", age) |
+------------------------------------+
| 10年後, 年齡變成了:28              |
+------------------------------------+
1 row in set (0.25 sec)

控制結構 if - then - else - end if;

-- 語法
if condition then
    statement_01
else
    statement_02
end if;
drop procedure if exists p4;
delimiter //
create procedure p4()
begin
    declare age int default 18;
    
    if age >= 18 then
        select "已成年";
    else
        select "未成年";
    end if;
end //
delimiter ;

-- test
call p4();

-- out
+--------+
| 已成年 |
+--------+
| 已成年 |
+--------+
1 row in set (0.09 sec)

Query OK, 0 rows affected (0.00 sec)

存儲過程傳參

存儲過程的括弧里, 可以聲明參數, 語法是 [in / out / inout] 參數名 參數類型

in 表示往procedure裡面傳參數; out 表示其往外發射參數

-- 輸入矩形的 width, height 求矩形的面積
drop procedure if exists p5;
delimiter //
create procedure p5(width int, height int)
begin
    select concat("面積是:", width * height);
    if width > height then
        select "比較胖";
    elseif width < height then
        select "比較瘦";
    else
        select "方的一痞";
    end if;
    
end //
delimiter ;

call p5(12, 13);

-- out
call p5(12, 13);
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.05 sec)

+-----------------------------------+
| concat("面積是:", width * height) |
+-----------------------------------+
| 面積是:156                        |
+-----------------------------------+
1 row in set (0.11 sec)

+--------+
| 比較瘦 |
+--------+
| 比較瘦 |
+--------+
1 row in set (0.22 sec)

Query OK, 0 rows affected (0.01 sec)

流程式控制制 while , repeat, loop

任何編程語言, 只要具備控制結構順序, 選擇, 迴圈就足夠了.

感覺就是, 編程其實思路都是一樣的, 只是不同語言的應用場景, 語法特性有差別而已, 思路都是一樣的.

-- while 迴圈 語法
WHILE search_condition DO
    statement_list
END WHILE [end_label]
-- 求 1+2+3+...100
drop procedure if exists p6;
delimiter //
create procedure p6()
begin
    declare total int default 0;
    declare num int default 0;
    -- while 迴圈
    while num <= 100 do
        set total := total + num;
        set num := num + 1;
    end while;
    -- 最後輸出結果
    select concat("1+2+...100的值是: ", total) as 'sum';
end //
delimiter ;

call p6();

-- out
call p6();
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.05 sec)

+------------------------+
| sum                    |
+------------------------+
| 1+2+...100的值是: 5050 |
+------------------------+
1 row in set (0.09 sec)

改進: 求 1+2+....N 的和, 這裡引入參數 IN

-- 求 1+2+3+...N
drop procedure if exists p7;
delimiter //
-- 傳入參數 in類型
create procedure p7(in n int)
begin
    declare total int default 0;
    declare num int default 0;
    -- while 迴圈
    while num <= n do
        set total := total + num;
        set num := num + 1;
    end while;
    -- 最後輸出結果
    select concat("1+2+.. 的值是: ", total) as 'sum';
end //
delimiter ;

call p7(10000);

-- out
call p7(10000);
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+-------------------------+
| sum                     |
+-------------------------+
| 1+2+.. 的值是: 50005000 |
+-------------------------+
1 row in set (0.14 sec)

out 型參數

drop procedure if exists p8;
delimiter //
create procedure p8(in n int, out total int)
begin
    -- 聲明一個局部(臨時)變數num來存儲 1..n
    declare num int default 0;
    -- while 
    while num <= n do
        set total := total + num;
        set num := num + 1;
    end while;
    -- select concat("the sum is:", total)
end //
delimiter ;

-- 區別: 沒有在 begin ..end 中聲明 total變數, 而是在 OUT類型的參數中.
-- out: 傳入一個變數去接收輸出
call p8(100, @cj); 

mysql> select @cj;
+------+
| @cj  |
+------+
| NULL |
+------+
1 row in set (0.10 sec)

NULL 的特殊性, 導致沒有正確輸出 , 解決: 給total 一個預設值即可

mysql> select null = null;
+-------------+
| null = null |
+-------------+
| NULL        |
+-------------+
1 row in set (0.09 sec)

mysql> select 1 + null;
+----------+
| 1 + null |
+----------+
| NULL     |
+----------+
1 row in set (0.05 sec)
-- 解決null的特殊性
drop procedure if exists p8;
delimiter //
create procedure p8(in n int, out total int)
begin

    -- 先聲明一個局部(臨時)變數num來存儲 1..n
    declare num int default 0;
    -- 再給out變數一個預設值即可(順序是先declare哦)
    set total := 0;
    -- while 
    while num <= n do
        set total := total + num;
        set num := num + 1;
    end while;
end //
delimiter ;

-- 區別: 沒有在 begin ..end 中聲明 total變數, 而是在 OUT類型的參數中.

-- out: 傳入一個變數去接收輸出的total變數值
call p8(100, @theSum);
select @theSum;

-- out

mysql> call p8(100, @theSum);
Query OK, 0 rows affected (0.00 sec)

mysql> select @theSum;
+---------+
| @theSum |
+---------+
|    5050 |
+---------+
1 row in set (0.11 sec)

小結參數 in 和 out 和 inout

  • in 類型, 是要輸入一個值進去, 傳遞給procedure的in類型變數(傳值)
  • out類型, 是要輸入一個變數進去, 接收procedure的out類型變數的值
  • inout類型, 傳入值進入和傳入變數接收值出來
-- inout 類型
drop procedure if exists p9;
delimiter //
create procedure p9(inout age int)
begin
    set age := age + 20;
end //
delimiter ;

-- call 的時候, inout, 首先要定義一個"全局(會話變數)", 然後再傳入
-- out
mysql> set @age := 100;
Query OK, 0 rows affected (0.00 sec)

mysql> call p9(@age);
Query OK, 0 rows affected (0.00 sec)

mysql> select @age;
+------+
| @age |
+------+
|  120 |
+------+

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、檢查環境 2、配置yum源 mkdir /iso #創建掛載點 mount /dev/cdrom /iso #掛載光碟到掛載點 ls /iso #查看掛載是否成功 cd /etc/yum.repos.d/ #進入yum源目錄 rm -fr *.repo #刪除官方源 vim iso.repo # ...
  • RAID是將把好幾塊硬碟通過一定組合方式把它組合起來,成為一個新的硬碟陣列組,從而使它能夠達到高性能硬碟的要求. ...
  • MySQL複習值代碼知識點 一. 創建資料庫 create database 資料庫名; 二. 刪除資料庫 drop database 資料庫名; 三. 選擇相應的資料庫 use 資料庫名; 四. 創建表 create table table_name( id integer primary key ...
  • 外鍵(Foreign Key) 如果今天有一張表上面有很多職務的信息 我們可以通過使用外鍵的方式去將兩張表產生關聯 這樣的好處能夠節省空間,比方說你今天的職務名稱很長,在一張表中就要重覆的去寫這個職務的名字,很浪費空間;除此之外也能起到一個約束的作用。 像department就是外鍵。 執行代碼: ...
  • Mysql 流程式控制制 認識 從我目前所接觸的編程語言,C, R, VB, Python, Javascript...,來看, 無非就是 變數, 表達式, 流程式控制制(順序, 分支, 迴圈), 封裝了一些更高級的數據結構而已 , 區別在於應用場景和語言特性, 其實邏輯都是相同的, 唯手熟爾. 選擇結構 ...
  • 說明:《數學分析原理》指 г.м.菲赫金哥爾茨 著《數學分析原理》(第一卷 第九版)高等教育出版社 整數和分數統稱為有理數。有理數域不能完全滿足數學定義的需求,比如人們無法將一個邊長為1的正方形的對角線長度表示為有理數,也即 沒有一個其平方能等於2的有理數 ${\frac{{p}}{{q}}}$($ ...
  • JDBC的入門 搭建開發環境 編寫程式,在程式中載入資料庫驅動 建立連接 創建用於向資料庫發送SQL的Statement對象 從代表結果集的ResultSet中取出數據 斷開與資料庫的連接,並釋放相關資源 新建一個測試用的資料庫jdbctest 下載資料庫驅動並導入到jdbc項目 下載地址:http ...
  • 高強度訓練第十九天總結: 為什麼要用索引 通過創建唯一性索引可以保證資料庫表中每一行數據的唯一性 可以大大加快數據的檢索速度(大大減少了檢索的數據量),這也是創建索引最主要的原因。 幫助伺服器避免排序和臨時表 將隨機IO變為順序IO 可以加速表和表之間的連接,特別是在實現數據的參考完整性方面特別有意 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...