Oracle SQL Plus The Definitive Guide- P3 ppsx

10 580 0
Oracle SQL Plus The Definitive Guide- P3 ppsx

Đang tải... (xem toàn văn)

Thông tin tài liệu

< previous page page_xxi next page > Page xxi I owe a great debt to Brian Gill, who encouraged me when I had the initial idea for this book. Without him, this project might never have gotten off the ground. Thanks also to my agent, David Rogelberg of Studio B, who helped me keep up with the business end of this project, and who also manages that wonderfully interesting email list that serves so well to distract me from my real work. Several O'Reilly & Associates people contributed to this book in various ways. To Debby Russell of O'Reilly & Associates, and the editor of this book, I say: thanks for all the red ink! Debby is a great editor to work with. She had a lot of good ideas for organizing this book. She was very understanding when I fell behind schedule. She was very encouraging, always drawing attention to things I did well. Edie Freedman designed the cover, and is responsible for that wonderful looking moving leaf insect on the front. Steve Abrams helped in various ways during the development of the book. Many thanks! Rob Romano did a great job with the figures. Ellie Maden pulled everything together and saw this book through the production process. < previous page page_xxi next page > < previous page page_1 next page > Page 1 1 Introduction to SQL* Plus In this chapter: What Is SQL*Plus? History of SQL*Plus Why Master SQL*Plus? Creating and Loading the Sample Tables SQL*Plus is the command-line interface to the Oracle database. Its fundamental reason for existence is to allow you to enter and execute ad hoc SQL statements and PL/SQL code blocks. This chapter explains what SQL*Plus is, how it relates to other Oracle tools (as well as the database), and why you should master it. At the end of the chapter I'll introduce you to the sample data, which is used for many of the examples in this book. If you like, you can load that data into your database and test out each example as you go through this book. What is SQL*Plus? SQL*Plus is essentially an interactive query tool, with some scripting capabilities. It is a non-GUI, character-based tool that has been around since the dawn of the Oracle age. Using SQL*Plus, you can enter an SQL statement, such as a SELECT query, and view the results. You can also execute Data Definition Language (DDL) commands that allow you to maintain and modify your database. You can even enter and execute PL/SQL code. In spite of SQL*Plus's age and lack of flash, it is a workhorse tool used day in and day out by database administrators, developers, and yes, even end users. As a database administrator, it is my tool of choice for managing the databases under my care. I use it to peek under the hoodto explore the physical implementation of my database, and to create and manage users, tables, and tablespaces. In my role as a developer, SQL*Plus is the first tool that I fire up when I need to develop a query. In spite of all the fancy, GUI-based SQL generators contained in products such as PowerBuilder, Clear Access, and Crystal Reports, I still find it quicker and easier to build up and test a complex query in SQL*Plus before transferring it to whatever development tool I am using. < previous page page_1 next page > < previous page page_2 next page > Page 2 Uses for SQL*Plus Originally developed simply as a way to enter queries and see results, SQL*Plus has been enhanced with scripting and formatting capabilities, and can now be used for many different purposes. The basic functionality is very simple. With SQL*Plus, you can do the following: Issue a SELECT query and view the results Insert, update, and delete data from database tables Submit PL/SQL blocks to the Oracle server for execution Issue DDL commands, such as those used to create, alter, or drop database objects such as tables, indexes, and users Execute SQL*Plus script files Write output to a file Execute procedures and functions that are stored in a database While they might not seem like much, these things are the building blocks you can use to perform a variety of useful functions. Consider the ability to enter a SELECT statement and view the results. The following example shows how to do this using SQL*Plus: SQL> SELECT employee_id, enployee_name, employee_billing_rate 2 FROM employee; EMPLOYEE_ID EMPLOYEE_NAME EMPLOYEE_BILLING_RATE 101 Jonathan Gennick 169 102 Jenny Gennick 135 104 Jeff Gennick 99 105 Horace Walker 121 107 Bohdan Khmelnytsy 45 108 Pavlo Chubynsky 220 110 Ivan Mazepa 84 111 Taras Shevchenko 100 112 Hermon Goche 70 113 Jacob Marley 300 10 rows selected. Combine this capability with SQL*Plus's formatting abilities and you can turn the above query into a very credible looking report, complete with page titles, page numbers, column titles, and nicely formatted output. That report might look something like this: < previous page page_2 next page > < previous page page_3 next page > Page 3 Employee Listing Page 1 Billing Emp ID Name Rate 101 Jonathan Gennick 169 102 Jenny Gennick 135 104 Jeff Gennick 99 105 Horace Walker 121 107 Bohdan Khmelnytsk 45 108 Pavlo Chubynsky 220 110 Ivan Mazepa 84 111 Taras Shevchenko 100 112 Hermon Goche 70 113 Jacob Marley 300 Another twist on the same theme is to format the output so you get a commadelimited list of values. That output could look like this: 101,Jonathan Gennick,169 102,Jenny Gennick,135 104,Jeff Gennick,99 105,Horace Walker,121 107,Bohdan Khmelnytsky,45 108,Pavlo Chubynsky,220 110,Ivan Mazepa,84 111,Taras Shevchenko,100 112,Hermon Goche,70 113,Jacob Marley,300 Using the SQL*Plus SPOOL command, you could write this output to a file, and later load it into a program such as Microsoft Excel for further manipulation. It's a small leap from executing only queries to executing any other SQL statement. In fact, SQL*Plus will let you execute any valid SQL statement, and is frequently used during database maintenance tasks. Creating a new user for example, can be accomplished by the following statement: CREATE USER ashley IDENTIFIED BY some_password; Of course, it's rare that you would only issue one command when you add a new user. Usually you want to assign a default tablespace and a quota on that tablespace. You may also want to grant the privileges needed to connect to the database. Whenever you have a task that requires a sequence of commands to be executed, you can simplify things by taking advantage of SQL*Plus's scripting capabilities. The following commands, when placed in a script file, allow you to add a new user with just one command: CREATE USER &&1 IDENTIFIED BY &&2 DEFAULT TABLESPACE USER_DATA TEMPORARY TABLESPACE TEMPORARY_DATA QUOTA UNLIMITED ON TEMPORARY_DATA QUOTA &&3.m ON USER_DATA; GRANT CONNECT TO &&1; < previous page page_3 next page > < previous page page_4 next page > Page 4 Assuming you named the file CREATE_USER.SQL, you could then issue the following command from SQL*Plus whenever you needed to add a user to your database: @CREATE_USER username password quota The following example shows how this works, by creating a user named ASHLEY, with a password of JUSTIN, and a quota of 10 megabytes in the USER_DATA tablespace: SQL> @CREATE_USER ashley justin 10 old 1: CREATE USER &&1 IDENTIFIED BY &&2 new 1: CREATE USER ashley IDENTIFIED BY justin old 5: QUOTA &&3.m ON USER_DATA new 5: QUOTA 10m ON USER_DATA User created. old 1: GRANT CONNECT TO &&1 new 1: GRANT CONNECT TO ashley Grant succeeded. The output you see is SQL*Plus showing you the before and after version of each line containing a substitution variable. You will read more about substitution variables, and the subject of scripting, in Chapter 4, Writing SQL*Plus Scripts. To write really complicated scripts, you can take advantage of Oracle's built-in procedural language, PL/SQL. The following example shows how a PL/SQL block can be executed using SQL*Plus: SQL> SET SERVEROUTPUT ON SQL> BEGIN 2 DBMS_OUTPUT.PUT_LINE(Hello World!); 3 END; 4 / Hello World! Once you know how to use SQL*Plus to perform the basic functions just described, you can leverage them to do the things described in this book. This includes: Producing reports with SQL*Plus Writing scripts that can be executed with SQL*Plus Using SQL*Plus to extract data to a text file Examining the structure of your database by querying the data dictionary tables Tuning queries using the EXPLAIN PLAN command < previous page page_4 next page > < previous page page_5 next page > Page 5 There are chapters in this book covering each of the above topics in detail. A lot can be accomplished with SQL*Plus. This book will show you how. SQL*Plus's Relation to SQL, PL/SQL and the Oracle Database. SQL*Plus is often used in conjunction with two other products, both of which have the letters SQL in their names. The first is SQL itself. Without a doubt, the most common use of SQL*Plus is to submit SQL statements to the database for execution. The second product is Oracle's PL/SQL procedural language. Table 1-1 gives a short summary of each of these three products. Table 1-1. The Three SQLs: SQL, PL/SQL, and SQL*Plus Product Description SQL SQL, which stands for Structured Query Language, is an ANSI (and ISO) standard language used for querying, modifying, and managing relational databases. It is used to insert, delete, update, and retrieve data. PL/SQL PL/SQL is a properitary procedural language developed by Oracle as an extension to SQL. Like SQL, it also executes inside the database. It was created as a tool for coding business rules and procedures at the database level. SQL*Plus SQL*Plus is an Oracle-developed tool that allows you to interactively enter and execute SQL commands and PL/SQL blocks. Because these three products all have SQL as part of their names, people occasionally get confused about the relationship between them and about which commands get executed where. SQL*Plus does have its own set of commands it recognizes and executes, but any SQL queries, DDL commands, and PL/SQL blocks are sent to the database server for execution. Figure 1-1 illustrates this relationship. Figure 1-1. Relationship between SQL*Plus, SQL, and PL/SQL < previous page page_5 next page > < previous page page_6 next page > Page 6 Think of SQL*Plus as kind of a middleman, standing between you and Oracle, and helping you to communicate with your database. You type in a SQL query, SQL*Plus takes it and sends it to the database, the database returns the results to SQL*Plus, and SQL*Plus displays those results in a format you can understand. History of SQL*Plus SQL*Plus has been around for a long time, pretty much since the beginning of Oracle. In fact, the original author was Bruce Scott. Any DBA will recognize the name Scott. It lives on, immortalized as the owner of the demo tables that are installed with every version of Oracle. The original purpose of SQL*Plus can be summed up in the succinct words of Kirk Bradley, another early author of SQL*Plus, who told me, We needed a way to enter statements into the database and get results. This is still arguably the major reason most people use SQL*Plus today, over fifteen years after it was originally written. SQL*Plus certainly satisfies a compelling, and enduring, need. The original name of the product was not SQL*Plus. The original name was UFI, which stands for User Friendly Interface. This name has its roots in one of the first relational database systems ever developed, IBM's System R. System R was the product of a research effort by IBM. Some of IBM's documents referred to the command-line interface as the User Friendly Interface, and that name was adopted by Oracle for their interactive SQL utility. One of the more interesting uses Oracle had for UFI was as a tool to produce their documentation. The DOCUMENT command, now considered obsolete, was used for this purpose. Script files were created that contained the manual text, interspersed with the SQL statements needed for the examples. The DOCUMENT command was used to set off the manual text so that it would just be copied to the output file. When these scripts were run, the text was copied, the SQL statements were executed, and the result was documentation complete with examples. UFI was used extensively in Oracle's internal testing and QA efforts. SQL*Plus still plays a significant role in Oracle's testing, even today. SQL*Plus maintains a fascinating relic from the old days in the form of the SET TRIMOUT, SET TRIMSPOOL, and SET TAB commands. These commands control the printing of trailing spaces and the use of tabs to format columnar output. To understand why these commands even exist, you have to realize that when < previous page page_6 next page > < previous page page_7 next page > Page 7 SQL*Plus first made its appearance, people thought a dial-up speed of 1200 bps was fast. If you had a lot of whitespace in your report, you spent a lot of time watching spaces print across your screen. In that environment, trimming spaces and using tabs to format columns provided a huge gain in throughput. Today, with our 10-megabit-per-second LAN connections and our 56kb modems, we hardly give this a thought. During the mid-1980s, Oracle experimented with efforts to add procedural capabilities to UFI. The result of this effort was AUFI, which stood for Advanced User Friendly Interface. AUFI implemented such things as IF statements and looping constructs, and was demonstrated publicly at an International Oracle User Group meeting in 1986 by Ken Jacobs, who is now the Vice-President of Data Server Product Management for Oracle. In spite of the public demos, whether or not to actually release AUFI as a shipping product was the subject of some debate within Oracle. Trying to layer a procedural language on top of the existing UFI command set was proving very difficult. It was made even more difficult by the need to maintain full backward compatibility so that existing scripts written by Oracle's clients would not suddenly break when those clients upgraded. Because of these issues, the code to support the procedural enhancements became very complex and somewhat unreliable. The issues of reliability and complexity led to Oracle's ultimate decision to kill the product, so AUFI never actually shipped. With the later advent of PL/SQL, procedural logic was supported within the database, and efforts to support a procedural scripting language were then seen as unnecessary. The name AUFI lives on in the name of the temporary file created when you use the SQL*Plus EDIT command. That file is named AFIEDT.BUF. Even today, AFI is the prefix used for all the source code. With the release of Oracle 5.0 in 1985, the name of the product was changed to SQL*Plus. The changes since then have been mostly evolutionary. Each new release brings with it a few new commands and a few new options on existing commands. Some commands have been made obsolete, but many of these obsolete commands are still supported for purposes of backward compatibility. The most recent changes to SQL*Plus have been the addition of support for commands such as STARTUP, SHUTDOWN, and RECOVER, which were previously only available in Server Manager. SQL*Plus is now the primary command-line interface to the Oracle database. Even SQL Worksheet, Enterprise Manager's adhoc query tool, makes use of SQL*Plus to execute the commands that you enter. Oracle's future plans for the product don't call for anything revolutionary, just a steady stream of enhancements in order to keep up with each new release of Oracle. It's just possible that SQL*Plus will be around for another fifteen years. < previous page page_7 next page > < previous page page_8 next page > Page 8 Why Master SQL*Plus? SQL*Plus is a universal constant in the Oracle world. Every installation I have ever seen has this tool installed. For that reason alone it is worth learning. Even if you prefer to use other tools, such as Enterprise Manager or Clear Access, you may not always have them available. In my work as a consultant I frequently visit clients to help them with Oracle. Some clients use GUI-based query tools, some don't. Some clients use Oracle Enterprise Manager, some don't. The one universal constant I can count on is the availability of SQL*Plus. The last thing I want is to be at a client site needing to look up something mundane such as an index definition, and not be able to do it because I'm not familiar with their tools. SQL*Plus is always there. If you are a database administrator, SQL*Plus is undoubtedly a tool you already use on a daily basis. Anything you use that often is worth learning and learning well. You undoubtedly use SQL*Plus to query Oracle's data dictionary tables in order to understand the structure of your database. SQL*Plus can be used to automate that task. Sometimes it's difficult to remember the specific data dictionary tables you need to join together in order to get the information you want. With SQL*Plus, you can figure this out once and encapsulate that query into a script. Next time you need the same information, you won't have all the stress of trying to remember how to get it, and you won't have to waste time rereading the manuals in order to relearn how to get it. SQL*Plus is also very useful for automating some routine DBA tasks. I have several SQL*Plus scripts (a script is a file of SQL statements and SQL*Plus commands) that produce reports on users and the database and object privileges these users have. I use these scripts to run periodic security audits on our database. I have scripts that report on tablespace usage, to help me keep on top of free space or the lack thereof. I also have scripts that run nightly to perform various maintenance tasks. If you are a developer, you can use SQL*Plus to build up queries, to quickly develop ad-hoc reports, and to explore the data in your database. You can also use SQL*Plus to create and debug stored procedures, stored functions, packages, and object types. If you have queries that aren't performing well, you may be able to find out why by using Oracle's EXPLAIN PLAN command from SQL*Plus. EXPLAIN PLAN will tell you the execution strategy chosen by the optimizer for the query. Chapter 8, Tuning and Timing, talks more about this. Many modern GUI development tools, such as PowerBuilder, for example, provide GUI-based query generators. These typically let you drag and drop tables into your query and then draw lines between fields joining those tables together. This drag-and-drop functionality may be great for a simple query that just joins a few < previous page page_8 next page > < previous page page_9 next page > Page 9 tables, but I find that it quickly becomes cumbersome as the query grows in complexity. It's not unusual, when developing reports, to have queries that are a page or more long. Sometimes these queries consist of several SELECT statements unioned together, each query having one or more subqueries. When developing one of those mega-queries, I'll take SQL*Plus and a good editor over a GUI query tool any day of the week. Why? Because with an editor I can keep bits and pieces of the query lying around. Using Windows copy and paste, I can pull out a subquery and execute it independently without losing track of the larger query I am trying to build. I can easily comment out part of a WHERE clause when debugging a query and then uncomment it later. If you are developing stored procedures, functions, packages, or Oracle object types using PL/SQL, then SQL*Plus may be the only tool you have for creating those in the database. Other tools, such as Oracle's Procedure Builder and Platinum Technology's SQL Station, are on the market, but not everyone will have a license to use those. In addition, third-party tools in particular may be slightly behind the curve when it comes to keeping up with Oracle releases. I suspect it took awhile for the third-party vendors to catch up when Oracle8, with its new object types, was released. Almost anything that you want to do with an Oracle database can be done using SQL*Plus. You can write scripts to automate routine maintenance tasks, report on the state of your database, or generate ad-hoc reports for end users. You can execute queries to explore your database, and you can use SQL*Plus to create and manage any schema or database object. Because of its universal availability, you will be able to perform these functions anywhere you go. If you manage an Oracle database or develop software to run against an Oracle database, you will greatly improve your productivity by mastering this tool. Creating and Loading the Sample Tables Many of the examples in this book, particularly the reporting examples, have been developed against a sample time- tracking database. It's a fairly simplistic database, containing only three tables, but it's enough to illustrate everything I talk about in this book. You may or may not wish to create this database for yourself. Creating the database will allow you to try all the examples in this book exactly as they are shown. If you choose not to create and load the sample database, at least familiarize yourself with the data model. Also glance at the sample data itself, which is reproduced later in this section. If you have looked at the model and at the data, you shouldn't have any trouble following and understanding the examples in this book. < previous page page_9 next page > . Introduction to SQL* Plus In this chapter: What Is SQL* Plus? History of SQL* Plus Why Master SQL* Plus? Creating and Loading the Sample Tables SQL* Plus is the command-line interface to the Oracle database a SQL query, SQL* Plus takes it and sends it to the database, the database returns the results to SQL* Plus, and SQL* Plus displays those results in a format you can understand. History of SQL* Plus SQL* Plus. PL /SQL and the Oracle Database. SQL* Plus is often used in conjunction with two other products, both of which have the letters SQL in their names. The first is SQL itself. Without a doubt, the most

Ngày đăng: 05/07/2014, 04:20

Từ khóa liên quan

Mục lục

  • Локальный диск

    • cover

    • page_iii

    • page_iv

    • page_v

    • page_vii

    • page_viii

    • page_ix

    • page_xi

    • page_xii

    • page_xiii

    • page_xiv

    • page_xv

    • page_xvi

    • page_xvii

    • page_xviii

    • page_xix

    • page_xx

    • page_xxi

    • page_1

    • page_2

Tài liệu cùng người dùng

Tài liệu liên quan