首頁 > 軟體

SQL中建立儲存過程

2022-11-15 14:02:11

建立SQL儲存過程需要使用到的語法

- 建立儲存過程

CREATE 儲存過程的名稱(引數)
BEGIN
...需要執行的SQL語句
END

- 呼叫

CALL 儲存過程的名稱(引數)

個人看法,這就是一個函數...

無引數

CREATE PROCEDURE p_student_select()
BEGIN 
SELECT * FROM student;
END

CALL p_student_select()

帶參

# out其實就是cpp裡的參照變數,in就是值傳遞
CREATE PROCEDURE p_count(OUT count int)
BEGIN
SELECT COUNT(*) into count FROM student;
END

set @num = 10;	# 定義變數
CALL p_count(@num);		#我的資料有11條
SELECT @num as num;		#這裡的num已經是11了

--這個就是一個呼叫引數的函數
CREATE PROCEDURE p_studnt_selectById(in id int)
BEGIN
SELECT * FROM student WHERE studentNo = id;
END

CALL p_studnt_selectById(4)

兩個引數

#兩個引數是一樣的用法
CREATE PROCEDURE p_result_test(out num int, in id int)
BEGIN
SELECT COUNT(*) INTO num FROM result WHERE studentNo = id;
END

set @num = 0;
CALL p_result_test(@num, 3);
SELECT @num as num

declare關鍵字的使用

# declare的作用是用來定義變數

CREATE PROCEDURE p5()
BEGIN
DECLARE studentName VARCHAR(10);	#建立了一個變數
set @studentName = 'HELLO';		#給變數賦值
END

CALL p5();
SELECT @studentName
-- 說明了declare定義的變數可以在外部直接呼叫

IF語句

#if語句沒啥說的,程式碼直接能看懂
CREATE PROCEDURE p6(in id int)
BEGIN
IF(id = 0) THEN
	SELECT * FROM student;
ELSE
	SELECT * FROM teacher;
END IF;
END

case語句

#看程式碼...
CREATE PROCEDURE p7(in tab VARCHAR(10))
BEGIN
CASE tab
	WHEN 'student' THEN
		SELECT * FROM student;
	WHEN 'teacher' THEN
		SELECT * FROM teacher;
END CASE;
END

loop語句

CREATE PROCEDURE p9(IN id INT)
BEGIN
addloop: LOOP
	set id = id + 1;
	SELECT id;
	IF id > 10 THEN
		LEAVE addloop;
	ELSE
		SELECT * FROM student; 
	END IF; 
END LOOP addloop;

END

repeat

CREATE PROCEDURE p10(in count int)
BEGIN
REPEAT
	set count = count + 1;
	SELECT count;
UNTIL count > 10 END REPEAT;	#count >10跳出

END

while

CREATE PROCEDURE p11(in num int)
BEGIN
while num < 10 DO
	SELECT num;
	SET  num = num + 1; 
END WHILE;
END

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com