Oracle PL/SQL Parameters, Variables, and Views



Similar documents
Analytical Processing with SQL

Basics of PL/SQL. Writing Your First Program A SIMPLE PL/SQL CODE BLOCK THAT DISPLAYS THE WORD HELLO

A brief MySQL tutorial. CSE 134A: Web Service Design and Programming Fall /28/2001

SQL. Short introduction

3.GETTING STARTED WITH ORACLE8i

A basic create statement for a simple student table would look like the following.

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

5. CHANGING STRUCTURE AND DATA

Campaign, Election, Inaugural, and Resignation Speeches

Participation in Government INTERVIEW OF AN OLDER ADULT

Oracle Database 10g Express

Oracle For Beginners Page : 1

Oracle Database 10g: Introduction to SQL

US Presidents. Welcome, students!

Information Systems SQL. Nikolaj Popov

How To Create A Table In Sql (Ahem)

List of United States Presidents by genealogical

Programming with SQL

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Journal of Business & Economics Research Second Quarter 2014 Volume 12, Number 2

A Brief Introduction to MySQL

American Presidents. Author: Dr. Michael Libbee, Michigan Geographic Alliance

news from Tom Bacon about Monday's lecture

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Advance DBMS. Structured Query Language (SQL)

Database Programming with PL/SQL: Learning Objectives

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

New SQL Features in Firebird 3

Oracle 10g PL/SQL Training

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

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

Oracle Database 12c: Introduction to SQL Ed 1.1

Darshan Institute of Engineering & Technology PL_SQL

Introduction to SQL and database objects

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

Learning MySQL! Angola Africa SELECT name, gdp/population FROM world WHERE area > !

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

Presidential Election Results

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Create a Database Driven Application

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

Oracle 12c New Features For Developers

2. Oracle SQL*PLUS Winter Some SQL Commands. To connect to a CS server, do:

DbSchema Tutorial with Introduction in SQL Databases

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

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

REPORT GENERATION USING SQL*PLUS COMMANDS

CSC 443 Data Base Management Systems. Basic SQL

Advanced SQL. Jim Mason. Web solutions for iseries engineer, build, deploy, support, train

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Oracle SQL. Course Summary. Duration. Objectives

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

SQL 2: GETTING INFORMATION INTO A DATABASE. MIS2502 Data Analytics

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Oracle Database: SQL and PL/SQL Fundamentals

VARRAY AND NESTED TABLE

constraint PKnbrVol primary key (No_vol) ); DROP TABLE segmentdevol CASCADE CONSTRAINTS; CREATE TABLE segmentdevol( numeric(9) NOT NULL,

A table is a collection of related data entries and it consists of columns and rows.

Oracle Database: SQL and PL/SQL Fundamentals

Database 10g Edition: All possible 10g features, either bundled or available at additional cost.

Database Query 1: SQL Basics

Oracle For Beginners Page : 1

Writing Control Structures

Porting from Oracle to PostgreSQL

Working with the Geodatabase Using SQL

Oracle For Beginners Page : 1

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

Developing SQL and PL/SQL with JDeveloper

SQL Server Database Coding Standards and Guidelines

OLH: Oracle Loader for Hadoop OSCH: Oracle SQL Connector for Hadoop Distributed File System (HDFS)

Oracle Internal & Oracle Academy

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

ORACLE 10g Lab Guide

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Oracle Database: SQL and PL/SQL Fundamentals NEW

Chapter 8: Introduction to PL/SQL 1

14 Triggers / Embedded SQL

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

Webapps Vulnerability Report

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

Table Backup and Recovery using SQL*Plus

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 03 (Nebenfach)

Virtual Private Database Features in Oracle 10g.

Using SQL Server Management Studio

Introduction to SQL ( )

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Multimedia im Netz Online Multimedia Winter semester 2015/16

SQL Server An Overview

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved.

Once the schema has been designed, it can be implemented in the RDBMS.

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

Netezza SQL Class Outline

2/3/04 Doc 7 SQL Part 1 slide # 1

Transcription:

Oracle PL/SQL Parameters, Variables, and Views Using the Single ampersand characters to input column names, table names, and conditions select &col1, &col2, &col3 2 from &table_name 3 where &condition; Enter value for col1: last_name Enter value for col2: first_name Enter value for col3: wages old 1: select &col1, &col2, &col3 new 1: select last_name, first_name, wages Enter value for table_name: employee old 2: from &table_name new 2: from employee Enter value for condition: fk_department = 'POL' old 3: where &condition new 3: where fk_department = 'POL' LAST_NAME FIRST_NAME WAGES --------------- --------------- --------- WILSON WOODROW 9000 DWORCZAK ALICE 9800 JOHNSON LYNDON 12000 JOHNSON ANDREW 7500 CLINTON WILLIAM 15000 NIXON RICHARD 12500 KENNEDY JOHN 11500 ROOSEVELT FRANKLIN 10400 8 rows selected. End listing 1

Using the Double ampersand variable In the previous examples in this section, each of the variables had a name that was unique to the statement. If you have Single ampersand variables with the same name, Oracle will still prompt you to enter values for each of the variables (unless a permanent variable is created). This can inconvenient a user when the same value must be used several times in a Select statement. Users may not understand why they must enter the same value several times. This problem is solved by the Double ampersand variable. The Double ampersand variable will cause Oracle to prompt the user for a value and will create a permanent (to the current session) variable. The permanent variable will use the name supplied by the Double ampersand variable. Subsequent Single ampersand variables using the variable name will use the Double ampersand variable value rather than prompt the user for a value. Using the Double ampersand variable to create a variable select fk_department, last_name, first_name, tool_name 2 from employee, emp_tools 3 where payroll_number = fk_payroll_number User is prompted 4 and fk_department = &&department_code for this value 5 union 6 select fk_department, last_name, first_name, optician 7 from employee, glasses 8 where payroll_number = fk_payroll_number 9 and fk_department = &department_code; Enter value for department_code: 'POL' old 4: and fk_department = &&department_code new 4: and fk_department = 'POL' old 9: and fk_department = &department_code new 9: and fk_department = 'POL' FK_D LAST_NAME FIRST_NAME TOOL_NAME ---- --------------- --------------- -------------------- POL JOHNSON ANDREW Fountain Pen POL JOHNSON ANDREW Greenberg Optical POL JOHNSON ANDREW Shovel POL JOHNSON LYNDON Peralman Optical POL NIXON RICHARD Downtown Optical POL NIXON RICHARD Hack Saw POL NIXON RICHARD Pliers POL ROOSEVELT FRANKLIN CIGARETTE HOLDE POL ROOSEVELT FRANKLIN HYDE PARK OPTICAL POL ROOSEVELT FRANKLIN STAPLER POL WILSON WOODROW DUST PAN POL WILSON WOODROW STERLING OPTICAL POL WILSON WOODROW VACUUM POL WILSON WOODROW VISE GRIPS 14 rows selected. User is not prompted for this value 2

Defining user variables Variable definition commands Command Define variable_name = value Define variable_name Define Accept variable_name Description Creates a user variable with a data type of Char. It also assigns a value to the variable Displays the variable, its datatype, and its value Displays all existing variables. This also includes their values and data type. Sets up a variable that displays a custom prompt when it is called. Illustrating the following Define command uses:? Using the Define command on a variable that does not exist.? Using the Define command to create and populate a variable? Using the Define command to view the variable attribute information.? Using the variable in a Select statement? Using the Define command to view all variables 3

Using the Define command define user_var SP2-0135: symbol user_var is UNDEFINED define user_var = 35 define user_var DEFINE USER_VAR = "35" (CHAR) select last_name, first_name 2 from employee 3 where payroll_number = &user_var; old 3: where payroll_number = &user_var new 3: where payroll_number = 35 LAST_NAME FIRST_NAME --------------- --------------- REAGAN RONALD Define command shows define the variables DEFINE _SQLPLUS_RELEASE = "801050000" (CHAR) DEFINE _EDITOR = "Notepad" (CHAR) DEFINE _O_VERSION = "Oracle8i Personal Edition Release 8.1.5.0.0 - Production With the Java option PL/SQL Release 8.1.5.0.0 - Production" (CHAR) DEFINE _O_RELEASE = "801050000" (CHAR) DEFINE USER_VAR = "35" (CHAR) End Listing Error message caused by using the Define command when a value was not assigned Creating the variable and assigning it a value Variable attributes Select statement did not prompt for the Single ampersand variable Administering Database Views Create [or replace] [force noforce] view viewname as select statement [with check option [constraint constraint]] [with read only]; 4

Using a view to mask the SQL complexity create or replace view employee_data as 2 select department_name, last_name ', ' first_name name, 3 wages, birth_date, 4 trunc(months_between(sysdate, birth_date)/12,0) age, 5 employment_date, 6 trunc(months_between(sysdate, birth_date)/12,0) 7 seniority_yrs 8 from department, employee 9 where department = fk_department; Derived View created. age values select department_name, name, seniority_yrs 2 from employee_data Using the view 3 order by seniority_yrs desc; DEPARTMENT_NAME NAME SENIORITY_YRS --------------- -------------------------------- ----------- -- POLITICAL SCIEN WILSON, WOODROW 144 WELFARE BUREAU TAFT, WILLIAM 143 INTERIOR DESIGN ROOSEVELT, THEODORE 142 INTERIOR DESIGN COOLIDGE, CALVIN 129 WELFARE BUREAU HOOVER, HERBERT 127 POLITICAL SCIEN ROOSEVELT, FRANKLIN 119 INTERIOR DESIGN TRUMAN, HAROLD 117 WELFARE BUREAU ROOSEVELT, ELEANOR 116 INTERIOR DESIGN EISENHOWER, DWIGHT 110 desc employee_data Name Null? Type ---------------------------------------------- -------- -------------- DEPARTMENT_NAME VARCHAR2(15) NAME VARCHAR2(32) WAGES NUMBER(8,2) BIRTH_DATE DATE AGE NUMBER EMPLOYMENT_DATE DATE SENIORITY_YRS NUMBER 5

Create view command options View Option Or Replace Force Noforce With Check Option With Read Only Description Replaces an existing view with the new one. If this option is missing, Oracle will not allow you to overwrite an existing view. It must be dropped first. Allows the view to be created even if the tables do not exist or if the view references any invalid components. Allows the view to be created only if the tables exist and the components are valid. This is the default. Restricts DML operations to only the rows that are accessible to the view. Ensures that no DML operations can be performed using the view. DML and views View type properties Property Simple View Complex view Number of tables One One or more Contains functions No Yes Grouped Values No Yes DML Allowed Yes Not Always 6

Simple views can be used in DML statements. This is because the records displayed in a simple view relate to one row of a table. Complex view records are a virtual record and do not generally relate to one row of a table. The Delete command cannot be used against a complex view if it has any of the following features:? View contains a group function.? View contains a Group By clause.? View contains the Distinct keyword.? View contains the pseudocolumn Rownum. A view cannot be updated if the view contains any of the above properties. It also cannot be updated if the view contains the following property:? View contains a column that is defined by expressions. These are columns that are concatenated or modified with functions such as Substr or Add_months. 7

A view cannot be used to add records to the database if it contains any of the above properties. It also cannot be used to insert records if it contains the following property:? The base tables contain Not Null constrained columns that do not exist in the view. The With Check Option Examples of creating a view with the With Check Option and executing Update commands against the view create view employee_names as 2 select fk_department, last_name, first_name 3 from employee 4 where fk_department = 'INT' 5 with check option; View created. With Check Option prevents the modification of the row update employee_names set fk_department = 'WEL' 2 where first_name = 'DWIGHT'; update employee_names set fk_department = 'WEL' * ERROR at line 1: ORA-01402: view WITH CHECK OPTION where-clause violation update employee_names set first_name = 'IKE' 2 where first_name = 'DWIGHT'; Update statement successfully updates 1 row updated. the table through the view. update employee set fk_department = 'WEL' 2 where first_name = 'IKE'; With Check Option 1 row updated. does not affect normal DML operations 8

Using the Read Only option The Read Only Option create view employee_names as 2 select fk_department, last_name, first_name 3 from employee 4 where fk_department = 'INT' 5 with read only; View created. update employee_names set first_name = 'IKE' 2 where first_name = 'DWIGHT'; where first_name = 'DWIGHT' * ERROR at line 2: ORA-01733: virtual column not allowed here End Listing How to update records using a view that can t be updated Oracle has developed a tool that allows a developer to update views that are not normally updateable. This tool is called an Instead Of trigger. This trigger can only be used if the target is a view. It executes the trigger s PL/SQL rather than the DML transaction that launched the trigger. 9

iew that Computes the Percent Difference Each Employee s Tool and Eyeglass Purchases Differ From the Department Average create or replace view wages_difference as 2 select employee.fk_department, payroll_number, last_name, 3 first_name, wages, 4 employee_purchases/(dept_purchases/employee_amt) 5 percent_of_department_avg 6 from employee, 7 (select fk_payroll_number, sum(cost) employee_purchases 8 from (select fk_payroll_number, nvl(tool_cost,0) cost 9 from emp_tools 10 union all 11 select fk_payroll_number, nvl(cost,0) 12 from glasses) 13 group by fk_payroll_number) e, 14 (select fk_department, sum(cost) dept_purchases 15 from (select fk_department, nvl(tool_cost,0) cost 16 from employee, emp_tools 17 where payroll_number = fk_payroll_number(+) 18 union all 19 select fk_department, nvl(cost,0) 20 from employee, glasses 21 where Payroll_number = fk_payroll_number(+)) 22 group by fk_department) f, 23 (select fk_department, count(*) employee_amt 24 from employee 25 group by fk_department) c 26 where employee.payroll_number = e.fk_payroll_number(+) 27 and employee.fk_department = f.fk_department(+) 28 and employee.fk_department = c.fk_department; View created. 10