PL / SQL Basics. Chapter 3



Similar documents
Database Programming with PL/SQL: Learning Objectives

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Writing Control Structures

Oracle Database: SQL and PL/SQL Fundamentals

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Oracle Database: SQL and PL/SQL Fundamentals NEW

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Oracle Database: SQL and PL/SQL Fundamentals

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

PL/SQL TUTORIAL. Simply Easy Learning by tutorialspoint.com. tutorialspoint.com

GENERAL PROGRAMMING LANGUAGE FUNDAMENTALS

ISYS PL/SQL Basics. Week 03

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

PL/SQL MOCK TEST PL/SQL MOCK TEST I

Handling PL/SQL Errors

Oracle PL/SQL Programming

SQL Server Database Coding Standards and Guidelines

Moving from CS 61A Scheme to CS 61B Java

Programming Database lectures for mathema

Oracle SQL. Course Summary. Duration. Objectives

Handling PL/SQL Errors

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Introduction to Python

Oracle Internal & Oracle Academy

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Chapter 2: Elements of Java

Object Oriented Software Design

Answers to the Try It Yourself Sections

3.GETTING STARTED WITH ORACLE8i

Ed. v1.0 PROGRAMMING LANGUAGES WORKING PAPER DRAFT PROGRAMMING LANGUAGES. Ed. v1.0

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Oracle Database 12c: Introduction to SQL Ed 1.1

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Exercise 4 Learning Python language fundamentals

How To Name A Program In Apl/Sql

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Handling Exceptions. Copyright 2008, Oracle. All rights reserved.

2. Which of the following declarations is invalid? Mark for Review (1) Points

Introduction to Python

Oracle Database: SQL and PL/SQL Fundamentals NEW

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Chapter 5 Names, Bindings, Type Checking, and Scopes

VB.NET Programming Fundamentals

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Object Oriented Software Design

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Programming with SQL

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Chapter 2 Introduction to Java programming

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

6.170 Tutorial 3 - Ruby Basics

ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5

Pemrograman Dasar. Basic Elements Of Java

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Lecture 5: Java Fundamentals III

3 Data Properties and Validation Rules

Using Variables in PL/SQL. Copyright 2007, Oracle. All rights reserved.

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi

Variables, Constants, and Data Types

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Exercise 1: Python Language Basics

Performing Simple Calculations Using the Status Bar

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

5.1 Database Schema Schema Generation in SQL

When an exception occur a message which explains its cause is received. PL/SQL Exception message consists of three parts.

Oracle For Beginners Page : 1

Some Naming and Coding Standards

2. Capitalize initial keyword In the example above, READ and WRITE are in caps. There are just a few keywords we will use:

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Oracle 11g PL/SQL training

Handling Exceptions. Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total

What is the value of SQL%ISOPEN immediately after the SELECT statement is executed? Error. That attribute does not apply for implicit cursors.

Introduction to PL/SQL Programming

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

PHP Tutorial From beginner to master

The C Programming Language course syllabus associate level

An Introduction to PL/SQL. Mehdi Azarmi

Training Guide. PL/SQL for Beginners. Workbook

Some Scanner Class Methods

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

MATLAB Programming. Problem 1: Sequential

JavaScript: Control Statements I

SAPScript. A Standard Text is a like our normal documents. In Standard Text, you can create standard documents like letters, articles etc

Instant SQL Programming

Oracle Database 10g: Program with PL/SQL

C++ Language Tutorial

Oracle PL/SQL Best Practices

Oracle Database: Develop PL/SQL Program Units

OpenInsight 9.3 Quick Start Guide

Chapter 13 - The Preprocessor

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement

Oracle 10g PL/SQL Training

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Transcription:

PL / SQL Basics Chapter 3

PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2

PL / SQL Block Basic Block Structure All blocks have three (3) sections Declarative Where all variables, cursors, types, local procedures and functions are declared Executable Where the work of the block is performed Contains SQL and procedural statements Exception Errors are handled Code here is not run unless an error occurs 3

Lexical Units Identifiers Delimiters Literals Comments 4

Lexical Units A lexical unit is a sequence of characters, the character set includes: Upper and lowercase letters: A-Z, a-z White space: tabs, spaces, and carriage returns Math symbols: +-*/<>= Punctuation symbols: () {} []? ~ ; :. @ # % $ ^ & _ 5

Lexical Units Identifiers Used to name PL/SQL objects Consists of a letter followed by any sequence of characters such as: Letters, numbers, $, underscore, # Maximum length is thirty (30) characters Other characters are not permitted 6

Lexical Units Identifiers ~ Examples Some proper identifiers: y v_studentid TempName t1 t2_ social_security_# YTD 7

Lexical Units Identifiers ~ Examples Some improper identifiers: m+n _temp_ First Name OhBoyThisIsReallyALongIdentifierName 1CannotStartWithADigit 8

Lexical Units Identifiers ~ Reserved Words There are many identifiers known as reserved words (keywords) They have special meaning to PL/SQL You cannot use them as identifiers For example the word BEGIN is used to start a PL/SQL block and cannot be used as a variable name 9

Lexical Units Delimiters Symbols used to separate identifiers either a single character sequence of characters Examples of delimiters are: + * > <> <= ; (and others ) 10

Lexical Units Literals A literal is a value that is not an identifier There are three (3) types of literals: Character This is a character literal Numeric 123-9 +17 0-6.9 3 9.87e-3 95.12e7 Boolean True False Null 11

Lexical Units Comments It is important to document your code with comments to make it clear to others and yourself They are ignored by the PL/SQL compiler There are two kinds of comments Single-line Multiline 12

Variable Declarations Declaration syntax Variable initialization 13

Variable Declarations Declaration Syntax Variables are declared in the declarative section of a block Each variable has a specific type of data that it can hold General syntax is: variable_name type [CONSTANT] [NOT NULL] [:=value]; 14

Variable Declarations Variable Initialization Variables are initialized in their declaration statement v_counter NUMBER := 100; v_fname VARCHAR2(10) DEFAULT Scott ; If a variable is not initialized it is set to NULL NULL simply means missing or unknown value 15

PL / SQL Types Scalar types Composite types Reference types LOB types Using %TYPE User-defined subtypes Converting between Datatypes Variable scope and visibility 16

PL / SQL Types Scalar Types Valid scalar types consist of the same as the types for database columns Scalar types can be divided into seven families: numeric character raw date rowid boolean trusted 17

PL / SQL Types Composite Types A composite type is one that has components within it The three (3) composite types available in PL/SQL are: Records Tables varrays 18

PL / SQL Types Reference Types A variable that is declared as a reference type can point (refer to) different storage locations over the life of the program REF CURSOR REF OBJECT 19

PL / SQL Types LOB Types This type is used to store large objects A large object can be either binary or character value up to 4 gigabytes Can contain unstructured data 20

PL / SQL Types Using %TYPE Often a PL/SQL variable will be used to manipulate data stored in a database table Variable needs to have the same type as the table column Variable needs to be changed as the table column is altered Time consuming and error prone 21

PL / SQL Types Using %TYPE By using %TYPE when declaring a variable Variable will be defined with the same type as the associated table column Type is determined each time a block is run or When procedures and functions are compiled 22

PL / SQL Types User-Defined Subtypes A subtype is a PL/SQL type that is based on an existing type Used to give an alternative name which describes its intended use PL/SQL defines several subtypes DECIMAL and INTEGER are predefined subtypes of NUMBER 23

PL / SQL Types Converting Between Datatypes Explicit Scalar Datatype Conversion Built-in conversion functions in SQL are also available in PL/SQL Converts explicitly between variables using formats Examples are: TO_CHAR converts numeric and date TO_DATE converts character TO_NUMBER converts character 24

PL / SQL Types Converting Between Datatypes Implicit Scalar Datatype Conversion PL/SQL will convert between families when possible Good programming practice suggests using explicit conversions Formats are not used and does not clearly show the intent of the program 25

PL / SQL Types Variable Scope and Visibility The scope of a variable is the portion of the program in which it can be accessed The visibility of a variable is the portion of the program where the variable can be accessed without having to qualify the reference 26

Expressions and Operators Assignment Expressions 27

Expressions and Operators Assignment The syntax for an assignment is: variable := expression; Performed in the executable and exception handling sections lvalues must refer to actual storage locations rvalues can be storage locations or literals An rvalue is read from while an lvalue is written to 28

Expressions and Operators Expressions PL/SQL expressions are rvalues These expressions have two components An operand is the argument to an operator An operator is what operates on the operands Precedence of operators determines the order of evaluation of the expression Please Excuse My Dear Aunt Sally 29

Expressions and Operators Expressions Numeric expressions Evaluated from left to right applying the precedence order of operators Character expressions Only operator is concatenation operator Joins one or more strings (or arguments that can be implicitly converted) Boolean expressions A boolean expression is any expression that evaluates to a boolean value(true, False, Null) 30

PL / SQL Control Structures IF-THEN-ELSE Loops GOTOs and Labels PRAGMAs 31

PL / SQL Control Structures IF-THEN-ELSE The syntax for an IF-THEN-ELSE statement is: IF boolean_expression1 THEN sequence_of_statements1; [ELSIF boolean_expression2 THEN sequence_of_statements2;] [ELSE sequence_of_statements3;] END IF; 32

PL / SQL Control Structures Loops Loops are divided into four (4) categories Simple loops WHILE loops Numeric FOR loops Cursor FOR loops 33

PL / SQL Control Structures Loops ~ Simple Loops The basic kind of loop has the syntax: LOOP sequence_of_statements; END LOOP; These loops will execute forever unless you include an EXIT statement Checks a condition for ending the loop since it has no stopping condition, it syntax is: EXIT [WHEN condition]; 34

PL / SQL Control Structures Loops ~ WHILE Loops The syntax for a WHILE loop is: WHILE condition LOOP sequence_of_statements; END LOOP; Condition is checked before each cycle of the loop If True, loop body is executed Otherwise loop is passed over 35

PL / SQL Control Structures Loops ~ Numeric FOR Loops The syntax for a numeric FOR loop is: FOR loop_counter IN [REVERSE] lo_bound.. hi_bound LOOP sequence_of_statements; END LOOP; Numeric FOR loops have a defined number of cycles Do not declare the loop index Loop increment (decrement) is always one In order to have a different increment you would need to include additional code in the loop body 36

PL / SQL Control Structures Loops ~ Cursor FOR Loops A cursor FOR loop is a loop that is associated: With an explicit cursor A SELECT statement incorporated directly within the loop boundary Used when you need to fetch and process records from a cursor Replaces the cursor operations such as: Open Fetch End of records Close 37

PL / SQL Control Structures GOTOs and Labels The syntax of a GOTO statement is: GOTO label; Where label is a label defined in the PL/SQL block Labels are enclosed in double angle brackets When a GOTO statement is evaluated, program control passes to the statement identified by the label If your code is properly structured you will never have to use a GOTO statement 38

PL / SQL Control Structures PRAGMAs The PRAGMA keyword signifies a preprocessor statement PRAGMAs are processed at compile time They do not execute during runtime Passes information to the compiler 39

PL / SQL Style Guide Good style means that: It will take less time to understand what the program is doing Modifications can be made easier and will be less error prone Uniformity of code increases productivity Areas of where style can be applied are: Comments Variable Names Capitalization Indentation General Guidelines 40

PL / SQL Style Guide Comments At the start of each block or procedure With each variable declaration Before each major section of a block Comments should be meaningful and not restate what the code obviously shows It s possible to have too many comments 41

PL / SQL Style Guide Variable Names Make the variable names descriptive t NUMBER; v_studentid NUMBER(5); A variable name can tell us its use: v_variablename e_exceptionname t_typename p_parametername Program variable User-defined exception User-defined type Parameter to a procedure or function 42

PL / SQL Style Guide Capitalization PL/SQL is not case sensitive Proper use of case will improve program readability reserved words in uppercase built-in functions in uppercase predefined types in uppercase sql keywords in uppercase database objects in lowercase variable names are in mixed case, with capital letter for each word in the name 43

PL / SQL Style Guide Indentation Use of white space (carriage returns, spaces, and tabs) is necessary to provide readability of your code Indent: inside blocks SQL continuation statements IF-THEN-ELSE blocks 44

PL / SQL Style Guide General Guidelines As you write more code you will develop a pronounced level of style It s a good idea to show your code to another programmer and have it reviewed Be consistent in making your code understandable 45

In Conclusion We have covered the basic syntax and structure of PL/SQL Block Variables Datatypes (scalar, composite, reference) Expressions and operators Datatype conversions Control structures Programming style 46