COMP 430 Intro. to Database Systems. Encapsulating SQL code

Similar documents
Assorted Topics Stored Procedures and Triggers Pg 1

SQL STORED ROUTINES. CS121: Relational Databases Fall 2017 Lecture 9

Programming the Database

Structured Query Language

G64DBS Database Systems. Lecture 7 SQL SELECT. The Data Dictionary. Data Dictionaries. Different Sections of SQL (DDL) Different Sections of SQL (DCL)

Advanced SQL GROUP BY Clause and Aggregate Functions Pg 1

EE221 Databases Practicals Manual

Database Technology. Topic 6: Triggers and Stored Procedures

COMP 430 Intro. to Database Systems. SQL from application code

SQL User Defined Code. Kathleen Durant CS 3200

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

STORED PROCEDURE AND TRIGGERS

Part 1: Access Privileges

SQL Interview Questions

Persistent Stored Modules (Stored Procedures) : PSM

Advanced SQL Topics. Michael Fields Central Library Consortium

Intro to Structured Query Language Part I

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

COMP283-Lecture 6 Applied Database Management

Maintaining Data 3.3.1

Lesson 13 Transcript: User-Defined Functions

Principles of Data Management

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Vendor: IBM. Exam Code: C Exam Name: DB Fundamentals. Version: Demo

Introduction to Computer Science and Business

IBM Exam C DB2 9.5 SQL Procedure Developer Version: 3.0 [ Total Questions: 97 ]

IBM DB2 9 Family Fundamentals. Download Full Version :

Database Programming with PL/SQL

Lecture 5. Monday, September 15, 2014

Course 492 Supplementary Materials. Mutating Tables

DATABASE MANAGEMENT SYSTEMS PREPARED BY: ENGR. MOBEEN NAZAR

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

C Examcollection.Premium.Exam.58q

Oracle Database 10g Express

INDEX. 1 Introduction. 2 Types of Cursors 2.1 Explicit cursor 2.2 Attributes 2.3 Implicit cursor 2.4 Attributes. 3 Parameterized cursor

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C

Handout 6 CS-605 Spring 18 Page 1 of 7. Handout 6. Physical Database Modeling

Database Programming with SQL

Oracle 1z z0-146 Oracle Database 11g: Advanced PL/SQL. Practice Test. Version QQ:

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Slides by: Ms. Shree Jaswal

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Consistency The DBMS must ensure the database will always be in a consistent state. Whenever data is modified, the database will change from one

CSC 261/461 Database Systems Lecture 6. Fall 2017

Misc. Triggers Views Roles Sequences - Synonyms. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering

Real Application Security Administration

Lecture 08. Spring 2018 Borough of Manhattan Community College

IT Certification Exams Provider! Weofferfreeupdateserviceforoneyear! h ps://

Number: Passing Score: 800 Time Limit: 120 min File Version:

An Introduction to Structured Query Language

C Exam Questions Demo IBM. Exam Questions C

Working with Databases and Java

5. Single-row function

An Introduction to Structured Query Language

An Introduction to Structured Query Language

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

Meet MariaDB Vicențiu Ciorbaru Software MariaDB Foundation * * 2017 MariaDB Foundation

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

Procedural Language Structured Query Language (PL/SQL)

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Database Programming with PL/SQL

Constructs in Oracle

Chapter 2. DB2 concepts

IBM A Assessment: DB2 9 Fundamentals-Assessment. Download Full Version :

Oracle Exam 1z0-144 Oracle Database 11g: Program with PL/SQL Version: 8.5 [ Total Questions: 103 ]

PL / SQL Basics. Chapter 3

Lab # 4. Data Definition Language (DDL)

based mainly on course notes by Will Hyslop (UNB-F) and course notes by Jeff Ullman and others (Stanford)

Optimize Enterprise Generation Language (EGL) applications using purequery

Working with Columns, Characters and Rows. Copyright 2008, Oracle. All rights reserved.

Course Overview. Copyright 2010, Oracle and/or its affiliates. All rights reserved.

1.8 Database and data Data Definition Language (DDL) and Data Manipulation Language (DML)

Question No : 1 Which statement is true about triggers on data definition language (DDL) statements?

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

DATABASE DESIGN - 1DL400

SQL: Part III. Announcements. Constraints. CPS 216 Advanced Database Systems

B.H.GARDI COLLEGE OF MASTER OF COMPUTER APPLICATION. Ch. 1 :- Introduction Database Management System - 1

Database Management Systems Triggers

DATABASE SECURITY AND PRIVACY. Some slides were taken from Database Access Control Tutorial, Lars Olson, UIUC CS463, Computer Security

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Structure Query Language (SQL)

Database Programming with SQL

Institute of Aga. Network Database LECTURER NIYAZ M. SALIH

Database Programming with PL/SQL

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Relational Databases Fall 2017 Lecture 7

Relational terminology. Databases - Sets & Relations. Sets. Membership

Summary Modifications. Database Construction (and Usage) Explicit attribute lists. Insertions with queries. Quiz. Default values

Lesson B Objectives IF/THEN. Chapter 4B: More Advanced PL/SQL Programming

The Relational Model

Oracle Class VII More on Exception Sequence Triggers RowID & Rownum Views

Instructor: Craig Duckett. Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL

Lecture 7 Stored procedure

Seminar 3. Stored procedures. Global variables. Dynamic Execution. The OUTPUT clause. Cursors

Assertions, Views, and Programming. CS157A Chris Pollett Oct. 31, 2005.

ACCESS isn t only a great development tool it s

Vendor: IBM. Exam Code: Exam Name: DB Fundamentals. Version: DEMO

Database System Concepts

An Introduction to Structured Query Language

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Transcription:

COMP 430 Intro. to Database Systems Encapsulating SQL code

Want to bundle SQL into code blocks Like in every other language Encapsulation Abstraction Code reuse Maintenance

DB- or application-level? DB: Encapsulation Application programmer only uses API, and doesn t need details, including much SQL. Safety Protect DB from application programmer. Only expose desired API. Performance Less I/O. Better DBMS optimization. Application: Convenience More Java/C++/ programmers than for SQL. Flexibility Can use the DB however you want. Libraries Make everything easier.

Procedural extensions of SQL PL/SQL Oracle, IBM, PL/pgSQL PostreSQL Transact-SQL Microsoft, Sybase We ll use this. Adds variables, assignment, conditionals, loops, begin/end, procedures, functions, packages(?), security, Yet another full language. We ll focus on only some core concepts.

Security Don t trust some users: Don t trust some programmers: Restrict access to tables, rows, columns, procedures, or functions based upon user/group/role GRANT, DENY, REVOKE, Namespaces packages/schemas Private functions/procedures Private not supported in Transact- SQL. We can define API, but can t prevent SQL code from bypassing API. In this course: Only consider SQL injection attacks (later).

DB-level code blocks

Three types User-defined functions Stored procedures Triggers Side-effect-free mappings from inputs to output Primarily used for their side-effects, e.g., updating DB Event handlers

Scalar function example CREATE FUNCTION CubeVolume (@side_len INT READONLY) RETURNS INT WITH RETURNS NULL ON NULL INPUT AS DECLARE @volume INT; IF @side_len < 0 SET @volume = 0; ELSE SET @volume = @side_len * @side_len * @side_len; RETURN @volume; ;

Inline table-valued function example CREATE FUNCTION GetEmployeeIDsCountry (@country VARCHAR(50) READONLY) RETURNS TABLE AS RETURN (SELECT id FROM Employee WHERE country = @country);

CREATE FUNCTION ParseDelimitedInts (@list VARCHAR(5000), @delimiter VARCHAR(10) =, READONLY) RETURNS @int_table TABLE (item INT) AS DECLARE @text_item VARCHAR(200); DECLARE @index INT; WHILE Datalength(@list) > 0 SET @index = Charindex(@delimiter, @list); IF @index > 0 SET @text_item = Substring(@list, 1, @index - 1); SET @list = Substring(@list, @index + Datalength(@delimiter), Datalength(@list)); ELSE SET @item_text = @list; SET @list = NULL; INSERT INTO @int_table SELECT item = Convert(INT, @text_item); RETURN Table-valued function example

CREATE PROCEDURE InsertEmployee ( @first_name VARCHAR(50), @last_name VARCHAR (50), Procedure example @salary INT, @hire_date DATETIME) AS DECLARE @count INT; SELECT @count = COUNT(*) FROM Employee WHERE first_name = @first_name AND last_name = @last_name; IF @count = 0 INSERT INTO Employee VALUES (@first_name, @last_name, @salary, @hire_date); EXECUTE InsertEmployee John, Smith, 50000, 03-11-2016 ; EXECUTE InsertEmployee @first_name = Mary, @last_name = Jones, @salary = 60000, @hire_date = 02-12-2016 ;

Cursors often used in procedures SELECT implicitly loops over table data. Cursors allow SQL code to explicitly loop over table data. Generally much slower than declarative SQL. (Often written by SQL-newbies.) Mechanism for returning table from procedure (soon). Concept sometimes used at application-level (soon). + Useful for running totals. + Decreases transaction granularity (later). Typical usage (pseudo-code): Cursor is for SELECT While cursor not at end of query Do something with this row. Move cursor to next row.

Cursor Example CREATE PROCEDURE MyProcedure ( ) AS DECLARE @id INT; DECLARE @first_name VARCHAR(50); DECLARE @last_name VARCHAR(50); DECLARE db_cursor CURSOR FOR SELECT id, first_name, last_name FROM Student; OPEN db_cursor; FETCH NEXT FROM db_cursor INTO @id, @first_name, @last_name; WHILE @@FETCH_STATUS = 0 FETCH NEXT FROM db_cursor INTO @id, @first_name, @last_name; CLOSE db_cursor; DEALLOCATE db_cursor;

Returning values from a procedure User-defined functions can return scalars or tables. What about procedures? Can return scalars Can sort-of return tables Several different mechanisms

Returning via OUTPUT parameters CREATE PROCEDURE MyProcedure ( @a VARCHAR(50), @b INT OUTPUT) AS Scalars only. Not text. Not tables. DECLARE @my_a VARCHAR(50) = foo ; DECLARE @my_b INT = 42; EXECUTE MyProcedure @my_a, @my_b OUTPUT; Functions cannot have OUTPUT parameters.

Returning via RETURN CREATE PROCEDURE MyProcedure ( @a VARCHAR(50), @b INT) AS RETURN 2; INT only. Meant as a status code. DECLARE @status INT; EXECUTE @status = MyProcedure foo, 42; Not meant as a general-purpose technique.

Returning result set CREATE PROCEDURE MyProcedure ( @a VARCHAR(50), @b INT) AS SELECT ; INSERT INTO table_name EXECUTE MyProcedure @my_a, @my_b; Returns a temporary table of data.

Returning a cursor CREATE PROCEDURE MyProcedure ( @a VARCHAR(50), @b INT, @cursor CURSOR VARYING OUTPUT) AS SET @cursor = CURSOR FOR SELECT ; DECLARE @my_cursor CURSOR; EXECUTE MyProcedure @my_a, @my_b, @my_cursor OUTPUT; In effect, returns the table itself.

Triggers A stored procedure associated with a particular table that is fired when an INSERT, UPDATE, or DELETE occurs. No parameters. CREATE TRIGGER TrigAddStudent ON Students AFTER INSERT, UPDATE AS DECLARE @count INT; SELECT @count = COUNT(*) in Inserted; PRINT @count + students added or updated. Alternate: INSTEAD OF Similarly, Deleted is available for UPDATE, DELETE.

Main uses of triggers Logging Put CREATE TRIGGER next to the relevant CREATE TABLE. Automatic correction of bad data. Updating relevant data elsewhere for consistency. E.g., PurchaseItem table has trigger that updates Inventory table. Bad: Rejecting bad values use CHECK. Alternatively, enforce that all table data changes are handled by a stored procedure that also does these.