Você está na página 1de 8

STRUCTURED QUERY LANGUAGE

The SQL language and relational database systems based on it are one of the most important foundation technologies in the computer industry. Over the last two decades, SQL has grown from its first commercial use into a computer product and services market segment worth tens of billions of dollars per year, and SQL stands today as the standard computer database language. Literally hundreds of database products now support SQL, running on computer systems from mainframes to personal computers and even handheld devices. An official international SQL standard has been adopted and expanded twice. Virtually every major enterprise software product relies on SQL for its data management, and SQL is at the core of the database products from Microsoft, Oracle, and IBM, the three largest software companies in the world. SQL is also at the heart of open-source database products that are helping to fuel the popularity of Linux and the open-source movement. From its obscure beginnings as an IBM research project, SQL has leaped to prominence as both an important computer technology and a powerful market force. What, exactly, is SQL? Why is it important? What can it do, and how does it work? If SQL is really a standard, why are there so many different versions and dialects? How do popular SQL products like SQL Server, Oracle, Informix, Sybase, and DB2 compare? How does SQL relate to Microsoft standards, such as ODBC and COM? How does JDBC link SQL to the world of Java and object technology? What role does it play in the emerging web services architecture and the competing web services architectures from the Microsoft and Java-based camps? Does SQL really scale from mainframes to handheld devices? Has it really delivered the performance needed for high-volume transaction processing? How will SQL impact the way you use computers, and how can you get the most out of this important data management tool?

Introduction to SQL - The SQL Language

SQL is a tool for organizing, managing, and retrieving data stored by a computer database. The acronym SQL is an abbreviation for Structured Query Language. For historical reasons, SQL is usually pronounced sequel, but the alternate pronunciation S.Q.L. is also used. As the name implies, SQL is a computer language that you use to interact with a database. In fact, SQL works with one specific type of database, called a relational database. Figure 1 shows how SQL works. The computer system in the figure has a database that stores important information. If the computer system is in a business, the database might store inventory, production, sales, or payroll data. On a personal computer, the database might store data about the checks you have written, lists of people and their phone numbers, or data extracted from a larger computer system. The computer program that controls the database is called a database management system, or DBMS.

Figure 1. Using SQL for database access When you need to retrieve data from a database, you use the SQL language to make the request. The DBMS processes the SQL request, retrieves the requested data, and returns it to you. This process of requesting data from a database and receiving back the results is called a database queryhence the name Structured Query Language. The name Structured Query Language is actually somewhat of a misnomer. First of all, SQL is far more than a query tool, although that was its original purpose, and retrieving data is still one of its most important functions. SQL is used to control all of the functions that a DBMS provides for its users, including:

Data definition. SQL lets a user define the structure and organization of the stored data and relationships among the stored data items. Data retrieval. SQL allows a user or an application program to retrieve stored data from the database and use it. Data manipulation. SQL allows a user or an application program to update the database by adding new data, removing old data, and modifying previously stored data. Access control. SQL can be used to restrict a users ability to retrieve, add, and modify data, protecting stored data against unauthorized access. Data sharing. SQL is used to coordinate data sharing by concurrent users, ensuring that they do not interfere with one another. Data integrity. SQL defines integrity constraints in the database, protecting it from corruption due to inconsistent updates or system failures.

SQL is thus a comprehensive language for controlling and interacting with a database management system. Second, SQL is not really a complete computer language like COBOL, C, C++, or Java. SQL contains no IF statement for testing conditions, and no GOTO, DO, or FOR statements for program flow control. Instead, SQL is a database sublanguage, consisting of about 40 statements specialized for database management tasks. These SQL statements can be embedded into another language, such as COBOL or C, to extend that language for use in database access. Alternatively, they can be explicitly sent to a database management system for processing, via a

call-level interface from a language such as C, C++, or Java, or via messages sent over a computer network. Finally, SQL is not a particularly structured language, especially when compared to highly structured languages such as C, Pascal, or Java. Instead, SQL statements resemble English sentences, complete with noise words that dont add to the meaning of the statement but make it read more naturally. There are quite a few inconsistencies in the SQL language, and there are also some special rules to prevent you from constructing SQL statements that look perfectly legal, but dont make sense. Despite the inaccuracy of its name, SQL has emerged as the standard language for using relational databases. SQL is both a powerful language and one that is relatively easy to learn. The quick tour of SQL in Chapter 2 will give you a good overview of the language and its capabilities. SQL is not itself a database management system, nor is it a stand-alone product. You cannot go into a computer store and buy SQL. Instead, SQL is an integral part of a database management system, a language and a tool for communicating with the DBMS. Figure 1-2 shows some of the components of a typical DBMS, and how SQL acts as the glue that links them together. The database engine is the heart of the DBMS, responsible for actually structuring, storing, and retrieving the data in the database. It accepts SQL requests from other DBMS componentssuch as a forms facility, report writer, or interactive query facilityfrom user-written application programs, and even from other computer systems. As the figure shows, SQL plays many different roles:

SQL is an interactive query language. Users type SQL commands into an interactive SQL program to retrieve data and display it on the screen, providing a convenient, easyto-use tool for ad hoc database queries. SQL is a database programming language. Programmers embed SQL commands into their application programs to access the data in a database. Both user written programs and database utility programs (such as report writers and data entry tools) use this technique for database access. SQL is a database administration language. The database administrator responsible for managing a minicomputer or mainframe database uses SQL to define the database structure and control access to the stored data. SQL is a client/server language. Personal computer programs use SQL to communicate over a network with database servers that store shared data. This client/server architecture has become very popular for enterprise-class applications. SQL is an Internet data access language. Internet web servers that interact with corporate data and Internet applications servers all use SQL as a standard language for accessing corporate databases. SQL is a distributed database language. Distributed database management systems use SQL to help distribute data across many connected computer systems. The DBMS software on each system uses SQL to communicate with the other systems, sending requests for data access.

SQL is a database gateway language. In a computer network with a mix of different DBMS products, SQL is often used in a gateway that allows one brand of DBMS to communicate with another brand.

SQL has thus emerged as a useful, powerful tool for linking people, computer programs, and computer systems to the data stored in a relational database.

Figure 2. Components of a typical database management system SQL is both an easy-to-understand language and a comprehensive tool for managing data. Here are some of the major features of SQL and the market forces that have made it successful: Vendor independence Portability across computer systems SQL standards IBM endorsement and commitment (DB2) Microsoft commitment (SQL Server, ODBC, and ADO) Relational foundation High-level, English-like structure Interactive, ad hoc queries Programmatic database access Multiple views of data Complete database language Dynamic data definition

Client/server architecture Enterprise application support Extensibility and object technology Internet database access Java integration (JDBC) Industry infrastructure

These are the reasons why SQL has emerged as the standard tool for managing data on personal computers, minicomputers, and mainframes. They are described in the sections that follow. Vendor Independence SQL is offered by all of the leading DBMS vendors, and no new database product over the last decade has been highly successful without SQL support. A SQL-based database and the programs that use it can be moved from one DBMS to another vendors DBMS with minimal conversion effort and little retraining of personnel. Database tools, such as query tools, report writers, and application generators, work with many different brands of SQL databases. The vendor independence thus provided by SQL was one of the most important reasons for its early popularity and remains an important feature today. Portability Across Computer Systems SQL-based database products run on computer systems ranging from mainframes and midrange systems to personal computers, workstations, a wide range of specialized server computers, and even handheld devices. They operate on stand-alone computer systems, in departmental local area networks, and in enterprise wide or Internet wide networks. SQL-based applications that begin on single-user or departmental server systems can be moved to larger server systems as they grow. Data from corporate SQL-based databases can be extracted and downloaded into departmental or personal databases. Finally, economical personal computers can be used to prototype a SQL-based database application before moving it to an expensive multiuser system. SQL Standards An official standard for SQL was initially published by the American National Standards Institute (ANSI) and the International Standards Organization (ISO) in 1986, and was expanded in 1989 and again in 1992 and 1999. SQL is also a U.S. Federal Information Processing Standard (FIPS), making it a key requirement for large government computer contracts. Over the years, other international, government, and vendor groups have pioneered the standardization of new SQL capabilities, such as call-level interfaces or object-based extensions. Many of these new initiatives have been incorporated into the ANSI/ISO standard over time. The evolving standards serve as an official stamp of approval for SQL and have speeded its market acceptance.

PL/SQL
PL/SQL stands for "Procedural Language extensions to SQL." PL/SQL is available primarily as an "enabling technology" within other software products; it does not exist as a standalone language. You can use PL/SQL in the Oracle relational database, in the Oracle Server, and in client-side application development tools, such as Oracle Forms. PL/SQL is closely integrated into the SQL language, yet it adds programming constructs that are not native to this standard relational database language. As you can see from the following code example, PL/SQL allows you to combine SQL statements with "standard" procedural constructs. This single program can

either insert a company into or delete a company from the database. It relies on the IF statement (not a SQL statement) to determine which action to take:
PROCEDURE maintain_company (action_in IN VARCHAR2, id_in IN NUMBER, name_in IN VARCHAR2 := NULL) IS BEGIN IF action_in = 'DELETE' THEN DELETE FROM company WHERE company_id = id_in; ELSIF action_in = 'INSERT' THEN INSERT INTO company (company_id, name) VALUES (id_in, name_in); END IF; END;

PL/SQL is an unusual -- and an unusually powerful -- programming language. You can write programs that look just like traditional 3GL modules, but you can also include calls to SQL statements, manipulate data through cursors, and take advantage of some of the newest developments in programming languages. PL/SQL supports packages which allow you to perform object-oriented design. PL/SQL provides a powerful mechanism for trapping and, with exception handlers, resolving errors. The tight integration of PL/SQL with SQL provides developers with the best of both worlds -- declarative and procedural logic. Figure 1.1 shows how PL/SQL fits within the client-server architecture of Oracle-based applications. It shows both an Oracle Forms client and a non-Oracle tool client, both executing against an Oracle Server database. Notice that the Oracle Forms client makes use of two versions of PL/SQL: PL/SQL Release 1.1: a client-side PL/SQL engine that allows the application to execute local PL/SQL programs PL/SQL Release 2.X: the server-based PL/SQL engine that executes stored programs

The third-party tool executes calls to stored programs, which are then run on the server.
Figure 1.1: PL/SQL within the Oracle client-server architecture

Because PL/SQL is used both in the database (for stored procedures and database triggers) and in the application code (to implement logic within a form, for example), you can leverage the same programming language for both client-side and server-side development. You can even move programs from one component of the configuration to another.[ 1 ] For example, you might

decide that a function which was originally coded for a single screen could be shared by all of the modules in an application. To make this happen, you simply move that function from the client-side screen component to the server-side database environment. You have to change neither the PL/SQL code nor any of the programs that call that function. [1] As long as there are no conflicts between different versions of PL/SQL. Of course, as an underlying technology in the Oracle constellation of products, PL/SQL is just one element of the total programming experience. In fact, building an Oracle-based application requires a combination of technology and techniques, as you'll see in the next section.

PL/SQL Fundamentals
PL/SQL programs are organized in functions, procedures and packages (somewhat similar to Java packages). There is a limited support for object-oriented programming. PL/SQL is based on the Ada programming language, and as such it shares many elements of its syntax with Pascal.

Your first example in PL/SQL will be an anonymous block that is a short program that is ran once, but that is neither named nor stored persistently in the database.
SQL> SET SERVEROUTPUT ON SQL> BEGIN 2 dbms_output.put_line('Welcome to PL/SQL'); 3 END; 4 /

SET SERVEROUTPUT ON is the SQL*Plus command1 to activate the console

output. You only need to issue this command once in a SQL*Plus session. the keywords BEGIN...END define a scope and are equivalent to the curly braces in Java {...} a semi-column character (;) marks the end of a statement the put_line function (in the built-in package dbms_output) displays a string in the SQL*Plus console.

You are referred to Table 2 for a list of operators, and to Table 3 for some useful built-in functions.
Compiling your code. PL/SQL code is compiled by submitting it to SQL*Plus. Remember that it is advisable to type your program in an external editor, as you have done with SQL (see Introduction to Oracle). Debugging. Unless your program is an anonymous block, your errors will not be reported. Instead, SQL*Plus will display the message ``warning: procedure created with compilation errors''. You will then need to type:
SQL> SHOW ERRORS

to see your errors listed. If yo do not understand the error message and you are using Oracle on UNIX, you may be able to get a more detailed description using the oerr utility, otherwise use Oracle's documentation (see References section). For example, if Oracle reports ``error PLS00103'', you should type:
oerr PLS 00103

at the UNIX command prompt (i.e. not in SQL*Plus).

Executing PL/SQL
If you have submitted the program above to Oracle, you have probably noticed that it is executed straight away. This is the case for anonymous blocks, but not for procedures and functions. The simplest way to run a function (e.g. sysdate) is to call it from within an SQL statement:
SQL> SELECT sysdate FROM DUAL 2 /

Next, we will rewrite the anonymous block above as a procedure. Note that we now use the user function to greet the user.
CREATE OR REPLACE PROCEDURE welcome IS user_name VARCHAR2(8) := user; BEGIN -- `BEGIN' ex dbms_output.put_line('Welcome to PL/SQL, ' || user_name || '!'); END; /

Make sure you understand the changes made in the code:


A variable user_name of type VARCHAR2 is declared
user_name is initialised using the user2 built-in function

``:='' is the assignment operator (see. Table 2)

Once you have compiled the procedure, execute it using the EXEC command.
SQL> EXEC welcome Both procedures and functions should remind you of Java methods. The similarities and differences between them are outlined in Table 1.

Table 1: Functions, procedures and Java methods compared.

Ja Pr Fu va oc nc M ed tio inp Pa et ur n Ca ut ut, ra ho e n ou m op no ye Re d be tp et tio s tu ca ut er nal rn no ye lle s s s d va wi lu thi e n SQ L

Você também pode gostar