note_SQL_PL/SQL基本结构

本文介绍了PL/SQL的基本结构,包括条件结构、循环结构、游标使用、存储过程及包的概念。通过示例详细解释了如何使用这些结构来实现数据库编程。

PL/SQL 的基本结构

 

文本框: /*----------------------------General Structure-------------20100314*/DECLARE/*Declarative section - PL/SQL variables, types, cursors, and loal subprograms go here. *//*申明部分 */BEGIN/*Executable section - procedural and SQL statements go here.   This is the main section of the block and the only one that is required.*//*代码段*/EXCEPTION/*Exception handling section - error-handling statements go here.*//*异常处理*/END;

PL/SQL 的基本结构示例

文本框: /*----------------------------UPDATE TABLE------------------20100314*/DECLARE	/*Declare variables which will be used in SQL statements*/	/*定义了变量类型和赋值*/	v_NewMajor VARCHAR2(10) := 'History';	v_FirstName VARCHAR2(10) := 'Scott';	v_LastName VARCHAR2(10) := 'Urman';BEGIN	/*Update the student table*//*更新表*/	UPDATE students		SET major = v_NewMajor		WHERE first_name = v_Firstname		AND last_name = v_LastName;	/*Check to see if the record was found, If not, then we need to insert this record*//*检验where语句是否找到更新的行*/	IF SQL%NOTFOUND THEN		/*没有找到更新的行,插入该行*/		INSERT INTO student (ID, first_name, lastname, major)			VALUES(student_sequence.NEXTVAL, v_FirstName, v_LastName, v_NewMajor)	END IF;END;

PL/SQL 的异常处理段的基本结构示例

文本框: /*----------------------------Exception Structue------------20100314*/DECLARE	v_ErrorCode NUMBER; --Code for the error	v_ErrorMsg VARCHAR2(200); -- Message text for the error	v_CurrentUser VARCHAR2(8); -- Current Datase User 	v_Information VARCHAR2(100); -- Information about the errorBEGIN/*Code that processes some data here */EXCEPTION	WHERE OTHERS THEN	-- Assign values to the log variables, using built-in functions.	-- 使用内部函数对错误进行日志记录	v_ErrorCode := SQLCODE;	v_ErrorMsg := SQLERRM;	v_CurrentUser := USER;	v_Information := 'Error encounted on '||TO_CHAR(SYSDATE)||'by database user'||v_CurrentUser;	-- Insert the log message into log_table.	INSERT INTO log_table (code, message, info)		VALUES(v_ErrorCode, v_ErrorMsg, v_Information);END;

用户自定义类型 TYPE User-Type IS RECORD()

 

文本框: /*----------------------------User-Defined Data Type--------20100314*/DECLARE	//定义	TYPE t_StudentRecord IS RECORD(	FirstName VARCHAR2(10),	LastName VARCHAR2(10),	CurrentCredits NUMBER(3)	);	//变量声明	v_Student t_StudentRecord;  

 

条件结构 IF。。。ELSIF。。。ELSE。。。ENDIF;

 

文本框: /*--------------------------- IF-ELSE-----------------------20100314*/DECLARE	v_TotalStudent NUMBER;BEGIN	-- Retrieve the total number of students from the database	SELECT COUNT(*)		INTO v_TotalStudents		From Students;	-- Based on this value, insert the appropriate row into temp_table	IF v_TotalStudents = 0 THEN		INSERT INTO temp_table (char_col)			VALUES('There are no students registered');	ELSIF v_TotalStudnets < 5 Then 		INSERT INTO temp_table (char_col)			VALUES('There are only a few students registered');	ELSIF v_TotalStudnets < 10 Then 		INSERT INTO temp_table (char_col)			VALUES('There are a little more students registered');	ELSE v_TotalStudnets < 5 Then 		INSERT INTO temp_table (char_col)			VALUES('There are many students registered');	END IF;END;

 

循环结构 LOOP…END LOOP

 

文本框: /*----------------------------LOOP-EXIT---------------------20100314*/DECLARE	v_LoopCounter BINARY_INTEGER := 1;BEGIN	LOOP		INSERT INTO temp_table (num_col)			VALUES(v_LoopCounter);		v_LoopCount := v_Loop + 1		EXIT WHEN v_LoopCount = 50	END LOOP;END;

循环结构 FOR...END LOOP

 

文本框: /*----------------------------LOOP-FOR----------------------2010314*/DECLARE	v_LoopCounter BINARY_INTEGER := 1;BEGIN	FOR v_LoopCounter IN 1..50 LOOP		INSERT INTO temp_table (num_col)			VALUES(v_LoopCounter);	END LOOP;END;
        

 

游标 CURSOR

游标用于指向表中的一行记录

 

文本框: /*----------------------------Cursor------------------------20100314*/			DECLARE	v_FirstName VARCHAR2(20);	v_LastName VARCHAR2(20);	-- Cursor declaration. This defines the SQL statments to return the rows.	/*定义游标的范围*/	CURSOR c_Students IS		SELECT first_name, last_name			From students;BEGIN	-- Begin cursor processing	-- 打开游标	OPEN c_Students;-	在游标内进行循环	LOOP		-- Retrieve one row		-- 取出游标中的数据		FETCH c_Students INTO v_FirstName, v_LastName;		-- Exit the loop after all rows have been retrieved.		-- 无法找到下个游标时 循环结束		EXIT WHEN c_Student%NOTFOUND;		/* Process data here */	END LOOP;	-- End processing	//关闭游标	CLOSE c_Students;END;

存储过程,编译完成并存储在数据库中,目的是为了被调用

 

存储过程如下

文本框: /*----------------------------Procedure---------------------20100314*/CREATE OR REPLACE PROCEDURE PrintStudents(	p_Major IN students.major%TYPE) AS	CURSOR c_Students IS		SELECT first_name, last_name			FROM students			WHERE major = p_Major;		BEGIN			FOR v_StudentRec IN c_Student LOOP				DBMS_OUTPUT.PUT_LINE(v_StudentRec.first_name||' '||v_StudentRec.last_name);			END LOOP;		END;

调用过程如下:

文本框: SQL> 	BEGIN				PrintStudents('Computer Science');		END;

返回结果如下:

                            文本框: Scott SmithJoanne JunebugShay Shariatpanahy

 

包:为了将相关的程序、变量封装到一个包中.

包括两个部分:规范和主体

创建包的规范

文本框: /*----------------------------Package-----------------------20100314*/CREATE OR REPLACE PACKAGE RoomPkg As		-- 函数声明PROCEDURE NewRoom(		p_Building rooms.building%TYPE,		p_RoomNum rooms.room_number%TYPE,		p_NumSeats rooms.number_seats%TYPE,		p_Description rooms.description%TYPE);	PROCEDURE DeleteRoom(		p_RoomID IN rooms.room_id%TYPE);	END RoomPkg;

创建包的主体

文本框: CREATE OR REPLACE PACKAGE BODY RoomPkg AS	-- 函数实现	PROCEDURE NewRoom(		p_Building rooms.building%TYPE,		p_RoomNum rooms.room_number%TYPE,		p_NumSeats rooms.number_seats%TYPE,		p_Description rooms.description%TYPE) IS	BEGIN		INSERT INTO rooms			(room_id, building, room_number, room_seats, description)			VALUES			(room_sequence.NEXTVAL, p_Building, p_RoomNum, p_NumSeats, p_Description)		END NewRoom;		PROCEDURE DeleteRoom(		p_RoomID IN rooms.room_id%TYPE) IS	BEGIN		DELETE FROM rooms			WHERE room_id = p_RoomID;		END DeleteRoom;		END RoomsPkg;

 

集合:索引表,嵌套表,可变数组

 
 矩形标注: 不太懂什么意思?
 

文本框: /*----------------------------Collection--------------------20100314*/DECLARE	TYPE t_IndexBy IS TABLE OF NUMBER		INDEX BY BINARY_INTEGER;	TYPE t_Nested IS TABLE OF NUMBER;	TYPE t_Varray IS VARRAY(10) OF NUMBER;		v_IndexBy t_IndexBy;	v_Nested t_Nested;	v_Varray t_Varray;	BEGIN	v_IndexBy(1) := 1;	v_IndexBy(2) := 2;	v_Nested := t_Nested(1, 2, 3, 4, 5);	v_Varray := t_Varray(1, 2);END;
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值