SQL: A COMMERCIAL DATABASE LANGUAGE
Database Programming/ Using SQL in an Application
1. Introduction 2. Data Definition, Basic Constraints, and Schema Changes 3. Basic Queries 4. More complex Queries 5. Aggregate Functions and Grouping 6. Advanced Querying Issues 7. Summary of SQL Queries 8. Data Change statements 9. Views 10. Complex Constraints 11. Database Programming
• We are interested in creating programs that involve a mixture of SQL statements. The conventional language. will supply features that are unavailable to SQL (e. and statements from a conventional language.
.10. called the host language.1 Motivation (1)
• Up to now we have seen SQL as an interactive language: we type a query and see the results on the screen. assignment statements and error handling).g. The SQL statements will enable the program to access the database. control mechanisms such as if and while statements.
• We discuss some advanced features of SQL that address the issues involved in this type of execution. Cobol. Java or Visual Basic.1 Motivation (2)
• In most SQL applications.10.
. SQL statements are part of an application program written in some conventional language such as C.
2 Issues Involved (1)
• SQL constructs can be included in an application program in two different ways: through a Statement-Level Interface (SLI). or a Call-Level Interface (CLI).10.
• Before the program can be compiled by the host language compiler. the created host language procedures communicate with the DBMS. • At run time.2 Issues Involved (2)
Statement-Level Interface (SLI). which takes the actions necessary to cause the SQL statements to be executed. • The SQL constructs appear as new statement types in the program.
. The program is a mixture of two statement types: the host language and the new statement types. the SQL constructs must be processed by a precompiler.10. which translates the constructs into calls to host language procedures. • The entire program can then be compiled by the host language compiler.
• The SQL constructs can take two forms: .Embedded SQL: the SQL constructs are ordinary SQL statements (e.
.g. SELECT. .Dynamic SQL: the SQL constructs are directives for preparing and executing SQL statements. but the SQL statements appear in the program as the values of string variables that are constructed by the host language portion of the program at run time.10. Embedded SQL is also referred to as Static SQL. • SQLJ – a version of SLI designed specifically for Java – was standardized in SQL:2003.2 Issues Involved (3)
Statement-Level Interface (SLI). INSERT).
no precompiler is needed.2 Issues Involved (4)
Call-Level Interface (CLI). • Unlike Static and Dynamic SQL.
. These variables are passed as arguments to host language procedures provided by the CLI. Since no special syntax is used. is a CLI specifically designed for Java (SQL:2003) and ODBC (Open DataBase Connectivity).10. • JDBC (Java DataBase Connectivity). As with Dynamic SQL. is a CLI that can be used with many languages (SQL:1999). the application program is written entirely in the host language. SQL statements are the values of string variables constructed at run time.
• We will use pseudocode as the host programming language. we may refer to host program variables. • The programmer should declare program variables to match the data types of the database attributes that the program will process.
.3 Embedded SQL
• The embedded SQL statement is distinguished from programming language statements by prefixing it with a special character or command so that a preprocessor can extract the SQL statements. These program variables may or may not have names that are identical to their corresponding attributes.10. the keywords EXEC SQL precede any SQL statement. Within an embedded SQL command. which are prefixed by a “:” sign. • Usually.
.4 Status Processing (1)
• In the real world. For example. things do not always proceed smoothly. In other situations. the server might be down or reject the connection. an SQL statement may execute correctly and return the outcome of the execution.10. when you attempt to connect to a database on a distant server.
• SQL provides two mechanisms for returning information describing such situations to the host program: a five character string variable SQLSTATE and a diagnostics area.
the particular exception situation can be determined. If not.
. and appropriate action can be taken.4 Status Processing (2)
• An implicit five-character string variable SQLSTATE communicates to the program the status of SQL embedded commands.
• If the value of SQLSTATE is 00000.10. the last statement executed successfully.
• The DBMS sends information to be stored in that variable after each SQL statement is executed.
4 Status Processing (3)
• Instead of checking status after each SQL statement.10. Then. • The WHENEVER statement remains in effect until another statement is executed. we can include a single WHENEVER statement anywhere before the first SQL statement is executed: EXEC SQL WHENEVER SQLERROR GOTO label.
. any nonzero status in a subsequently executed statement causes a transfer of control to label.
The diagnostics area records information about all exceptions raised. • Detailed information about the outcome of the last executed SQL statement can be retrieved from the diagnostics area using a GET DIAGNOSTICS statement.4 Status Processing (4)
• The diagnostics area is a data structure that contains information about the execution status of the most recent SQL statement. • A single SQL statement may raise several exceptions.10.
In that way: .data extracted from the database can be processed by the host language statements.
. • The declarations are included between EXEC SQL BEGIN DECLARE SECTION. and . and EXEC SQL END DECLARE SECTION so that they can be easily found and processed by the precompiler.5 Variable declaration (1)
• For the application program as a whole to communicate with the database. • Before the embedded SQL statements. host language statements and SQL statements must be able to access common variables. we declare variables of the host program (host variables) that are used for this purpose.10.results computed by the host language portion of the program can be stored in the database.
5 Variable declaration (2)
• Example: The following group of statements declares variables of the host program. minit . sex .
. dnumber. fname . EXEC SQL BEGIN DECLARE SECTION varchar dname . lname .10. raise. EXEC SQL END DECLARE SECTION • SQLSTATE is declared within the declaration section since it is used for communication between the DMBS and the host language portion of the application. This declaration is required in all embedded SQL programs. float salary. char ssn . bdate . char SQLSTATE . address . int dno.
:address. address. minit.6 Single row statements (1)
• Example: Write a program segment (loop) that reads a social security number and prints out some information from the corresponding EMPLOYEE tuple
loop:= 'Y'. writeln('more SS numbers (Y or N)? '). :lname. SALARY INTO :fname.10. :bdate. while loop = 'Y' do begin writeln('input social security number:').
. lname. if SQLSTATE = ‘00000’ then writeln(fname. LNAME. EXEC SQL SELECT FNAME. :salary FROM EMPLOYEE WHERE SSN = :ssn . readln(loop) end. :minit. MINIT. readln(SSN). ADDRESS. BDATE. salary) else writeln(‘ssn does not exist’).
• Host variables that occur in WHERE clauses correspond to in parameters.6 Single row statements (2)
• We can think of the host language variables as parameterizing the SQL statement.10. not table or column names or structured data. while those used in INTO clauses correspond to out parameters. They are used to communicate scalar values.
the number of rows in the result set in not know until the statement is executed. Thus. that is why we are able to assign its attribute values directly to program variables. An SQL query returns a table which we refer to as the query result or result set.10.
. • In general. • One of the advantages of SQL as a database language is that its statements can deal with entire tables.7 Cursors (1)
• In the previous program segment. • If we want to include an SQL SELECT statement in a host language program. an SQL query can retrieve many tuples. we face the problem of allocating storage within the program for an unknown number of rows. a single tuple is selected by the embedded SQL query.
This difference is often called an impedance mismatch.10.the fundamental unit dealt with by an SQL statement is a set of tuples.7 Cursors (2)
• This problem points up a fundamental difference between SQL and the host language: .the fundamental unit dealt with by a statement in a host language is a variable. whereas . • The SQL mechanism for solving this problem is the cursor.
. It allows a tuple-at-a-time processing or a query set by the host program.
• A subsequent OPEN cursor command fetches the query result and sets the cursor to a position before the first row in the result of the query.
. this becomes the current row for the cursor.10. • Subsequent FETCH commands in the program advance the cursor to the next row and copy its attribute values into program variables specified in the FETCH command. • The cursor is declared when the SQL query command is specified.7 Cursors (3)
• We can think of a cursor as a pointer that points to a single tuple (row) from the result of a query.
10. then lists the names of employees who work in that department. The program reads a raise amount for each employee and updates the employee's salary by that amount. and a list of the names of any attributes that will be updated follows. .The condition WHERE CURRENT OF cursor specifies that the current tuple is the one to be updated (or deleted) Example: Write a program segment that reads (inputs) a department name. . one at a time.A CLOSE cursor command is issued to indicate that we are done with the result of the query.7 Cursors (4)
.When a cursor is defined for rows that are to be updated the clause FOR UPDATE OF must be in the cursor declaration.
:salary.10. :fname.7 Cursors (5)
writeln('enter the department name:'). :minit. LNAME. MINIT. EXEC SQL OPEN EMP. EXEC SQL SELECT DNUMBER INTO :dnumber FROM DEPARTMENT WHERE DNAME =: dname. readln(DNAME). FNAME.
. SALARY FROM EMPLOYEE WHERE DNO =: dnumber FOR UPDATE OF SALARY. :lname. EXEC SQL DECLARE EMP CURSOR FOR SELECT SSN. EXEC SQL FETCH EMP INTO :ssn.
10. EXEC SQL FETCH EMP INTO :ssn. fname. end. :minit. writeln('enter raise amount: ').7 Cursors (6)
while SQLSTATE = '00000' do begin writeln('employee name: '.
. minit. EXEC SQL UPDATE EMPLOYEE SET SALARY = SALARY + :raise WHERE CURRENT OF EMP. :fname. :lname. EXEC SQL CLOSE CURSOR EMP.lname). :salary. readln(raise).