3 4
SQL Server 2000 provides several methods for executing Transact-SQL statements. You can execute single statements, or you can execute the statements as a batch (which is a group of one or more Transact-SQL statements). You can also execute Transact-SQL statements through stored procedures and triggers. This lesson introduces you to the various methods that you can use to execute statements. This lesson also provides you with an overview of how these statements are executed, depending on the method of execution. Finally, this lesson discusses how you can use scripts to execute Transact-SQL statements.
Processing a single SQL statement is the most basic way that SQL Server 2000 executes SQL statements. How a statement is processed can best be illustrated by looking at how a SELECT statement is processed.
A SELECT statement is nonprocedural; it does not state the exact steps that the database server should use to retrieve the requested data. In other words, the database server must analyze the statement to determine the most efficient way to extract the requested data. This process is called optimizing the SELECT statement, and the component that performs this procedure is called the query optimizer.
The process of choosing one execution plan from several possible plans is called optimization. The query optimizer is one of the most important components of a SQL database system. While the query optimizer uses some overhead to analyze the query and choose a plan, this overhead is compensated several-fold when the query optimizer picks an efficient execution plan. For example, two construction companies can be given identical blueprints for a house. If one company spends a few days at the start to plan how it will build the house and the other company starts building without planning, the company that takes the time to plan its project will most likely finish first.
The query optimizer is important because it enables the database server to adjust dynamically to changing conditions in the database without requiring input from a programmer or from a database administrator. This process enables programmers to focus on describing the final result of the query. They can trust that the query optimizer will always build an efficient execution plan for the state of the database each time the statement is run.
The steps used to process a single SELECT statement referencing only local base tables (no views or remote tables) illustrates the basic process of executing most Transact-SQL statements. SQL Server uses the following steps to process a single SELECT statement:
The basic steps described for processing a SELECT statement apply to other SQL statements as well, such as INSERT, UPDATE, and DELETE. UPDATE and DELETE statements both target the set of rows to be modified or deleted. The process of identifying these rows is the same process used to identify the source rows that contribute to the result set of a SELECT statement. The UPDATE and INSERT statements can both contain embedded SELECT statements that provide the data values to be updated or inserted.
Even DDL statements such as CREATE PROCEDURE or ALTER TABLE are ultimately resolved to a series of relational operations on the system catalog tables and sometimes (such as ALTER TABLE and ADD COLUMN) against the data tables.
A batch is a group of one or more Transact-SQL statements sent all at once from an application to SQL Server for execution. SQL Server compiles the statements of a batch into a single executable unit (called an execution plan). The statements in the execution plan are then executed one at a time.
A compile error, such as a syntax error, prevents the compilation of the execution plan so that none of the statements in the batch are executed. A run-time error, such as an arithmetic overflow or a constraint violation, has one of two effects:
The statements executed before the one that encountered the run-time error are not affected. The only exception is if the batch is in a transaction and the error causes the transaction to be rolled back. In this case, any uncommitted data modifications made before the run-time error are rolled back.
For example, assume that there are 10 statements in a batch. If the fifth statement has a syntax error, none of the statements in the batch are executed. If the batch is compiled and the second statement fails while executing, the result of the first statement is not affected (because it has already been executed).
The following rules apply to batches:
SQL Query Analyzer, the osql utility, and the isql utility use the GO command to signal the end of a batch. GO is not a Transact-SQL statement; rather, it simply signals to the utilities how many SQL statements should be included in a batch. In SQL Query Analyzer and osql, all of the Transact-SQL statements from one GO command to the next are put in the string sent to SQLExecDirect. In isql, all of the Transact-SQL statements between GO commands are placed into the command buffer before being executed.
Because a batch is compiled into a single execution plan, a batch must be logically complete. The execution plan created for one batch has no capacity to reference any variables declared in another batch. Comments must both start and end in the same batch.
The following example creates a view. Because CREATE VIEW must be the only statement in a batch, the GO commands are required to isolate the CREATE VIEW statement from the USE and SELECT statements around it.
USE pubs GO CREATE VIEW auth_titles AS SELECT * FROM authors GO SELECT * FROM auth_titles GO
A batch is a collection of one or more SQL statements sent in one unit by the client. Each batch is compiled into a single execution plan. If the batch contains multiple SQL statements, all of the optimized steps needed to perform all of the statements are built into a single execution plan.
There are several ways to specify a batch:
If a batch sent from an application contains an EXECUTE statement, the execution plan for the executed string or stored procedure is performed separately from the execution plan containing the EXECUTE statement. The execution plan generated for the string executed by an sp_executesql stored procedure also remains separate from the execution plan for the batch containing the sp_executesql call. If a statement in a batch invokes a trigger, the trigger execution plan executes separately from the original batch.
For example, a batch that contains the following four statements uses five execution plans:
Figure 2.12 illustrates how these four statements are processed.
Figure 2.12 Batch processing.
A stored procedure is a group of Transact-SQL statements that is compiled one time and that can then be executed many times. This functionality increases performance when the stored procedure is executed because the Transact-SQL statements do not have to be recompiled.
A trigger is a special type of stored procedure that a user does not call directly. When the trigger is created, it is defined to execute when a specific type of data modification is made against a specific table or column.
A CREATE PROCEDURE or CREATE TRIGGER statement cannot span batches. In other words, a stored procedure or trigger is always created in a single batch and is compiled into an execution plan.
SQL Server 2000 stores only the source for stored procedures and triggers. When a stored procedure or trigger is first executed, the source is compiled into an execution plan. If the stored procedure or trigger is again executed before the execution plan is aged from memory, the relational engine detects the existing plan and reuses it. If the plan has aged out of memory, a new plan is built. This process is similar to the process that SQL Server 2000 follows for all SQL statements. The main performance advantage that stored procedures and triggers have in SQL Server 2000 is that their SQL statements are always the same; therefore, the relational engine matches them with any existing execution plans.
Stored procedures had a more pronounced performance advantage over other SQL statements in previous versions of SQL Server. Earlier versions of SQL Server did not attempt to reuse execution plans for batches that were not stored procedures or triggers. The only way to reuse execution plans was to encode the SQL statements in stored procedures.
The execution plan for stored procedures and triggers is executed separately from the execution plan for the batch that is calling the stored procedure or firing the trigger. This feature facilitates more frequent reuse of the stored procedure and trigger execution plans.
Stored procedures are discussed in more detail in Chapter 8, "Implementing Stored Procedures." Triggers are discussed in more detail in Chapter 9, "Implementing Triggers."
A script is a series of Transact-SQL statements stored in a file. The file can be used as input to SQL Query Analyzer or to the osql and isql utilities. The utilities then execute the SQL statements stored in the file.
Transact-SQL scripts have one or more batches. The GO command signals the end of a batch. If a Transact-SQL script does not have any GO commands, it is executed as a single batch.
You can use Transact-SQL scripts to perform the following tasks:
SQL Server 2000 provides several methods for executing Transact-SQL statements. Processing a single SQL statement is the most basic way that SQL Server 2000 executes SQL statements. When a statement is processed, the database server analyzes the statement to determine the most efficient way to extract the requested data. The process of choosing one execution plan from several possible plans is called optimization. When processing a statement, SQL Server follows specific steps. SQL Server can process statements as a batch. A batch is a group of one or more Transact-SQL statements sent all at once from an application to SQL Server for execution. SQL Query Analyzer, the osql utility, and the isql utility use the GO command to signal the end of a batch. Each batch is compiled into a single execution plan. If the batch contains multiple SQL statements, all of the optimized steps needed to perform all of the statements are built into a single execution plan. A stored procedure is a group of Transact-SQL statements that are compiled one time and that can be executed many times. A trigger is a special type of stored procedure that a user does not call directly. SQL Server 2000 stores only the source for stored procedures and triggers. A script is a series of Transact-SQL statements stored in a file. The file can be used as input to SQL Query Analyzer or to the osql and isql utilities. The utilities then execute the SQL statements stored in the file.