49
Introduction of SQL Introduction of SQL Programming Programming SS Chung SS Chung

Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Embed Size (px)

Citation preview

Page 1: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Introduction of SQL Introduction of SQL

ProgrammingProgramming

SS ChungSS Chung

Page 2: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Embedded SQLEmbedded SQL

SQL is not enough! Needs to be embedded in a SQL is not enough! Needs to be embedded in a general purpose language to get general purpose language to get

–– GUIGUI

–– Flow of controlFlow of control

–– Generate SQL dynamically based on user inputGenerate SQL dynamically based on user input

The SQL standard defines embeddings of SQL in The SQL standard defines embeddings of SQL in a variety of programming languages a variety of programming languages

SQL commands can be called from within a host SQL commands can be called from within a host language (e.g., C/C++, Basic, .NET or Java) language (e.g., C/C++, Basic, .NET or Java) program or scripting language (e.g., PHP, Ruby)program or scripting language (e.g., PHP, Ruby)

A query answer is a bag of records A query answer is a bag of records -- with with arbitrarily many rows! No such data structure in arbitrarily many rows! No such data structure in most languages. Called most languages. Called impedance mismatchimpedance mismatch

The SQL standard supports a The SQL standard supports a cursorcursor to handle to handle thisthis

Page 3: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Embedded SQLEmbedded SQL

A language to which SQL queries are embedded A language to which SQL queries are embedded

is referred to as a is referred to as a host languagehost language, and the SQL , and the SQL

structures permitted in the host language structures permitted in the host language

comprise comprise embedded embedded SQL.SQL.

The basic form of these languages follows that of The basic form of these languages follows that of

the System R embedding of SQL into PL/I.the System R embedding of SQL into PL/I.

EXEC SQLEXEC SQL statement is used to identify statement is used to identify

embedded SQL request to the preprocessorembedded SQL request to the preprocessor

EXEC SQL <embedded SQL statement > EXEC SQL <embedded SQL statement >

END_EXECEND_EXEC

Note: this varies by language (for example, the Note: this varies by language (for example, the

Java embedding uses # SQL { Java embedding uses # SQL { ……. }; ) . }; )

Page 4: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

CursorsCursors

You can declare a You can declare a cursorcursor on a table or query on a table or query

statement (which generates a table as a result).statement (which generates a table as a result).

You can You can openopen a cursor, and repeatedlya cursor, and repeatedly fetchfetch a a

tuple then tuple then movemove the cursor, until all the cursor, until all tuplestuples have have

been retrieved.been retrieved.

You can modify/delete a You can modify/delete a tupletuple pointed to by a pointed to by a

cursor.cursor.

SQL must be able to report dataSQL must be able to report data--generated generated

errors.errors.

Page 5: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

CursorsCursors

Cursor points to the current row.Cursor points to the current row.

DECLARE DECLARE cNamecName CURSOR CURSOR

FORFOR select statementselect statement

–– declares the select statementdeclares the select statement

OPENOPEN cNamecName

–– Executes the select statementExecutes the select statement

Page 6: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Embedding SQL in C: An ExampleEmbedding SQL in C: An Example

Void Void ListAgesListAges( ( intint minzipminzip))

{{

char SQLSTATE[6];char SQLSTATE[6];

EXEC SQLEXEC SQL BEGIN DECLARE SECTIONBEGIN DECLARE SECTION

charchar c_name[20]; c_name[20];

char char c_party[3]; c_party[3];

integer integer minzipminzip;;

EXEC SQLEXEC SQL END DECLARE SECTIONEND DECLARE SECTION

• SQLSTATE holds SQL error codes

• EXEC SQL denotes embedded SQL section

• DECLARE SECTION binds variables into

SQL

Page 7: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

CursorCursor that gets names of candidates who that gets names of candidates who

have a principal committee, in alphabetical have a principal committee, in alphabetical

orderorder

EXEC SQL EXEC SQL DECLARE DECLARE cinfocinfo CURSORCURSOR FORFOR

SELECT SELECT N.CandnameN.Candname

FROM FROM CandCand N JOIN N JOIN CommComm M ON (M ON (N.PrincommN.Princomm = = M.CommidM.Commid))

ORDER BY ORDER BY N.CandnameN.Candname;;

OPEN OPEN cinfocinfo;;

FETCH FETCH cinfocinfo INTO INTO :c:c--namename; (probably in a loop in your ; (probably in a loop in your

program)program)

CLOSE CLOSE cinfocinfo;; Notice the colon in :cname – it refers to a variable that has

been declared in the surrounding program

Page 8: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Embedding in C: An ExampleEmbedding in C: An Example

DECLAREDECLARE cinfocinfo CURSOR:CURSOR: defines a name for Cursordefines a name for Cursor

SELECT SELECT …… : SQL whose results the cursor will : SQL whose results the cursor will point topoint to

::minzipminzip : Note the colon referring to a C variable : Note the colon referring to a C variable declared previouslydeclared previously

EXEC SQL EXEC SQL DECLARE DECLARE cinfocinfo CURSOR FORCURSOR FOR

SELECT SELECT N. N. candnamecandname, , N.parN.par

FROM FROM candcand NN

WHERE WHERE zip > :zip > :minzipminzip

ORDER BY ORDER BY N.candnameN.candname;;

Page 9: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Embedding in C: An ExampleEmbedding in C: An Example

OPENOPEN cinfocinfo : Executes the query and positions the : Executes the query and positions the cursor before the first row of the outputcursor before the first row of the output

FETCH FETCH cinfocinfo INTOINTO : assigns the data of the first row (if it : assigns the data of the first row (if it exists) into C program variablesexists) into C program variables

CLOSE CLOSE cinfocinfo : Free the cursor: Free the cursor’’s resourcess resources

EXEC SQLEXEC SQL OPENOPEN cinfocinfo;;

EXEC SQLEXEC SQL FETCHFETCH cinfocinfo INTOINTO ::c_namec_name;;

WhileWhile(SQLSTATE(SQLSTATE != != ““0200002000””) )

{{

printf(printf(““CandidateCandidate name is %name is %ss\\nn””, , candnamecandname););

EXEC SQL FETCHEXEC SQL FETCH cinfocinfo INTOINTO ::c_namec_name;;

} ;} ;

EXEC SQLEXEC SQL CLOSECLOSE cinfocinfo;;

Page 10: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Example QueryExample Query

Specify the query in SQL and declare a Specify the query in SQL and declare a cursorcursor for itfor it

EXEC SQLEXEC SQL

Declare Declare cc Cursor for Cursor for

Select Select Depositor.Customer_nameDepositor.Customer_name, , Customer_cityCustomer_city

From From Depositor, Customer, AccountDepositor, Customer, Account

Where Where Depositor.Customer_nameDepositor.Customer_name = =

Customer.Customer_nameCustomer.Customer_name

andand Depositor.Account_numberDepositor.Account_number = =

Account.Account_numberAccount.Account_number

and and Account.BalanceAccount.Balance > :amount> :amount

END_EXECEND_EXEC

� From within a host language, find the names and cities of

customers with more than the variable amount dollars in some

account.

Page 11: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Embedded SQL (Cont.)Embedded SQL (Cont.)TheThe openopen statement causes the query to be evaluatedstatement causes the query to be evaluated

EXEC SQL open EXEC SQL open c c END_EXECEND_EXEC

The The fetchfetch statement causes the values of one tuple in the statement causes the values of one tuple in the

query result to be placed on host language variables.query result to be placed on host language variables.

EXEC SQL fetch EXEC SQL fetch c c into into ::cncn, :cc, :cc END_EXECEND_EXEC

Repeated calls to Repeated calls to fetchfetch get successive tuples in the query get successive tuples in the query

resultresult

A variable called A variable called SQLSTATESQLSTATE inin the SQL communication area the SQL communication area

(SQLCA) gets set to (SQLCA) gets set to ‘‘0200002000’’ to indicate no more datato indicate no more data is is

availableavailable

The The close close statement causes the database system to delete the statement causes the database system to delete the

temporary relation that holds the result of the query.temporary relation that holds the result of the query.

EXEC SQL closeEXEC SQL close cc END_EXECEND_EXEC

Note: above details vary with language. For example, the Java Note: above details vary with language. For example, the Java

embedding defines Java iterators to step through result tuples.embedding defines Java iterators to step through result tuples.

Page 12: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Updates Through CursorsUpdates Through Cursors

� Can update tuples fetched by cursor by declaring that the cursor is for update

declare c cursor forselect *from account

where branch_name = ‘Perryridge’for update

� To update tuple at the current location of cursor c

update account

set balance = balance + 100

where current of c

Page 13: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Dynamic SQLDynamic SQLAllows programs to construct and submit SQL queries Allows programs to construct and submit SQL queries

at run time.at run time.

Example of the use of dynamic SQL from within a C Example of the use of dynamic SQL from within a C

program.program.

char * char * sqlprog = sqlprog = ““update update account account

setset balance = balance * balance = balance * 1.051.05

where where account_number = ?account_number = ?””

EXEC SQL EXEC SQL prepareprepare dynprogdynprog from from :sqlprog;:sqlprog;

charchar account account [10] = [10] = ““AA--101101””;;

EXEC SQL EXEC SQL execute execute dynprogdynprog using using :account;:account;

The dynamic SQL program contains a ?, which is a The dynamic SQL program contains a ?, which is a

place holder for a value that is provided when the place holder for a value that is provided when the

SQL program is executed.SQL program is executed.

Page 14: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Extensions:Procedural Extensions:

Stored Procedures Stored Procedures

Stored Procedure is a function in a shared Stored Procedure is a function in a shared library accessible to the database serverlibrary accessible to the database server

Can also write Stored Procedures using Can also write Stored Procedures using languages such as C or Javalanguages such as C or Java

Advantages of Stored Procedure : Advantages of Stored Procedure : –– Flexibility to SQL, Flexibility to SQL,

–– Reduced network traffic for speedReduced network traffic for speed

The more SQL statements that are grouped The more SQL statements that are grouped together for execution, the larger the savings together for execution, the larger the savings in network traffic in network traffic

Page 15: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Extensions:Procedural Extensions:

Stored Procedures Stored Procedures

In SQL, the analog of a subroutine is called a In SQL, the analog of a subroutine is called a Stored Stored Procedure (SP)Procedure (SP)..

Similarities between Similarities between SPsSPs and subroutinesand subroutines

–– SPsSPs can be written in many languagescan be written in many languages

–– An An SP returns a structureSP returns a structure

In SQLIn SQL--land this means a land this means a TableTable

A call to an A call to an SPSP can appear in the can appear in the FROMFROM clause clause of a queryof a query

Difference between Difference between SPsSPs and subroutinesand subroutines

–– An SP executes An SP executes in the in the DBMS'sDBMS's address spaceaddress space, not , not the clients'the clients'

This has This has hugehuge performance implications.performance implications.

Page 16: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Normal Database

Page 17: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Applications using

stored procedures

Page 18: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Bad news, Good newsBad news, Good newsStored Procedures are not in any SQL standardStored Procedures are not in any SQL standard

–– Each Server vendors' implementation is differentEach Server vendors' implementation is different

But each vendor gives porting advice, e.g., But each vendor gives porting advice, e.g., http://www.postgresql.org/docs/8.3/interactive/plpgsqlhttp://www.postgresql.org/docs/8.3/interactive/plpgsql--porting.htmlporting.html

Stored Proc can be Stored Proc can be veryvery efficient compared to SQLefficient compared to SQL

–– Suppose a program's logic is Suppose a program's logic is S1;S2;S1;S2;……;;SnSn, each Si is , each Si is

a SQL statementa SQL statement

ServerClient

S1

S2…

Sn

:query :answer

Implemented as SQL

ServerClient

S1

S2…

Sn

Implemented as SP

Page 19: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Efficiency of Efficiency of SPsSPsIf you write the program in If you write the program in SQLSQL, the cost , the cost isis–– 2n 2n context switches +context switches +–– n n network traversals to send queries to the server +network traversals to send queries to the server +–– nn network traversals to send answers to the clientnetwork traversals to send answers to the client

If you write the program as a If you write the program as a Stored Stored ProcedureProcedure, the cost is, the cost is–– 22 context switchescontext switches–– 11 network traversals to send queries to the servernetwork traversals to send queries to the server–– 11 network traversals to send answers to the clientnetwork traversals to send answers to the client

Depending on the size of n, the size of Depending on the size of n, the size of each query and the size of the each query and the size of the intermediate and final answers, this can intermediate and final answers, this can be a be a huge differencehuge difference..

Page 20: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Extensions:Procedural Extensions:

Functions / Stored Procedures Functions / Stored Procedures

Stored ProceduresStored Procedures

–– Named blocks of PL/SQLNamed blocks of PL/SQL complied program complied program

stored within the database stored within the database

–– Execute them using the Execute them using the Call Call statementstatement

–– Permit external applications to operate on the Permit external applications to operate on the

database without knowing about internal database without knowing about internal

detailsdetails

Functions are particularly useful with specialized Functions are particularly useful with specialized

data types such as images and geometric objectsdata types such as images and geometric objects

–– Example: functions to check if polygons Example: functions to check if polygons

overlap, or to compare images for similarityoverlap, or to compare images for similarity

TableTable--valued functions, valued functions, which can return a which can return a

relation as a resultrelation as a result

Page 21: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Extensions:Procedural Extensions:

Functions / Stored ProceduresFunctions / Stored Procedures

SQL provides a a rich set of imperative SQL provides a a rich set of imperative constructs including:constructs including:

–– For and While Loops For and While Loops

–– Assignment Assignment

–– ifif--thenthen--else statements.else statements.

SP returns a structure SP returns a structure TableTable

–– A call to an A call to an SPSP can appear in the can appear in the FROMFROMclause of a queryclause of a query

TableTable--valued functionsvalued functions, which can , which can return a relation as a result return a relation as a result

Page 22: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Extensions:Procedural Extensions:

Functions / Stored Procedures Functions / Stored Procedures

Stored Procedures can: Stored Procedures can:

–– Have parametersHave parameters

–– Invoke other procedures and functionsInvoke other procedures and functions

–– Return valuesReturn values

–– Raise exceptionsRaise exceptions

–– Syntax checked and compiled into pSyntax checked and compiled into p--codecode

–– The pThe p--code is stored in the databasecode is stored in the database

Creating stored proceduresCreating stored procedures

–– Write a stored procedure in a text file and process Write a stored procedure in a text file and process the commands using Client Interface tool (for the commands using Client Interface tool (for example, the Query Analyzer orexample, the Query Analyzer or

SQL Server Enterprise Manager in MS SQL SQL Server Enterprise Manager in MS SQL Server) Server)

Page 23: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

3 types of Parameters3 types of Parameters

Procedures can have 3 types of parametersProcedures can have 3 types of parameters–– ININ

used for inputused for input

–– OUTOUTused for outputused for output

side effects side effects ⇒⇒⇒⇒⇒⇒⇒⇒ hard to read / debug the codehard to read / debug the code

–– INOUTINOUTused for input + outputused for input + output

Functions Functions –– standard: only IN parametersstandard: only IN parameters

–– Oracle: all kinds of parametersOracle: all kinds of parametersDonDon’’t use OUT and INOUT with functions!t use OUT and INOUT with functions!

Page 24: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Compiling and recompiling Compiling and recompiling

stored proceduresstored procedures

Stored Procedures / Functions are Stored Procedures / Functions are

automatically compiled when recreated.automatically compiled when recreated.

If one of the tables used in a If one of the tables used in a

procedures is altered, the procedure / procedures is altered, the procedure /

function must be recompiledfunction must be recompiled

–– Alter procedure Alter procedure procedureNameprocedureName compile;compile;

Page 25: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Some PL/SQL Construct in Stored Some PL/SQL Construct in Stored

Procedures and FunctionsProcedures and Functions

Call Call pName(parameterspName(parameters))

–– call another procedurecall another procedure

Return valueReturn value

–– return from a functionreturn from a function

Variable := valueVariable := value

–– assignmentassignment

begin begin …… endend–– statement groupstatement group

if if conditioncondition then then statementsstatements else else statementsstatements end ifend if

For loopFor loop

While loopWhile loop

General loopGeneral loop–– Inner exit statementInner exit statement

Page 26: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

SQL statementsSQL statements

Stored Procedures / Functions can contain Stored Procedures / Functions can contain

SQL statementsSQL statements

–– select, insert, update, deleteselect, insert, update, delete

Select syntax [result: one value]Select syntax [result: one value]

–– select select attrattr into variableinto variable from from ……

Page 27: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

SQL FunctionsSQL FunctionsDefine a function that, given the name of a customer, returns Define a function that, given the name of a customer, returns

the count of the number of accounts owned by the customer.the count of the number of accounts owned by the customer.

Create function Create function account_count account_count ((customer_namecustomer_name varcharvarchar(20))(20))

returns integerreturns integer

beginbegin

declare declare a_counta_count integer;integer;

select count select count ((* * ) ) into into a_counta_count

from from depositordepositor

where where depositor.customer_name = depositor.customer_name = customer_namecustomer_name

return return a_counta_count;;

endend

Find the name and address of each customer that has more Find the name and address of each customer that has more

than one account.than one account.

select select customer_name, customer_street, customer_citycustomer_name, customer_street, customer_city

fromfrom customercustomer

wherewhere account_account_count (count (customer_name customer_name )) > 1> 1

Page 28: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Create Or Replace Procedure <name> (<Create Or Replace Procedure <name> (<arglistarglist>) AS >) AS <declarations><declarations>

BEGINBEGIN<procedure statements><procedure statements>

ENDEND

•• Tasks performed by the client applicationTasks performed by the client application•• Tasks performed by the stored procedure, when invokedTasks performed by the stored procedure, when invoked•• The CALL statementThe CALL statement•• Explicit parameter to be defined : Explicit parameter to be defined :

•• ININ: Passes a value to the stored procedure from the client applica: Passes a value to the stored procedure from the client applicationtion

•• OUTOUT: Stores a value that is passed to the client application when t: Stores a value that is passed to the client application when the he stored procedure terminates.stored procedure terminates.

•• INOUT :INOUT : Passes a value to the stored procedure from the client Passes a value to the stored procedure from the client application, and returns a value to the Client application wheapplication, and returns a value to the Client application when the n the stored procedure terminatesstored procedure terminates

SQL Stored Procedures SQL Stored Procedures

Page 29: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

CREATE PROCEDURE CREATE PROCEDURE UPDATE_SALARY_1 UPDATE_SALARY_1 (IN (IN EMPLOYEE_NUMBEREMPLOYEE_NUMBER CHAR(6), CHAR(6),

IN IN RATERATE INTEGER) INTEGER)

LANGUAGE SQL LANGUAGE SQL BEGINBEGIN

UPDATE EMPLOYEE UPDATE EMPLOYEE SET SALARY = SALARY * (1.0 * SET SALARY = SALARY * (1.0 * RATERATE / 100.0 )/ 100.0 )WHERE SSN = WHERE SSN = EMPLOYEE_NUMBEREMPLOYEE_NUMBER;;

ENDEND

LANGUAGE value of SQL and the BEGIN...END block, which forms theLANGUAGE value of SQL and the BEGIN...END block, which forms the procedure body, are particular procedure body, are particular to an SQL procedureto an SQL procedure

1)1)The stored procedure name is UPDATE_SALARY_1. The stored procedure name is UPDATE_SALARY_1.

2)The two parameters have data types of CHAR(6) and INTEGER. Bot2)The two parameters have data types of CHAR(6) and INTEGER. Both are input h are input parameters. parameters.

3)LANGUAGE SQL indicates that this is an SQL procedure, so a pro3)LANGUAGE SQL indicates that this is an SQL procedure, so a procedure body follows cedure body follows the other parameters.the other parameters.

4)The procedure body consists of a single SQL UPDATE statement, 4)The procedure body consists of a single SQL UPDATE statement, which updates rows which updates rows

in the employee table.in the employee table.

Page 30: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

SQL ProceduresSQL ProceduresThe The account_countaccount_count function could instead be written as procedure:function could instead be written as procedure:

Create procedure Create procedure account_count_procaccount_count_proc ((in in customer_namecustomer_name varcharvarchar(20), (20),

out out a_counta_count integerinteger))

beginbegin

select countselect count((**) ) into into a_counta_count

from from depositordepositor

where where depositor.customer_name = depositor.customer_name =

account_count_proc.account_count_proc.customer_namecustomer_name

endend

Procedures can be invoked either from an SQL procedure or from Procedures can be invoked either from an SQL procedure or from

embedded SQL, using the embedded SQL, using the callcall statement.statement.

declare declare a_counta_count integerinteger;;

call call account_count_procaccount_count_proc( ( ‘‘SmithSmith’’, , a_counta_count););

Procedures and functions can be invoked also from dynamic SQLProcedures and functions can be invoked also from dynamic SQL

SQL:1999 allows more than one function/procedure of the same SQL:1999 allows more than one function/procedure of the same

name (called name name (called name overloadingoverloading), as long as the number of ), as long as the number of

arguments differ, or at least the types of the arguments differarguments differ, or at least the types of the arguments differ

Page 31: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Constructs Procedural Constructs

•• CASE statementCASE statement

•• FOR statementFOR statement

•• GOTO statementGOTO statement

•• IF statementIF statement

•• ITERATE statementITERATE statement

•• RETURN statementRETURN statement

•• WHILE statementWHILE statement

Page 32: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural ConstructsProcedural Constructs

Compound statement: Compound statement: begin begin …… endend, ,

–– May contain multiple SQL statements between May contain multiple SQL statements between begin begin

and and endend..

–– Local variables can be declared within a compound Local variables can be declared within a compound

statementsstatements

While While and and repeatrepeat statements:statements:

declare declare n n integer default integer default 0;0;while while n n < 10 < 10 dodoset set n n = = n n + 1+ 1

end whileend while

repeatrepeatset set n n = = n n –– 11

until until nn = 0= 0end repeatend repeat

Page 33: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Constructs (Cont.)Procedural Constructs (Cont.)

ForFor looploop–– Permits iteration over all results of a queryPermits iteration over all results of a query

–– Example: find total of all balances at the Example: find total of all balances at the

PerryridgePerryridge branchbranch

declare declare n n integer default integer default 0;0;

for for r r asas

select select balance balance

from from accountaccount

where where branch_name branch_name = = ‘‘PerryridgePerryridge’’

dodo

set set n n = = n n + + r.r.balancebalance

end forend for

Page 34: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Procedural Constructs (cont.)Procedural Constructs (cont.)Conditional statements (ifConditional statements (if--thenthen--else)else)E.g. To find sum of balances for each of three categories of accE.g. To find sum of balances for each of three categories of accounts ounts (with balance <1000, >=1000 and <5000, >= 5000)(with balance <1000, >=1000 and <5000, >= 5000)

ifif rr..balance balance < 1000< 1000then set then set ll = = ll + + rr..balancebalance

else ifelse if rr..balance balance < 5000< 5000then set then set m m = = m m + + rr..balancebalance

elseelse set set h h = = h h + + rr..balancebalanceend ifend if

SQL:1999 also supports a SQL:1999 also supports a case statementcase statement similar to C case statementsimilar to C case statement

Signaling of exception conditions, and declaring handlers for exSignaling of exception conditions, and declaring handlers for exceptionsceptions

declare declare out_of_stockout_of_stock conditionconditiondeclare declare exit handler forexit handler for out_of_stockout_of_stockbeginbegin…….. .. signalsignal outout--ofof--stockstockendend

–– The handler here is The handler here is exit exit ---- causes enclosing causes enclosing begin..endbegin..end to be exitedto be exited

–– Other actions possible on exceptionOther actions possible on exception

Page 35: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

CREATE PROCEDURECREATE PROCEDURE UPDATE_SALARY_IFUPDATE_SALARY_IF

(IN (IN employee_numberemployee_number CHAR(6), CHAR(6), IN IN ratingrating SMALLINT)SMALLINT)

LANGUAGE SQLLANGUAGE SQL

BEGINBEGINSET counter = 10;SET counter = 10;

WHILEWHILE (counter > 0) (counter > 0) DODOIFIF ((ratingrating = 1)= 1)

THEN THEN UPDATEUPDATE employeeemployeeSETSET salary = salary * 1.10, bonus = 1000salary = salary * 1.10, bonus = 1000WHERE WHERE empnoempno = = employee_numberemployee_number;;

ELSE IFELSE IF (rating = 2)(rating = 2)THEN UPDATE employeeTHEN UPDATE employee

SET salary = salary * 1.05, bonus = 500SET salary = salary * 1.05, bonus = 500WHERE WHERE empnoempno = = employee_numberemployee_number;;

ELSE ELSE UPDATE employeeUPDATE employee

SET salary = salary * 1.03, bonus = 0SET salary = salary * 1.03, bonus = 0WHERE WHERE empnoempno = = employee_numberemployee_number;;

END IF;END IF;

SET counter = counter SET counter = counter –– 1;1;END WHILEEND WHILE;;

ENDEND

Page 36: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Calling Stored ProcedureCalling Stored Procedure

SyntaxSyntax

ProcedureNameProcedureName (Parameter1, Parameter2, (Parameter1, Parameter2, ……))

Two ways to link formal and actual Two ways to link formal and actual

parametersparameters

–– PositionPosition

Like Java: 1Like Java: 1stst parameter formal parameter linked to parameter formal parameter linked to

11stst actual parameter, etc.actual parameter, etc.

–– NamedNamed

FormalParameterNameFormalParameterName => value=> value

Page 37: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Invoking Procedures Invoking Procedures

Can invoke Stored procedure stored at the Can invoke Stored procedure stored at the location of the database by using the SQL CALL location of the database by using the SQL CALL statementstatement

Nested SQL Procedures:Nested SQL Procedures:

To call a SQL procedure from within a caller SQL To call a SQL procedure from within a caller SQL procedure, simply include a CALL statement with procedure, simply include a CALL statement with the appropriate number and types of parameters the appropriate number and types of parameters in your caller procedure.in your caller procedure.

CREATE PROCEDURE NEST_SALES(CREATE PROCEDURE NEST_SALES(OUT OUT budget budget DECIMAL(11,2))DECIMAL(11,2))LANGUAGE SQLLANGUAGE SQL

BEGINBEGINDECLARE DECLARE total total INTEGER DEFAULT 0;INTEGER DEFAULT 0;SET SET totaltotal = 6;= 6;CALL SALES_TARGET(total);CALL SALES_TARGET(total);SET SET budget budget = = totaltotal * 10000;* 10000;

ENDEND

Page 38: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Variables are declared

after the keyword AS

Parameters

Page 39: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

External Languages:External Languages:

Functions / Stored ProceduresFunctions / Stored Procedures

SQL:1999 permits the use of SQL:1999 permits the use of functions and procedures written in functions and procedures written in

other languages such as C or C++ other languages such as C or C++

Declaring external language procedures and functionsDeclaring external language procedures and functions

create procedure create procedure account_count_proc(account_count_proc(inin customer_name customer_name varcharvarchar(20),(20),

out out count count integerinteger))

language language CC

external name external name ’’//usr/avi/bin/account_count_procusr/avi/bin/account_count_proc’’

create function create function account_count(account_count(customer_name customer_name varcharvarchar(20))(20))

returns returns integerinteger

language language CC

external name external name ‘‘//usr/avi/bin/account_countusr/avi/bin/account_count’’

Page 40: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

External Language Routines (Cont.)External Language Routines (Cont.)

Benefits of external language functions/procedures: Benefits of external language functions/procedures:

–– more efficient for many operations, and more expressive more efficient for many operations, and more expressive

powerpower

DrawbacksDrawbacks

–– Code to implement function may need to be Code to implement function may need to be loaded into loaded into

database system and executed in the database systemdatabase system and executed in the database system’’s s

address spaceaddress space

risk risk of accidental corruption of database structuresof accidental corruption of database structures

security risk, allowing users access to unauthorized datasecurity risk, allowing users access to unauthorized data

–– There are alternatives, which give good security at the cost of There are alternatives, which give good security at the cost of

potentially worse performancepotentially worse performance

–– Direct execution in the database systemDirect execution in the database system’’s space is used when s space is used when

efficiency is more important than securityefficiency is more important than security

Page 41: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Security with External Language Security with External Language

RoutinesRoutinesTo deal with security problemsTo deal with security problems

–– Use Use sandboxsandbox techniquestechniques

that is use a safe language like Java, which cannot be that is use a safe language like Java, which cannot be

used to access/damage other parts of the database used to access/damage other parts of the database

codecode

–– Or, run external language functions/procedures in a Or, run external language functions/procedures in a

separate process, with no access to the database processseparate process, with no access to the database process’’

memorymemory

Parameters and results communicated via interParameters and results communicated via inter--process process

communicationcommunication

Both have performance overheadsBoth have performance overheads

Many database systems support both above approaches as Many database systems support both above approaches as

well as direct executing in database system address spacewell as direct executing in database system address space

Page 42: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Table FunctionsTable Functions

Functions that Functions that return a relation as a resultreturn a relation as a result

Example: Return all accounts owned by a given customerExample: Return all accounts owned by a given customer

Create function Create function accounts_ofaccounts_of ((customer_namecustomer_name char(20)char(20)

returns returns table table ( ( account_numberaccount_number char(10),char(10),branch_namebranch_name char(15),char(15),balancebalance numeric(12,2)) numeric(12,2))

ASAS

return return

(Select (Select account_numberaccount_number, branch_name, balance, branch_name, balanceFrom From account Aaccount AWhere Exists (Where Exists (

Select *Select *From From depositor Ddepositor DWhere Where D.customer_nameD.customer_name = =

accounts_of.customer_nameaccounts_of.customer_name andandD.account_numberD.account_number = = A.account_numberA.account_number ));));

Page 43: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Table Table FunctionsFunctions(cont(cont’’dd))

Use the created table in Use the created table in FromFrom clause in clause in

SQL like base table or view:SQL like base table or view:

Select *Select *

From From table table ((accounts_of accounts_of ((‘‘SmithSmith’’))););

Page 44: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Table Functions Table Functions (cont(cont’’d) d)

CREATE FUNCTIONCREATE FUNCTION TrackingItemsModified(@minIdTrackingItemsModified(@minId intint) )

RETURNS RETURNS @@trackingItemstrackingItems TABLETABLE

( Id ( Id intint NOT NULL, NOT NULL,

Issued date NOT NULL, Issued date NOT NULL,

Category Category intint NOT NULL, NOT NULL,

Modified Modified datetimedatetime NULL ) AS NULL ) AS

BEGIN BEGIN INSERT INTO @INSERT INTO @trackingItemstrackingItems (Id, Issued, Category) (Id, Issued, Category)

SELECT SELECT ti.Idti.Id, , ti.Issuedti.Issued, , ti.Categoryti.Category

FROM FROM TrackingItemTrackingItem titi

WHERE WHERE ti.Idti.Id >= @>= @minIdminId; ;

UPDATE @UPDATE @trackingItemstrackingItems

SET Category = SET Category = CategoryCategory + 1, + 1,

Modified = GETDATE() Modified = GETDATE()

WHERE Category%2 = 0; WHERE Category%2 = 0;

RETURN; RETURN;

END; END;

Page 45: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

UserUser--Defined TypesDefined Types

Create type Create type construct in SQL creates construct in SQL creates useruser--defined defined typetype

Create typeCreate type DollarsDollars as numeric (12,2) finalas numeric (12,2) final

Create domainCreate domain construct creates construct creates useruser--defined defined domain typesdomain types

Create domainCreate domain person_name person_name charchar(20) (20) not nullnot null

Types and domains are similar. Domains can Types and domains are similar. Domains can have constraints, such as not null, specified on have constraints, such as not null, specified on themthem..

Page 46: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Scalar UserScalar User--Defined TypesDefined Types

A Scalar userA Scalar user--defined function returns one of the scalar data defined function returns one of the scalar data typestypes

CREATE FUNCTION CREATE FUNCTION WhichContinentWhichContinent (@(@CountryCountry varchar(15)) varchar(15))

RETURNS varchar(30) RETURNS varchar(30)

AS AS

BEGIN BEGIN

declare @return varchar(30) declare @return varchar(30)

select @return = select @return = CaseCase @@Country Country

when 'Argentina' then 'South America' when 'Argentina' then 'South America'

when 'Belgium' then 'Europe' when 'Belgium' then 'Europe'

when 'Brazil' then 'South America' when 'Brazil' then 'South America'

when 'Canada' then 'North America' when 'Canada' then 'North America'

when 'Denmark' then 'Europe' when 'Denmark' then 'Europe'

when 'Finland' then 'Europe' when 'Finland' then 'Europe'

when 'France' then 'Europe' when 'France' then 'Europe'

else 'Unknown' else 'Unknown'

End End

return @return return @return

End End

Page 47: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Scalar UDTScalar UDT

Can be used anywhere a varchar(30) Can be used anywhere a varchar(30) expression is allowed such as a computed expression is allowed such as a computed column in a table, view, SQL select list column in a table, view, SQL select list

Use of UDTUse of UDT

Select Select dbo.WhichContinent(Customers.Countrydbo.WhichContinent(Customers.Country),), Customers.nameCustomers.name

From From Customers;Customers;

Create Create table testtable test (Country varchar(15), (Country varchar(15),

Continent as (Continent as (dbo.WhichContinent(Countrydbo.WhichContinent(Country)))) ))

Insert into Insert into testtest values (values (‘‘USAUSA’’););

Page 48: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

MultiMulti--statement Tablestatement Table--Value UserValue User--Defined FunctionDefined Function

CREATE FUNCTION CREATE FUNCTION dbo.dbo.customersbycountrycustomersbycountry ( ( @Country@Country varchar(15) ) varchar(15) )

RETURNS RETURNS @@CustomersbyCountryTabCustomersbyCountryTab table ( table (

[[CustomerIDCustomerID] [] [ncharnchar] (5), [] (5), [CompanyNameCompanyName] [] [nvarcharnvarchar] (40), ] (40),

[[ContactNameContactName] [] [nvarcharnvarchar] (30), [] (30), [ContactTitleContactTitle] [] [nvarcharnvarchar] (30), ] (30),

[Address] [[Address] [nvarcharnvarchar] (60), ] (60),

[City] [[City] [nvarcharnvarchar] (15), ] (15),

[[PostalCodePostalCode] [] [nvarcharnvarchar] (10), ] (10),

[Country] [[Country] [nvarcharnvarchar] (15), [Phone] [] (15), [Phone] [nvarcharnvarchar] (24), [Fax] [] (24), [Fax] [nvarcharnvarchar] (24) ) ] (24) )

AS AS

BEGIN BEGIN

INSERT INTO INSERT INTO @@CustomersByCountryTabCustomersByCountryTab

SELECT [SELECT [CustomerIDCustomerID], ],

[[CompanyNameCompanyName], [], [ContactNameContactName], [], [ContactTitleContactTitle], [Address], [City], [], [Address], [City], [PostalCodePostalCode], ], [Country], [Phone], [Fax] [Country], [Phone], [Fax]

FROM [FROM [Northwind].[dbo].[CustomersNorthwind].[dbo].[Customers] ]

WHERE country = WHERE country = @Country@Country

DECLARE @DECLARE @cntcnt INT INT

SELECT @SELECT @cntcnt = COUNT(*) = COUNT(*)

FROM FROM @@customersbyCountryTabcustomersbyCountryTab

IF @IF @cntcnt = 0 = 0

INSERT INTO INSERT INTO @@CustomersByCountryTabCustomersByCountryTab ( [( [CustomerIDCustomerID], [], [CompanyNameCompanyName], [], [ContactNameContactName], ], [[ContactTitleContactTitle], [Address], [City], [], [Address], [City], [PostalCodePostalCode], [Country], [Phone], [Fax] ) ], [Country], [Phone], [Fax] )

VALUES ('','No Companies Found','','','','','','','','') VALUES ('','No Companies Found','','','','','','','','')

RETURN RETURN

END END

SELECT * FROM SELECT * FROM dbo.customersbycountry('USAdbo.customersbycountry('USA') ')

SELECT * FROM SELECT * FROM dbo.customersbycountry('CANADAdbo.customersbycountry('CANADA') ')

SELECT * FROM SELECT * FROM dbo.customersbycountry('ADFdbo.customersbycountry('ADF') ')

Page 49: Introduction of SQL Programming - csuohio.educis.csuohio.edu/~sschung/cis612/LectureNoteStoredProcedure... · Embedded SQL A language to which SQL queries are embedded is referred

Inline TableInline Table--Value UserValue User--Defined FunctionDefined Function

CREATE FUNCTION CREATE FUNCTION CustomersByContinentCustomersByContinent (@(@Continent Continent varchar(30)) varchar(30))

RETURNS TABLE RETURNS TABLE

AS AS

RETURN RETURN

SELECT SELECT dbo.WhichContinent(Customers.Countrydbo.WhichContinent(Customers.Country)) as continent, as continent, Customers.* Customers.*

FROM FROM Customers Customers

WHERE WHERE dbo.WhichContinent(Customers.Countrydbo.WhichContinent(Customers.Country)) = @= @Continent Continent

SELECT * from SELECT * from CustomersbyContinent(CustomersbyContinent('North'North America') America')

SELECT * from SELECT * from CustomersByContinentCustomersByContinent('South('South America') America')

SELECT * from SELECT * from CustomersbyContinent(CustomersbyContinent('Unknown'Unknown') ')