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
1,78 MB
Nội dung
CHAPTER 14 • STORED PROCEDURES
520
6. On the third screen, check the Insert box next to the authors table. Click Next.
7. On the final screen, click the Edit button.
8. On the Edit screen, change the name of the stored procedure to Authors_Insert,
then click OK.
2627ch14.qxt 8/22/00 10:53 AM Page 520
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
521
9. On the final screen, click Finish. Note that the Edit button will allow you to
change the code used to create the stored procedure, but you do not want to
make any changes here.
UNDERSTANDING STORED PROCEDURES
Digging into SQL
Server
PART
III
2627ch14.qxt 8/22/00 10:53 AM Page 521
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 14 • STORED PROCEDURES
522
If you would like to see exactly what this stored procedure will do for you, open it
and look at its properties in Enterprise Manager. You will notice in Figure 14.1 that it
is a simple stored procedure that uses input parameters to insert new records into the
authors table.
FIGURE 14.1
The Create Stored
Procedure Wizard is
designed to create
quick, simple stored
procedures.
Now that you know how to create and use stored procedures, you need to know how
to keep them running fast. Let’s get a little more in depth on how they work and
how to optimize them.
Optimizing Stored Procedures
To optimize a stored procedure, it is best for you to understand a little more about
how SQLServer executes queries. When SQLServer first executes a query (any query,
not just stored procedures), it compiles the query first. The compiling process is just
SQL Server peering inside your query to see what you are trying to accomplish. Specif-
ically, SQLServer looks at what tables you are JOINing and what columns you have
specified in the WHERE clause of your query. Once the server has this knowledge, it
can develop an execution plan, which is a map of what indexes would return data
fastest. Once the execution plan has been devised, SQLServer stores it in procedure
cache, which is an area of RAM that has been specifically apportioned for this purpose.
2627ch14.qxt 8/22/00 10:53 AM Page 522
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
523
Now, whenever you run the same query again or a very similar query, SQLServer does
not need to create another execution plan to get your data; it simply uses the execu-
tion plan that has been stored in the procedure cache.
This can cause a problem for you at times, though. For instance, you may need to
change the structure (or schema) of your database, adding a new table or columns to
an existing table. If this kind of change occurs, SQLServer will automatically recom-
pile your stored procedures to use the changes in the structure. The only time the
stored procedure will not be recompiled is if you create a new index; in that instance,
you must recompile the stored procedure manually so that SQLServer can create an
execution plan that takes advantage of the new index.
Or, suppose that you have a stored procedure that uses widely varied input para-
meters every time you run it. Some of those parameters may affect the JOIN or
WHERE clause statements in the stored procedure, and because SQLServer uses those
parameters to create an execution plan, it may not be wise to use the same execution
plan every time the stored procedure is run—you may want to recompile it. You have
two ways to force SQLServer to recompile your stored procedure; the first is by creat-
ing it with the WITH RECOMPILE statement.
WITH RECOMPILE will force SQLServer to create a new execution plan each and
every time you execute the stored procedure and is the best way to create a stored pro-
cedure that has input parameters that change drastically every time you use it (and
affect the JOIN and WHERE clauses in the stored procedure). For example, if you
wanted to recompile the Show_Authors stored procedure every time you run it, the
code to create it would look as follows:
CREATE PROCEDURE Show_Authors
@city varchar(50)
WITH RECOMPILE
AS
SELECT au_fname, au_lname, address, city, state, zip
FROM authors
WHERE city = @city
ORDER BY au_lname DESC
It is the WITH RECOMPILE option that tells SQLServer to create a new execution
plan every time the stored procedure is executed and not store that execution plan in
cache. That can be tedious and slow if you need to change the execution plan only
occasionally, though. If that is the case, you should use the second method for recom-
piling a stored procedure: the EXECUTE…WITH RECOMPILE statement. EXECUTE…
WITH RECOMPILE tells SQLServer to create a new execution plan just this one time,
not every time the statement is executed. If you use this statement, the code used to
UNDERSTANDING STORED PROCEDURES
Digging into SQL
Server
PART
III
2627ch14.qxt 8/22/00 10:53 AM Page 523
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 14 • STORED PROCEDURES
524
create the stored procedure does not change, but when you execute the stored proce-
dure, it looks as follows:
EXEC Show_Authors WITH RECOMPILE
By using these RECOMPILE statements, you can keep your stored procedures running
fast. However, thus far, you haven’t secured them from prying eyes—let’s do that now.
Securing Your Stored Procedures
When you create a stored procedure, you are just creating a query that is stored on
the server rather than on the client machines. These stored procedures are contained
in the syscomments system table in each database and are completely accessible by
default. This means that by executing a simple SELECT query against the syscom-
ments table in the database where the stored procedure was created, your users could
see all of the code used to create the procedure. This may not be desirable because one
of the main uses of a stored procedure is to remove the user from the complexity and
structure of the underlying tables, and, as we will discuss in Chapter 18, stored proce-
dures are used for securing tables as well. By reading the definition of the stored pro-
cedure right from syscomments, the users would be bypassing that security; in other
words, they would be hacking. To avoid that, you should create stored procedures
using the WITH ENCRYPTION statement.
WITH ENCRYPTION is designed to keep prying eyes out of definitions stored in
the syscomments table—not just for stored procedures, but for everything stored
there (views, triggers, etc.). In the following exercise, you will execute a SELECT query
against the syscomments table in the pubs database to see what is stored there and,
therefore, what your users could see:
1. Open Query Analyzer and log in using Windows NT Authentication (unless you
need to use SQLServer Authentication).
2. Enter the following code and execute it by clicking the green arrow button on
the toolbar (you have to join the sysobjects table because the name is stored
there—only the ID is stored in syscomments):
USE Pubs
SELECT ob.name, com.text
FROM syscomments com
JOIN sysobjects ob
ON ob.id = com.id
WHERE ob.name = ‘Show_Authors’
2627ch14.qxt 8/22/00 10:53 AM Page 524
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
525
3. Notice in the result set that you can read the code used to create and run the
stored procedure.
4. To encrypt it, open Enterprise Manager, expand the pubs database, then select
the Stored Procedures icon.
5. In the contents pane, double-click the Show_Authors stored procedure to bring
up the properties.
6. To encrypt the stored procedure, change the definition to look as follows (notice
the bold changes):
CREATE PROCEDURE DBO.Show_Authors
@city varchar(50) = ‘Oakland’
WITH ENCRYPTION
AS
SELECT au_fname, au_lname, address, city, state, zip
FROM authors
WHERE city = @city
ORDER BY au_lname DESC
UNDERSTANDING STORED PROCEDURES
Digging into SQL
Server
PART
III
2627ch14.qxt 8/22/00 10:53 AM Page 525
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 14 • STORED PROCEDURES
526
7. Click OK to apply the changes.
8. To verify that it has been encrypted, double-click Show_Authors to bring up the
properties again. You should receive an error message stating that the object is
encrypted and therefore unreadable. Click OK to return to the stored procedure
properties screen.
9. Return to Query Analyzer and execute the query from step 2 again; notice that
this time you cannot read the text from syscomments, because it is full of
unreadable characters (these characters may vary depending on your system).
2627ch14.qxt 8/22/00 10:53 AM Page 526
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
527
10. Close Query Analyzer.
WARNING Once you create an object, such as a stored procedure, using WITH
ENCRYPTION, you cannot decrypt the object. Make sure you are finished modifying the
object for a while before encrypting.
User-defined stored procedures (the ones you make yourself) are a very powerful tool,
but they are not the only stored procedures with which you have to work. Microsoft has
given you a batch of ready-made stored procedures that are designed to help you work
with system tables. These are called system and extended stored procedures.
Using System and Extended Stored Procedures
Microsoft has started using the term metadata quite a bit these days; it means informa-
tion about information. When the term is applied to SQL Server, it means information
about objects on the server, such as how big a database file is or what permissions a
user has. When you want to change or read such system information, you could open
the system tables directly and start fiddling with the data inside, but that usually turns
UNDERSTANDING STORED PROCEDURES
Digging into SQL
Server
PART
III
2627ch14.qxt 8/22/00 10:53 AM Page 527
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 14 • STORED PROCEDURES
528
out badly because most of the values in the system tables are not designed to be under-
stood by mere mortal humans (most of the values in these tables are numeric and not
easily decoded). A much better way, the supported way, to change or read the system
information is by using system stored procedures.
Using System Stored Procedures
Every time you add a database, add a login (which is used to grant access to SQL Server),
create an index, or add or modify any object on the server, you are making changes to
the system tables, which is where SQLServer stores information about your objects. The
information stored in these system tables is mostly numeric data, which is difficult to
read, let alone modify, directly. That is why Microsoft has given you scores of stored
procedures (about 650) to help with the task of modifying system tables. They are all
stored in the master and msdb databases, and most begin with the characters sp_. Here
is a synopsis of some of the more common system stored procedures:
sp_tables: This stored procedure will show you any object that can be used
in the FROM clause of a SELECT query. This is useful if you have forgotten or
just don’t know the exact name of the table or view you need to query.
sp_stored_procedures: This will list all of the stored procedures available
for your use. Again this is useful if you have forgotten or just don’t know the
name of the procedure you need.
sp_server_info: Using this procedure is the best way to determine how your
SQL Server was configured at setup, such as the character set or sort order that
was defined at install, what version of SQLServer you are running (for exam-
ple, desktop or standard), etc.
sp_databases: This lists all of the available databases on the server. It can be
useful for finding database names.
sp_start_job: This is used to start an automation job in SQL Server. This is
very handy for jobs that are scheduled on demand. We’ll be discussing jobs and
automation in Chapter 17.
sp_stop_job: This procedure will stop a job that has been started already.
sp_addlogin: This procedure is used to add a standard login to the server to
allow users access to the server as a whole. This is very useful for creating a
script that will regenerate user logins in the event of a system crash. We’ll dis-
cuss security and logins in Chapter 18.
sp_grantlogin: This is used to grant access on SQLServer to a Windows NT
account. This should be combined with the sp_addlogin account to create a
script to re-create user accounts in the event of a disaster.
2627ch14.qxt 8/22/00 10:53 AM Page 528
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
529
sp_setapprole: An account role in SQLServer (as you will see in Chapter 18)
is used to make sure that only approved applications are used to access your
database. This stored procedure activates the application role so that the user
can access the database with the permissions that are granted to the applica-
tion role.
sp_password: As you will see in Chapter 18, there is a difference between
standard and Windows NT login accounts; this stored procedure is used to
change passwords for standard, and only standard, logins.
sp_configure: Several global configuration options can be set to change the
way SQLServer behaves. For example, you can tell the server whether to allow
updates to system tables directly or how much system memory to use. The
sp_configure stored procedure can be used to change such options. The avail-
able options are listed here:
• affinity mask
• allow updates
• concat_null_yields_null
• cost threshold for parallelism
• cursor threshold
• default full-text language
• default language
• extended memory size
• fill factor
• index create memory
• language in cache
• lightweight pooling
• locks
• max degree of parallelism
• max server memory
• max text repl size
• max worker threads
• media retention
• min memory per query
• min server memory
• nested triggers
UNDERSTANDING STORED PROCEDURES
Digging into SQL
Server
PART
III
2627ch14.qxt 8/22/00 10:53 AM Page 529
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... the name implies: They extend the capabilities of SQLServer so that it can do things that a database server would not ordinarily be capable of doing For example, you wouldn’t expect a database server to be able to execute a command from the command prompt, but thanks to an extended stored procedure that comes with SQL Server, called xp_cmdshell, SQLServer can do just that Extended stored procedures... your SQLServer have a record in the sysdatabases system table in the master database This record tells SQLServer where the database is on disk, how big it is, etc If you were to lose your master database and (heaven forbid) not have a good backup, you would need to run this stored procedure to re-create the records in sysdatabases for each of the databases on your server sp_processmail: SQL Server. .. the SQL Server 2000 group under Programs on the Start menu and log in with Windows NT Authentication (unless you must use SQLServer Authentication) 2 To use sp_help to get information about the authors table in the pubs database, enter and execute the following code: USE Pubs EXEC sp_help ‘authors’ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark PA R T III Digging into SQL. .. your server sp_processmail: SQLServer is capable of not only sending, but receiving and responding to e-mail When SQL Mail is configured (which you will learn how to do in Chapter 17), you can send a query via e-mail to the MSSQLServer service When you run this stored procedure, the MSSQLServer service will read the query in the e-mail and send back the result set Please purchase PDF Split-Merge on... record passes, the insert is completed; if the record does not pass, the record is not inserted SQLServer is able to block data modifications if they don’t pass your stringent criteria because triggers are considered transactions A transaction (as discussed in Chapter 8) is a block of Transact -SQL code that SQLServer treats as a unit Code is grouped Please purchase PDF Split-Merge on www.verypdf.com to... Summary Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark PA R T III Digging into SQL Server In this chapter, you learned all about stored procedures You learned first what they are—just a collection of Transact -SQL statements, usually a query, that is stored centrally on the server waiting to be executed by users The advantage to storing these centrally is that when your users... some here: 1 Open Query Analyzer from the MS SQL Server group under Programs on the Start menu and log in with Windows NT Authentication 2 To use xp_cmdshell to get a directory listing of your C drive, enter and execute the following code: EXEC xp_cmdshell ‘dir c:’ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Digging into SQL Server 2627ch14.qxt 2627ch14.qxt 534 8/22/00... into a table, SQLServer copies the new record into a table in the database called the trigger table and a special table stored in memory called the inserted table As shown in Figure 15.1, this means that your new record exists in two tables, the trigger table and the inserted table The records in the inserted table should exactly match the records in the trigger table FIGURE 15.1 SQLServer places... you will need to refer to Chapter 11 to create it Next, you will need to fill the tables with some values: 1 Open Query Analyzer by selecting it from the SQL Server 2000 group in Programs on the Start menu and log in using either Windows NT or SQLServer Authentication 2 You need to enter some customers to sell products to Enter and execute the following code to populate the customers table with customer... letting the manager know who deleted the customer and when Ordinarily, when a user executes a DELETE statement, SQLServer removes the record from the table, and the record is never heard from again That behavior changes when a DELETE trigger is added to the table With a DELETE trigger in place, SQLServer moves the record being deleted to a logical table in memory called deleted, which means that the records . access to SQL Server) ,
create an index, or add or modify any object on the server, you are making changes to
the system tables, which is where SQL Server. compiling process is just
SQL Server peering inside your query to see what you are trying to accomplish. Specif-
ically, SQL Server looks at what tables