`
kylinsoong
  • 浏览: 239645 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

PL/SQL Studing Notes

 
阅读更多

      As an extension of native sql, PL/SQL has Procedural Language features of programming languages. like block structures what it consists of blocks of code, can be nested within each other, can be stored in database and be reused, another advantage of PL/SQL is performance, PL SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic. In this section i will list a lot of demo code to demonstrate referenced theroy. For PL/SQL has Procedural language feature, so this section will list as: Variables, Constants, Records, Conditional Statements, Iterative Statements...

      In order to convenient Demo code, we create employee table and add some data to employee table as following:

create table employee(
emp_id number(10) primary key not null,
first_name varchar2(25),
last_name varchar2(25), 
dept varchar2(10),
salary  number(6)
);
insert into employee values(1111, 'Kylin', 'Soong', 'BPM', 8000); 
insert into employee values(1112, 'Kylin', 'Soong', 'BPM', 8000);
insert into employee values(1113, 'Kylin', 'Soong', 'BPM', 8000);
insert into employee values(1114, 'Kylin', 'Soong', 'BPM', 9000);
insert into employee values(1115, 'Kylin', 'Soong', 'BPM', 9000);
insert into employee values(1116, 'Kylin', 'Soong', 'BPM', 9000);

 

 

1. Variables

      Variables are kinds of Placeholders, which are temporary storage area. which are used to manipulate data during the execution of a PL SQL block. According to the scope of variables, variables can be classify into 2 kinds: Local variables which are declared in a inner block and cannot be referenced by outside Blocks; Global variables which are declared in a outer block and can be referenced by its itself and by its inner blocks. As following code block:

DECLARE
  var_num1 number;
  var_num2 number;
BEGIN
  var_num1 := 100;
  var_num2 := 200;   
  DECLARE
    var_mult number;
  BEGIN
    var_mult := var_num1 * var_num2;   
    dbms_output.put_line('var_mult '|| var_mult);  
  END;
  dbms_output.put_line('var_num1 '|| var_num1);  
  dbms_output.put_line('var_num2 '|| var_num2);  
END;
/ 

In the above code block, the variable 'var_mult' is declared in the inner block, so cannot be accessed in the outer block . The variables 'var_num1' and 'var_num2' can be accessed anywhere in the block.  

 

2. Constants

      As the name implies a constant is a value used in a PL/SQL Block that remains unchanged throughout the program. You must assign a value to a constant at the time you declare it. If you do not assign a value to a constant while declaring it and try to assign a value in the execution section, you will get a error.  The following code is a Constants usege demo:

DECLARE  
  salary_increase CONSTANT number(3) := 100; 
BEGIN   
  dbms_output.put_line (salary_increase); 
END; 
/

 

3. Records

1> What are records?

      Records are another type of datatypes which oracle allows to be defined as a placeholder. Records are composite datatypes, which means it is a combination of different scalar datatypes like char, varchar, number etc.  Each scalar data types in the record holds a value. A record can be visualized as a row of data. It can contain all the contents of a row.     

2> Declaring a record:

      To declare a record, you must first define a composite datatype; then declare a record for that type. If all the fields of a record are based on the columns of a table, we can declare the record as follows:

      record_name table_name%ROWTYPE

3> Passing Values To and From a Record

      When you assign values to a record, you actually assign values to the fields within it. The General Syntax to assign a value to a column within a record direclty is: record_name.col_name := value; 

DECLARE
  TYPE employee_type IS RECORD
  ( 
    employee_id number(5),  
    employee_first_name varchar2(25),  
    employee_last_name employee.last_name%type,  
    employee_dept employee.dept%type 
  );
  employee_salary employee.salary%type;
  employee_rec employee_type;
  employee_rec_all employee%ROWTYPE;
  var_emp_id number(6) := 1116;
  var_test_1 varchar2(25);
  var_test_2 varchar2(25);
BEGIN
SELECT first_name, last_name, dept INTO employee_rec.employee_first_name, employee_rec.employee_last_name, employee_rec.employee_dept from employee where emp_id = var_emp_id;
SELECT * INTO employee_rec_all from employee where emp_id = var_emp_id;
var_test_1 := employee_rec.employee_first_name;
dbms_output.put_line(var_test_1);
var_test_2 := employee_rec_all.first_name;
dbms_output.put_line(var_test_2);
commit;
END;
/

 The above code block define 2 Records: employee_rec and employee_rec_all, the red, bold sentence explain how to pass value to Record employee_rec  one by one; the blue bold sentence demonstrate how to pass values to Record employee_rec_all as a whole, and the black bold sentence show pass valurs from a Record.

 

4. Conditional Statements & Iterative Statements

      As a professional coding programmer, I do not write more about condition Statements and Iterative statements in this section, I will use condition Statements and Iterative statements in the following section directly.

 

5. Cursors

1> What are cursors?

      A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.

2> Two types of Cursor:

      Implicit cursors: These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed.

      Explicit cursors: They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.

3> Implicit Cursors:

DECLARE  
  var_rows number(5);
BEGIN
  UPDATE employee SET salary = salary + 1000;
  IF SQL%NOTFOUND THEN
     dbms_output.put_line('None of the salaries where updated');
  ELSIF SQL%FOUND THEN
     var_rows := SQL%ROWCOUNT;
     dbms_output.put_line('Salaries for ' || var_rows || ' employees are updated');  
  END IF;
  commit;
END;
/

      In the above PL/SQL Block, the salaries of all the employees in the ‘employee’ table are updated. If none of the employee’s salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for 1000 employees are updated' if there are 1000 rows in ‘employee’ table.

4> Explicit Cursors
  1) How to use Explicit Cursor?
    There are four steps in using an Explicit Cursor:
      DECLARE the cursor in the declaration section;
      OPEN the cursor in the Execution Section;
      FETCH the data from cursor into PL/SQL variables or records in the Execution Section;
      CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
  2) How to access an Explicit Cursor?
    These are the three steps in accessing the cursor:
      Open the cursor.
      Fetch the records in the cursor one at a time.
      Close the cursor.
5> Explicit Cursor Demo

DECLARE 
   emp_rec employee%ROWTYPE;
   CURSOR emp_cur IS SELECT * FROM employee WHERE salary > 5000;
BEGIN
   IF NOT emp_cur%ISOPEN THEN
     OPEN emp_cur;
   END IF;
   
   LOOP
     FETCH emp_cur INTO emp_rec;
     EXIT WHEN emp_cur%NOTFOUND;
     dbms_output.put_line (emp_rec.first_name || '  ' || emp_rec.last_name || '  ' || emp_rec.dept || '  ' || emp_rec.salary);
     END LOOP;
     
   IF emp_cur%ISOPEN THEN
     CLOSE emp_cur; 
   END IF;
END;
/ 

The above use simple loop with cursor, the Red Bold sentence are using the cursor attribute %ISOPEN to check if the cursor is open, the second Red Bold sentence are checking whether the fetch returned any row.

DECLARE 
   emp_rec employee%ROWTYPE;
   CURSOR emp_cur IS SELECT * FROM employee WHERE salary > 5000;
BEGIN
   IF NOT emp_cur%ISOPEN THEN
     OPEN emp_cur;
   END IF;
   
   FETCH emp_cur INTO emp_rec;
   WHILE emp_cur%FOUND 
     LOOP
     dbms_output.put_line (emp_rec.first_name || '  ' || emp_rec.last_name || '  ' || emp_rec.dept || '  ' || emp_rec.salary);
     FETCH emp_cur INTO emp_rec;
     END LOOP;
     
   IF emp_cur%ISOPEN THEN
     CLOSE emp_cur; 
   END IF;
END;
/ 

The above use while loop instead of simple loop.

DECLARE 
   emp_rec employee%ROWTYPE;
   CURSOR emp_cur IS SELECT * FROM employee WHERE salary > 5000;
BEGIN  
   FOR emp_rec IN emp_cur
     LOOP
     dbms_output.put_line (emp_rec.first_name || '  ' || emp_rec.last_name || '  ' || emp_rec.dept || '  ' || emp_rec.salary);
     END LOOP;
     
   IF emp_cur%ISOPEN THEN
     CLOSE emp_cur; 
   END IF;
END;
/ 

 The above use for loop insteaded the simple loop.

0
0
分享到:
评论

相关推荐

    javascript可以很简单的把png透明,并且支持IE5、IE6

    这是我用jquery框架编写的一个可以使用你的网站中的所有PNG格式的图片支持透明度,本来符合W3C规范的浏览器是支持PNG透明的,但是可恨的...源文来自:http://studing.com.cn/bbs/thread-6430-1-1.html Studing技术论坛

    eeglab for eeglab studing

    ### EEGlab知识点详解 #### 一、EEGLAB概述与入门 **1.1 什么是EEGLAB?** EEGLAB是一款开源的图形界面工具箱,主要基于MATLAB平台开发,用于处理脑电图(EEG)数据。该工具箱为用户提供了多种功能,包括但不限于...

    approach to english studing

    u may attain aspiration from it

    ISC offical studing guid 7th edition.pdf

    根据提供的文件信息,本文知识点将围绕ISC CISSP官方学习指南第七版的发布背景、内容架构、作者团队和版权声明等方面进行详细说明。 首先,ISC CISSP官方学习指南第七版是一本专为信息安全领域中希望获取CISSP认证...

    studing_Node

    标题“studing_Node”暗示了我们正在探讨与Node.js相关的学习主题。Node.js是一个基于Chrome V8引擎的JavaScript运行环境,它允许开发者在服务器端使用JavaScript进行开发,从而实现全栈JavaScript开发。在这个主题...

    ASP.NET_MVC_5_studing

    ASP.NET MVC 5通常与Entity Framework一起使用,这是一个ORM(对象关系映射)工具,能够方便地操作数据库,减少了开发者与SQL直接交互的工作量。 **7. Bootstrap集成** 为了快速创建响应式和移动优先的网页设计,...

    studing-typescript

    在 "studing-typescript" 这个主题中,我们将深入探讨 TypeScript 的核心特性、语法结构以及如何在实际开发中应用它。 ### 1. 类型系统 TypeScript 引入了丰富的类型系统,包括基本类型(如 string、number、...

    studing_ml

    标题“studing_ml”暗示了这是一个关于机器学习(Machine Learning, ML)的学习资源,很可能包含一系列教程、代码示例或项目。描述中的“studing_ml”同样表明它专注于机器学习的学习过程。考虑到标签是“Python”,...

    Rourtering.rar_WSN_WSN matlab

    Document for studing about WSN

    Kubernetes Bible

    Early Release just for studing

    thinking java

    famous book for studing java

    带有缓冲效果的jquery打开和关闭层代码

    此外,这个项目中提到的“Studing发布代码”可能是指一个学习平台或个人的学习项目,这样的代码分享有助于开发者们学习和交流jQuery的动画技巧。在实际应用中,还可以根据需求添加更多的交互逻辑,例如防止层在打开...

    非常漂亮的隐藏对象的jquery代码

    从标签“Studing发布代码”来看,这可能是Studing在线学习知识论坛上发布的一个教学资源,旨在帮助学习者理解和应用jQuery的动画技术。"studing在线学习知识论坛"可能是一个社区平台,用户可以在其中分享代码、提问...

    Dom4j解析XML

    <title>Lucene Studing</title> </book> <title>Lucene in Action</title> </book> <owner>O'Reilly</owner> </books> ``` 这个XML文档描述了一个在线书店,包含了几本书的信息,每本书都有一个`title`元素...

    pv example simulink

    pv example for studing。光伏发电系统的并网,扰动法

    Hidden Markov modelling.rar_Hidden Power_hidden markov_hidden vi

    hidden markov modelling for studing of reliability and availability in power system in different condiktion.

    Performance of Distance Relays.rar_Distributed_matlb _relay_rela

    Performance of Distance Relays in powe system in various condition matlab code and simulation for studing tuniing relay performance.

    Dom4J生成XML的完整方法希望大家能用到

    String[] titles = {"Dom4j Tutorials", "Lucene Studing", "Lucene in Action"}; titleElement.setText(titles[i]); } // 添加owner元素 Element ownerElement = booksElement.addElement("owner"); ...

    beginning microsoft visual c# 2008

    This is version 3.5, Net programmer can look it as a refference,also you can learn asp.net 3.5 by studing this book.

    数据库检索方式.ppt

    "检索出"study", "studies", "studied", "studing"等。 2. 无限截词:"computer?"则可以匹配到所有以"computer"为词根的词,如"computers", "computerization"等,但过度使用可能导致误检。 这些检索技术的组合...

Global site tag (gtag.js) - Google Analytics