Documente Academic
Documente Profesional
Documente Cultură
Views
Concept of an index
Embedded SQL
In todays session we would be discussing about the concept of views, the concept of an index and
how it is useful in database implementations and the concept embedded SQL programming using
pro*c.
Views
Views is an important and useful feature in RDBMS. It helps achieve sharing with proper security.
We will be looking at
What is a view
How to create a view
How to update/delete a view
Different types of views
Advantages and disadvantages of views in the next few slides
What is a view?
A view is a kind of virtual table
Contents are defined by a query like:
Select Empno, Name, age from
Employee
Where designation=developer;
As shown in the figure
Copyright 2004,
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Views are tables whose contents are taken or derived from other tables.
To the user, the view appears like a table with columns and rows
But in reality, the view doesnt exists in the database as a stored set of values
The rows and columns that we find inside a view are actually the results generated by a query that
defines the view
View is like a window through which we see a limited region of the actual table
The table from where the actual data is obtained is called the source table
Copyright 2004,
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
For simple queries the results are generated row by row on the fly.
For more complex views the DBMS must generate a temporary table representing the view and later
discard it.
Create a view
CREATE VIEW ViewSupplier
AS SELECT *
FROM Supplier;
Copyright 2004,
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
You must have permission on the table refereed in the view to successfully create the view
Can assign a new name to each column chosen in the view
Only names can be different. The data type etc remain the same as the source table because, the
values are after all going to be derived from that table
If no names are specified for columns, the same name as used in the source table is used
Copyright 2004,
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
We can assign names for the various columns in the view. This may be totally different from what
has been used in the source table
Types of views
Horizontal views
Vertical views
Row/column subset views
Grouped views
Joined views
Copyright 2004,
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Based on how the view is created. We will discuss them in detail in the following slides
Horizontal views
Create view Bgraders as select * from employee where grade =B;
Bgraders
Employee
Copyright 2004,
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Here a horizontal subset of the source table is taken to create the view.
Very useful when data belonging to different categories are present in the table.
A private( virtual) table for each category can be created and given access to the person concerned
Vertical views
A view which selects only
few columns of a table:
Genemp
For e.g:
Create view Genemp as
select Empno, Name, Age
from Employee;
Copyright 2004,
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Copyright 2004,
10
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
SQL standard doesnt define any notion of horizontal or vertical views . It is for our own
understanding that we have given names for views which select only selected rows/columns from the
source table as horizontal/vertical views. There could be a combination of these two concepts where
a view selects a subset of rows and columns
10
Grouped views
The query contains a group by clause
Copyright 2004,
11
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Grouped views are created based on a grouped query. They group rows of data and produce one
row in the result corresponding to each group
So, the rows in the view dont have a one to one correspondence with the rows of the source table
For this reason , grouped views cannot be updated.
11
Joined views
Created by specifying a two-table or three-table query in the view creation
command
Copyright 2004,
12
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
(Refer to the supplier,parts, shipment tables we have used in our earlier slides on DDL,DML)
The advantage with this type of view is, any subsequent info can be extracted from this view as a
single-table query instead of writing a more complex two or three table query . For e.g:
SELECT Supplier_id, Partname, SUM(Qty) from SHIP_VIEW
(Group by Supplier_id, Partname;
Would help extract data which is actually spread over more than one table
12
Updating a VIEW
Copyright 2004,
13
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Depending on the commercial implementation being used, views may or may not be updateable. In some
cases, all views are not updateable. In some others a view is updateable if it is from one table, else it is not. In
still others, a view is updateable if it is the result of a simple query; if it is defined by some GROUP BY
statements, for example, the view is not updateable.
According to ANSI/ISO standards, A view is updatable if
The DBMS is able to trace back the rows and columns of the view to the corresponding rows and columns of
the source table.
So a view is updatable if :
DISTINCT is not specified in the query used to create the view
The FROM clause specifies only one source table
The select list doesnt contain expressions/calculated columns
The WHERE clause doesnt include a subquery
The query doesnt include a GROUP BY or HAVING
An example of a view which cant be updated is given in the next slide
13
An example
C rea te view view _su p p lier
As
S elect S u p p n um , su p p na m e, city
F rom S u p plier
W h ere
C ity = " D elh i";
ER/CORP/CRS/DB07/003
Version No: 2.0
The newly inserted row, gets added to the source table subject to non-violation of other integrity
constraints. What is the result of a Select * from view_suppliers? It shows only the details of suppliers
belonging to Delhi. Why?
Reason is, the view is created to display only suppliers based at Delhi.
To ensure that the user of the view, view_supplier should not be able to add data for any other town
than "Delhi", check option can be used as follows:
CREATE VIEW View_Supplier
AS
SELECT Suppnum, Suppname, City
FROM Supplier
WHERE
City=Delhi WITH CHECK OPTION
14
Dropping Views
Views are dropped similar to the way in which
the tables are dropped. However, you must
own a view in order to drop it.
DROP VIEW <view name>;
DROP VIEW ViewSupplier;
Copyright 2004,
15
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
15
Advantages of views
Security
Query simplicity
Structural simplicity
Copyright 2004,
16
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Security: only a limited set of rows/ columns are viewable by certain users
Query simplicity: A view can derive data from many tables. So, subsequently we can use queries on
the view as single table queries rather than writing queries against the source tables as multi-table
queries
Structural simplicity: views can show only a portion of the table which is relevant to the user there by
keeping it simple.
16
Disadvantages of views
Performance
Restrictions
Copyright 2004,
17
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
Performance: views based on joins are merely virtaul tables. Every time a query is placed against the
view, the query representing creation of the view has to be executed . So, complex joins may have to
be performed every time a query is placed against the view.
Restrictions: Not all views are updateable
17
Concept of an Index
18
What is an index?
Physical storage structure
Provides rapid access to rows of a table
Mostly created on the primary key column
Can be created on any other column also
Transparent to the user
Copyright 2004,
19
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
An index is like the index page we see at the end of a book or like the index card used in a library. Let
us understand this
Say you wish to know where you can find some description on linkage editors in a system software
book. Imagine how difficult it is if you have to go through all the pages of the book to locate this
information.
Instead, if you go through the index which is sorted based on alphabetical order, it is very easy to
locate a term called linkage editor under the letter L. Now against this term you will find the page
numbers where this information is present in the book. So, you can straightawy go to that page
number(s) and find your information. Apply the same principle to searching for a row in a database
table. If you want to locate those rows of the employee table where the department is finance, if you
have to search through the entire hard disk to locate this information, it would be extremely time
consuming. Instead, if we store an index in a specific block of the disk which contains something like
the following
Department
address
Finance
2001f, 4005f,1002f
HRD
2000f, 3045f
Then you know that you have look for rows corresponding to finance dept only in three locations in
the hard disk. Here the index has been formed on the department column.
This is the benefit of having indexes.
19
Advantage
Speeds the execution of search queries
Disadvantages
Consumes additional disk space
Must be updated for every row insert into the table and also for every update
of the key column
Copyright 2004,
20
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
20
Creation of index-Syntax
Creation:
CREATE [unique] INDEX index-name ON Table-name (column-name)
E.g : CREATE UNIQUE INDEX Emp_index ON Employee (Empid);
Deletion:
DROP INDEX index-name
E.g: DROP INDEX Emp_index;
Copyright 2004,
21
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
21
Embedded SQL
22
Copyright 2004,
23
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
a) The first step in processing an SQL is Parsing. The statement is split into words and checked
against syntax. Syntax errors and spelling mistakes can be detected at this stage
b)
The second step is Validation. Semantic errors are checked. It is verified as to whether the
tables referred in the query are present, whether column names are valid etc. The system
catalog is refereed for this purpose
c)
The next step is optimization. RDBMS explores possibility of using an index, the order of
execution of join etc
d) The next step is to generate the Application plan. It is binary representation of the sequence of
steps to be executed by the DBMS in executing the query
e) The Application plan is executed.
23
Copyright 2004,
24
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
24
Copyright 2004,
25
Infosys Technologies Ltd
1.
ER/CORP/CRS/DB07/003
Version No: 2.0
The Embedded SQL program is submitted to a precompiler. This is a language specific tool. Ir we have
separate precompiler for c, for
cobol etc.
2. The precompiler generates two files as output. One is the source file in which all SQL commands are
removed and replaced with calls to some special DBMS routines. These routines provide the necessary
run-time link with the DBMS. This is aut0-generated by the precompiler
The other file is the DBRM (Data Base Request Module). This contains all the SQL commands removed from
the program
3. Now, this source file is compiled by the compiler to generate the object file.
4. The linker links the object code with other library routines (which includes the DBMS library) and generates
the executable
5. parallely, the DBRM is submitted to a Bind program. This program parses each SQL statement, validates,
optimizes and generates the binary DBMS-executable form called the application plan. After all statements
are thus converted , the combined application plan is stored under the DBMS with the same name as the
application name from where the SQL statements were stripped off
6. The run-time communication between the executable form of source program and the Application plan is
totally hidden .
25
EXEC SQL
Keyword indicates to the pre compiler that the next line of code is for the
SQL handling.
The block of sql code is ended with a ;
Copyright 2004,
26
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
This depends on the host language . EXEC SQL is a common way to begin. But the way to end is
language specific.
26
EXEC SQL
INSERT INTO Supplier
VALUE (:Sup_No, :Sup_Name, :Sup_City);
Copyright 2004,
27
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
27
Copyright 2004,
28
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
The below code snippet shows how a connection to a DBMS is established by supplying the userid
and password.
main()
{
exec sql whenever sqlerror goto sqlerrorlabel;
strcpy(username.arr,"pramodv");
username.len = strlen(username.arr);
strcpy(password.arr,"pramodv");
password.len=strlen(password.arr);
exec sql connect :username identified by :password;
After this step, the remaining sql statements are written.
The answer to the question in the slide lies in the next few slides..
28
Indicator variables
Variable to indicate whether the returned value is NULL.
Copyright 2004,
29
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
The indicator variables are used to indicate the status of the value received into the host variable.
Zero
Host variable has been assigned the retrieved value. Host variable can be used in
the application program.
Negative
Positive
Retrieved value is in host variable, but this indicates a warning, rounding off or
truncation for example.
The following highlights the declaration of indicator variables
exec sql begin declare section;
short emp_addri;
short emp_desi;
short emp_depti;
short emp_sali;
varchar username[20];
varchar password[20];
exec sql end declare section;
Indicator variables are required only for NULLABLE columns. They are also used with a prefixed
colon
29
Text Document
Copyright 2004,
30
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
30
CURSOR
Needed for select queries which return multiple rows of output from DBMS
A kind of variable associated with a query.
The value of this variable will be each row, in turn, of that querys output.
Copyright 2004,
31
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
A cursor is used along with an SQL statement in an embedded SQL program, when the
SELECT statement returns multiple rows. A cursor is declared as follows:
exec sql declare emp cursor for
select *
from employee;
Another example follows in the next slide
31
Declaring Cursor
The query is not executed immediately;
This is only the definition.
EXEC SQL
DECLARE CURSOR SupplierCur
SELECT * FROM Supplier
Where City=BHU;
Copyright 2004,
32
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
The Declaration of the cursor is like a directive to the precompiler. It doesnt call for any immediate
action
32
EXEC SQL
OPEN CURSOR SupplierCur;
Copyright 2004,
33
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
33
EXEC SQL
FETCH SupplierCur
INTO :Sup_No, :Sup_Name,
:Sup_City, :Sup_Status;
Copyright 2004,
34
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
The open statement positions the cursor on top of the query results. At this point, the cursor is not pointing at
any row
When the first fetch statement is encountered, the cursor is automatically positioned at the first row and
retrieves the same this goes on by automatically incrementing the cursor position for executing the fetch
statement each time until the end of rows is reached. After the last row has been retrieved, when the fetch
statement is executed again, an SQLWARNING is raised.
for(;;)
{
exec sql fetch emp into :emp_no, :emp_name, :emp_addr:addri,
:emp_des:desi, :emp_dept:depti,
:emp_sal:sali;
emp_name.arr[emp_name.len] = '\0';
if (addri == -1)
emp_addr.arr[0] ='\0';
else
emp_addr.arr[emp_addr.len] = '\0';
if (desi == -1)
strcpy(emp_des," ");
if (depti == -1)
strcpy(emp_dept," ");
if (sali == -1)
emp_sal=0;
printf("%d\t%20s\t%20s\t%3s\t%3s\t%d\n", emp_no, emp_name.arr, emp_addr.arr, emp_des, emp_dept,
emp_sal);
34
EXEC SQL
CLOSE SupplierCur
Copyright 2004,
35
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
This closes the cursor. The query results represented by the cursor would not be available after this.
To get back the values, the cursor has to be opened again
35
Copyright 2004,
36
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
emp_no;
varchar
emp_name[20];
varchar
emp_addr[20];
char
emp_des[3];
char
emp_dept[3];
int
emp_sal;
varchar username[20];
varchar password[20];
short
addri,desi,depti,sali;
36
Copyright 2004,
37
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
37
Copyright 2004,
38
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
system("cls");
printf("\t\t List of employees\n\n");
printf("No\t\t\tName\t\t\tAddress\t Desig dept Salary\n\n");
for(;;)
{
exec sql fetch emp into :emp_no, :emp_name, :emp_addr:addri,
:emp_des:desi, :emp_dept:depti,
:emp_sal:sali;
emp_name.arr[emp_name.len] = '\0';
if (addri == -1)
emp_addr.arr[0] ='\0';
else
emp_addr.arr[emp_addr.len] = '\0';
if (desi == -1)
strcpy(emp_des," ");
if (depti == -1)
strcpy(emp_dept," ");
if (sali == -1)
emp_sal=0;
printf("%d\t%20s\t%20s\t%3s\t%3s\t%d\n", emp_no, emp_name.arr, emp_addr.arr, emp_des, emp_dept, emp_sal);
}
end_of_fetch:
exec sql close emp;
exit(0);
sqlerrorlabel:
printf("\n %s \n", sqlca.sqlerrm.sqlerrmc);
exit(1);
}
38
Error handling
EXEC SQL
WHENEVER SQLERROR
goto sqlerrorlabel;
Copyright 2004,
39
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
In embedded SQL programs, run-time errors are reported to the program by the DBMS in the form of some
error code. The DBMS communicates the error status information through an area of program storage
called SQLCA (SQL communications area)
This SQLCA is a data structure that contains error variables and status indicators. You might have observed a
statement like:
exec sql include sqlca;
In the program. This includes the SQLCA datastructure into the program. By checking the fileds in this
datastructure, the program can check the status of execution and act accordingly.
AS and when the DBMS executes an embedded SQL code, it updates the value of the SQLCA
According to the SQL2 standrad, programs can use an SQLSTATE error code to handle errors.This is one of
the fileds inside the SQLCA datastructure.
SQLSTATE consists of two parts:
a)
b)
A code snippet making use of this would look something like this:
Exec sql delete * from emp where sal < 3000;
If(strcmp(sqlca.sqlstate,00000)
Goto error_lablel;
39
EXEC SQL
WHENEVER NOT FOUND CONTINUE;
NOT FOUND is used when there are no records that the SQL can
return
It is not an error case
Copyright 2004,
40
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
It is laborious task to check the error code after every sql statement. To simplify this process, there is
a WHENEVER statement. This is a directive that tells the precompiler what code code should be
included following every executable SQL statement
This statement can be used to handle three types of errors
1) SQLERROR
2) SQLWARNING
3) NOT FOUND (when we try to fetch rows from a cursor while there are no more)
WHENEVER/GOTO: to generate a branch to the given label
WHENEVER/CONTINUE to alolow the normal flow to continue
This is summarised in the following slide
40
WHENEVER
{NOT FOUND
| SQLERROR
| SQLWARNING}
{CONTINUE
| GO TO host-label}
Copyright 2004,
41
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
This whenever is a positional command. It is in effect until the next such whenever statement is
encountered in the code.
41
Summary
Views create a window into the table thereby allowing restricted access
Index helps speed up the search process
Embedded SQL programs are written in some HLL in which SQL statements
are intermixed
A special processing separates the SQL , converts and generates executable
code
Copyright 2004,
42
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
42
Thank You!
Copyright 2004,
43
Infosys Technologies Ltd
ER/CORP/CRS/DB07/003
Version No: 2.0
43