Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
765,5 KB
Nội dung
Chapter 3:SQL Basics
-99-
o.Order_Date
FROM ORDERS o, CUSTOMERS c
WHERE o.customer_number =* c.customer_number;
Note
In the shorthand version, the type of JOIN depends on both the order of
the tables in the FROM clause and the position of the asterisk in the *=
operator.
FULL OUTER JOIN
A "full outer join" includes all unmatched rows from both tables in the result. For
example, to find any orders in the Orders Table with customer numbers that do not
match any entries in our Customers Table, you can execute a Full Outer Join to show
all the entries in both tables. Here's an example:
SELECT c.Last_Name, c.First_Name, o.Order_Date
FROM Customers c FULL OUTER JOIN
Orders o ON c.Customer_number = o.Customer_Number;
The result set generated by this join is the same as the results shown in Table 3-14,
since all orders have a corresponding customer. However, if, for some reason, an
order placed on 12/12/01existed in the Orders Table with no corresponding entry in
the Customers Table, the additional row shown at the bottom of Table 3-15 would be
generated.
Table 3-15: Results of FULL OUTER JOIN
Last_Name First_Name Order_Date
Corleone Michael <NULL>
Corleone Fredo 12/8/01
Corleone Sonny <NULL>
Corleone Francis 12/9/01
Corleone Vito 12/9/01
Hagen Tom <NULL>
Adams Kay 12/10/01
Coppola Francis <NULL>
Puzo Mario <NULL>
<NULL> <NULL> 12/12/01
Using NOT EXISTS
TEAMFLY
Team-Fly
®
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-100-
Now you know how to use INNER JOINS to find records from two tables with
matching fields, and how to use OUTER JOINS to find all records, matching or
nonmatching. Next, consider a case in which you want to find records from one table
that don't have corresponding records in another.
Using the Customers and Orders Tables again, find all the customers who have not
placed an order. The way to do this is to find customer records with customer
numbers that do not exist in the Orders Table. This is done using NOT EXISTS:
SELECT c.Last_Name + ', ' + c.First_Name AS Customer
FROM CUSTOMERS c
WHERE NOT EXISTS
(SELECT *
FROM orders o
WHERE o.customer_number = c.customer_number);
Self-joins
A self-join is simply a normal SQL join that joins a table to itself. You use a self-join
when rows in a table contain references to other rows in the same table. An example
of this situation is a table of employees, where each record contains a reference to
the employee's supervisor by Employee_ID. Since the supervisor is also an
employee, information about the supervisor is stored in the Employees Table, as
shown in Table 3-16, so you use a self-join to access it.
Table 3-16: Employees Table
EMPLOYEE_ID FIRST_NAME LAST_NAME SUPERVISOR
100 Michael Corleone 104
101 Fredo Corleone 100
102 Sonny Corleone 100
103 Francis Corleone 100
104 Vito Corleone 99
105 Tom Hagen 100
106 Kay Adams 100
107 Francis Coppola 100
108 Mario Puzo 100
Since a join implicitly requires two table names, identifying the tables to be joined, you
can create a self-join by using table-name aliases to give each reference to the table
a separate name. To get a list of employees and their supervisors, create a self-join
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-101 -
by creating two separate references to the Employees Table, using two different
aliases:
SELECT e.Last_Name, e.First_Name,
boss.Last_Name + ', ' + boss.First_Name AS Boss
FROM EMPLOYEES e, EMPLOYEES boss
WHERE e.supervisor = boss.employee_id
The preceding SQL code is effectively creating what looks like two identical tables, E
and Boss, and joining them using an Inner Join. This approach allows you to get the
employee information from one reference to the table and supervisor information from
the other, as shown here:
Last_Name First_Name Boss
Corleone Michael Corleone, Vito
Corleone Fredo Corleone, Michael
Corleone Sonny Corleone, Michael
Corleone Francis Corleone, Michael
Hagen Tom Corleone, Michael
Adams Kay Corleone, Michael
Coppola Francis Corleone, Michael
You can turn this into an Outer Self-Join very easily, as follows:
SELECT e.last_name, e.first_name,
boss.last_name + ', ' + boss.first_name AS Boss
FROM EMPLOYEES e, employees boss
WHERE e.supervisor *= boss.employee_id;
This returns one additional row, since the Employee_ID of Vito's supervisor does not
appear in the Employees Table. His boss appears as <NULL>, as shown here:
Last_Name First_Name Boss
Corleone Michael Corleone, Vito
Corleone Fredo Corleone, Michael
Corleone Sonny Corleone, Michael
Corleone Francis Corleone, Michael
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-102 -
Last_Name First_Name Boss
Corleone Vito <NULL>
Hagen Tom Corleone, Michael
Adams Kay Corleone, Michael
Coppola Francis Corleone, Michael
Cartesian Products
Cartesian products, or cross products, are something you normally want to avoid.
The Cartesian product of a Join occurs when every record in one table is joined on
every record of the other, so the Cartesian product of two tables 100-rows long is
10,000 rows.
Cartesian products are normally an error, caused by a bad or nonexistent WHERE
clause. In the case of a small table like the ones in our examples, this is not a
major problem; but on a large database, the time taken to generate cross products
of thousands of rows can be significant.
Using the UNION Operator to Combine Queries
Another way to combine data from two separate sources is to use the UNION
operator. The default action of the UNION operator is to combine the results of two or
more queries into a single query and to eliminate any duplicate rows. When ALL is
used with UNION, duplicate rows are not eliminated.
In the following example, the first query returns the names and addresses of all the
Corleones; the second returns all customers in New Jersey. The UNION operator
combines the results, removing the duplicate records that are generated for
Corleones in New Jersey:
SELECT First_Name, Last_Name, Street, City, State
FROM Customers
WHERE Last_Name = 'Corleone'
UNION
SELECT First_Name, Last_Name, Street, City, State
FROM Customers
WHERE State = 'NJ'
ORDER BY Last_Name, First_Name;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-103 -
You can use ORDER BY, as shown, to sort the combined answer set by adding the
ORDER BY clause after the last query. Here is the result:
First_Name Last_Name Street City State
Kay Adams 109 Maple Newark NJ
Francis Corleone 17 Main New York NY
Fredo Corleone 19 Main New York NY
Michael Corleone 123 Pine New York NY
Sonny Corleone 123 Walnut Newark NJ
Vito Corleone 23 Oak St Newark NJ
Tom Hagen 37 Chestnut Newark NJ
You do not have to use the same columns in each query. Only the column counts and
column types need to match. However, if you create a UNION of two result sets with
different columns, you have to apply the ORDER BY clause using the column
number.
EXCEPT operator
The EXCEPT operator creates a result set by including all rows that the first query
returns but not rows that the second query returns. The default version eliminates all
duplicate rows; EXCEPT ALL does not. The following statement will return the names
and addresses of all Corleones except those living in New Jersey:
SELECT First_Name, Last_Name, Street, City, State
FROM Customers
WHERE Last_Name = 'Corleone'
EXCEPT
SELECT First_Name, Last_Name, Street, City, State
FROM Customers
WHERE State = 'NJ'
INTERSECT operator
The INTERSECT operator creates a result set by including only rows that exist in
both queries and eliminating all duplicate rows. When you use ALL with INTERSECT,
the duplicate rows are not eliminated. The following statement will return the names
and addresses of Corleones living in New Jersey:
SELECT First_Name, Last_Name, Street, City, State
FROM Customers
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-104 -
WHERE Last_Name = 'Corleone'
INTERSECT
SELECT First_Name, Last_Name, Street, City, State
FROM Customers
WHERE State = 'NJ';
Data Control Language
The Data Control Language (DCL) provides the tools to manage the database and
control such aspects as user-access privileges. Since a database usually represents
a significant investment in time and effort, managing users is an important aspect of
database management.
A user is anyone who has access to the database. Users can be granted different
privileges, ranging from read-only access to a limited portion of the database, all the
way up to unlimited access to the entire RDBMS.
Managing Users
To add individual users to a database, the database administrator must create
database users. This is done using the CREATE USER command. When you create
a user, you can assign a password, certain basic permissions and an expiration date,
all in one command. You can also add the user to an existing user group.
After creating a user, you may need to modify his or her privileges, perhaps to add the
right to modify or delete certain tables or to change the user's password. These
functions are handled using the ALTER USER command.
Finally, you may need to remove an individual's access to the database entirely. This
is done using the DROP USER command.
User privileges
Relational Database Management Systems define sets of privileges that can be
assigned to users. These privileges correspond to actions that can be performed on
objects in the database. User privileges can be assigned at two different levels. Users
can be restricted both at the level of the types of actions they can perform, such as
READ, MODIFY, or WRITE, and at the level of the types of database objects they can
access.
Access-level privileges can generally be assigned at the following levels:
§ Global level access to all databases on a given server
§ Database level access to all tables in a given database
§ Table-level access to all columns in a given table
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-105-
§ Column-level access to single columns in a given table
Normally, the management of user privileges is an administrative function that the
database administrator handles.
Frequently, user privileges are assigned by defining a user's role. Database roles are
simply predefined sets of user privileges. Like users, user groups and roles are
managed using SQL commands. Most RDBMSes support the following roles or their
equivalents:
§ Owner – A user who can read or write data and create, modify, and delete the database or its
components
§ Writer – A user who is allowed to read or write data
§ Reader – Someone who is allowed to read data but not write to the database
§ Public – The lowest possible in terms of privileges
User roles are a neat administrative feature designed to save time for the database
administrator. Like groups, roles can be defined by the database administrator as
required.
Managing user groups
In addition to defining individual users, many systems allow the database
administrator to organize users into logical groups with the same privileges. Groups
are created in much the same way as individual users. The general syntax for
CREATE GROUP is as follows:
CREATE GROUP group_name WITH USER user1, user2
Like users, groups are dropped using the DROP command, as shown here:
DROP GROUP group_name
To add a user to a group, use the ALTER GROUP ADD command; to delete users,
use the ALTER GROUP DROP command, as shown here:
ALTER GROUP group_name ADD USER username [, ]
ALTER GROUP group_name DROP USER username [, ]
A significant difference between adding and dropping groups as opposed to adding
and dropping individual users is that when a group is altered or dropped, only the
group is affected. Any users in a group that is dropped simply lose their membership
in the group. The users are otherwise unaffected. Similarly, when a group is altered
by dropping a user, only the group is affected. The user simply loses his or her
membership in the group but is otherwise unaffected.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-106 -
Granting and revoking user privileges
The SQL GRANT command is used to grant users the necessary access privileges to
perform various operations on the database. In addition to granting a user specified
access privileges, the GRANT command can be used to allow the user to grant a
privilege to other users. There is also an option allowing the user to grant privileges
on all subtables and related tables. These two versions of the GRANT command look
like this:
GRANT privilege ON table_name TO user_name;
GRANT SELECT ON PRODUCTS WITH GRANT OPTION TO jdoe;
The REVOKE command is used to revoke privileges granted to a user. Like the
GRANT command, this command can be applied at various levels.
The REVOKE command is used to revoke privileges from users so that they cannot
do certain tasks on the database. Just like the GRANT command, this command can
be applied at various levels. It is important to note that the exact syntax of this
command might differ as per your database. For example, the following command
revokes the SELECT privileges from John Doe, on the Products Table.
REVOKE SELECT ON PRODUCTS FROM jdoe
Creating and Using Stored Procedures
A stored procedure is a saved collection of SQL statements that can take and return
user-supplied parameters. You can think of a stored procedure as a method or
function, written in SQL. There are obviously a number of advantages to using stored
procedures, including:
§ Stored procedures are precompiled, so they will execute fast.
§ Stored procedures provide a standardised way of performing common tasks.
Almost any SQL statement can be used as a stored procedure. All that is required is
to provide a procedure name and a list of variables:
CREATE PROCEDURE procedure_name
@parameter data_type,
@parameter data_type = default_value,
@parameter data_type OUTPUT
AS
sql_statement [ n ]
Variable names are specified using an at sign @ as the first character. Otherwise the
name must conform to the rules for identifiers. Variable names cannot be used in
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-107 -
place of table names, column names, or the names of other database objects. They
can only be used to pass values to and from the stored procedure.
In addition to the variable name, you must specify a data type. All data types can be
used as a parameter for a stored procedure. You can also specify a default value for
the variable, as shown in the example.
If you want to return a value to the caller, you must specify the variable used for the
return value using the OUTPUT keyword. You can then set this value in the body of
the stored procedure.
The AS keyword is used to identify the start of the SQL statement forming the body of
the stored procedure. A very simple stored procedure with no parameter variables
might look like:
CREATE PROCEDURE LIST_ORDERS_BY_STATE
AS
SELECT
o.Order_Number,
c.Last_Name + ', ' + c.First_Name AS Name,
c.State
FROM Customers c,Orders o
WHERE c.Customer_Number = o.Customer_Number
ORDER BY c.State,c.Last_Name;
To execute this stored procedure, you simply invoke it by name. The following code
snippet shows how:
LIST_ORDERS_BY_STATE;
The stored procedure will return a result set which looks like:
Order_Number Name State
5 Adams, Kay NJ
4 Corleone, Vito NJ
2 Corleone, Fredo NY
3 Corleone, Francis NY
Using Input Parameters in a Stored Procedure
The following code snippet shows how you can use input parameters in a stored
procedure. This particular store procedure was designed to handle the input from an
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 3:SQL Basics
-108-
HTML form. Notice that the variable names are not required to be the same as the
column names:
CREATE PROCEDURE INSERT_CONTACT_INFO
@FName VARCHAR(20), @MI CHAR(1), @LName VARCHAR(30),
@Street VARCHAR(50), @City VARCHAR(30), @ST CHAR(2),
@ZIP VARCHAR(10), @Phone VARCHAR(20), @Email VARCHAR(50)
AS
INSERT INTO CONTACT_INFO
(First_Name, MI, Last_Name,
Street, City, State, ZIP, Phone, Email)
VALUES
(@FName, @MI, @LName,
@Street, @City, @ST, @ZIP, @Phone, @Email);
The SQL statement used to call this procedure is very similar to the statement shown
in the previous example. The only difference is the use of the input parameters
obtained from the HTML form:
INSERT_CONTACT_INFO 'Charles', 'F', 'Boyer', '172 Michelin',
'Detroit', 'MI', '76543', '900-555-1234', 'charles@boyer.net'
Using Output Parameters in a Stored Procedure
Creating a stored procedure which uses output parameters is also quite
straightforward. The example shows a stored procedure which returns a validation
message when a UserName, Password pair is checked against a table:
CREATE PROCEDURE CHECK_USER_NAME
@UserName varchar(30),
@Password varchar(20),
@PassFail varchar(20) OUTPUT
AS
IF EXISTS(Select * From Customers
WHERE Last_Name = @UserName
AND
First_Name = @Password)
BEGIN
SELECT @PassFail = "PASS"
END
ELSE
BEGIN
SELECT @PassFail = "FAIL"
END
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... implementation of the following interfaces: § java. sql.Driver § java. sql.DatabaseMetaData (excluding those portions defined in the JDBC 2.0 and 3.0 extensions) § java. sql.ResultSetMetaData (excluding portions defined in the JDBC 2.0 and 3.0 extensions) § § java. sql.Statement § java. sql.CallableStatement § java. sql.PreparedStatement § § java. sql.Connection java. sql.ResultSet JDBC 2.0 API Compliance, which... for programming access to SQL databases, which is also the basis for Microsoft's ODBC interface The JDBC 2.0 API includes two packages: java. sql, known as the JDBC 2.0 core API; and javax.sql, known as the JDBC Standard Extension Together, they contain the necessary classes to develop database applications using Java As a core of the Java 2 Platform, the JDBC is available on any platform running Java. .. create and populate a database and to use SQL to perform fairly complex queries Specifically, you learn about using SQL when: Creating and populating databases and tables § Querying a database § Using primary and foreign keys to join tables § Managing database security AM FL Y § TE Chapter 4 discusses JavaDatabase Connectivity (JDBC), which enables you to use your knowledge of SQL in a Java application... Mapping of SQL data types in JDBC JDBC is a JavaDatabase Connectivity API that lets you access virtually any tabular data source from a Java application In addition to providing connectivity to a wide range of SQL databases, JDBC allows you to access other tabular data sources such as spreadsheets or flat files Although JDBC is often thought of as an acronym for JavaDatabase Connectivity, the trademarked... actually JDBC What Is JDBC? JDBC is a JavaDatabase Connectivity API that lets you access virtually any tabular data source from a Java application In addition to providing connectivity to a wide range of SQL databases, JDBC allows you to access other tabular data sources such as spreadsheets or flat files Although JDBC is often thought of as an acronym for JavaDatabase Connectivity, the trademarked... Type 2: Native-API partly Java driver § Type 3:JDBC-Net pure Java driver § Type 4: Native-protocol pure Java driver These types are discussed in the following sections Type 1: JDBC-ODBC bridge plus ODBC driver The JDBC-ODBC bridge product provides JDBC access via ODBC drivers ODBC (Open Database Connectivity) predates JDBC and is widely used to connect to databases in a non -Java environment ODBC is... reading its contents and sending them to the database as the actual parameter value The setNull method allows you to send a NULL value to the database as an IN parameter You can also send a NULL to the database by passing a Java null value to a setXXX method CallableStatement The CallableStatement object allows you to call a database stored procedure from a Java application A CallableStatement object... Native-API partly Java driver Type 2 drivers use a native API to communicate with a database system Java native methods are used to invoke the API functions that perform database operations A big advantage of Type 2 drivers is that they are generally faster than Type 1 drivers The primary disadvantages of Type 2 drivers are as follows: § Type 2 drivers require native code on the target machine § The Java Native... three-tier models for database access In other words, JDBC can either be used directly from your application or as part of a middle-tier server application Two-Tier Model In the two-tier model, a Java application interacts directly with the database Functionality is divided into these two layers: § Application layer, including the JDBC driver, business logic, and user interface § Database layer, including... RDBMS The interface to the database is handled by a JDBC driver appropriate to the particular database management system being accessed The JDBC driver passes SQL statements to the database and returns the results of those statements to the application Figure 4-1: Two-tier client/server configuration A client/server configuration is a special case of the two -tier model, where the database is located on . and 3.0
extensions)
§ java. sql.Connection
§ java. sql.Statement
§ java. sql.CallableStatement
§ java. sql.PreparedStatement
§ java. sql.ResultSet
§ JDBC. thought of as an acronym for
Java Database Connectivity, the trademarked API name is actually JDBC.
What Is JDBC?
JDBC is a Java Database Connectivity API