[Top] [Prev] [Next]

Chapter 5

Transact-SQL and Utilities


Introduction

Transact-SQL enhances the power of SQL to provide a more powerful and versatile language set than other versions of SQL. The Transact-SQL implementation aims to minimize or eliminate the need to use any other programming language within the Sybase environment. Transact-SQL functionality exceeds both the ANSI (American National Standards Institute) standard and the many commercial versions of SQL. It lets you define business rules, transaction logic, and referential integrity as stored procedures.

This chapter describes the rich toolset that Transact-SQL provides, including:

The compute Clause

The compute clause is used with the row aggregate functions sum, min, max, avg, and count to calculate summary values. The results of a query that includes a compute clause are displayed with both detail and summary rows; the output is in a report-style format that many database management systems can produce only with a report generator. compute displays summary values as additional rows in the results rather than as new columns. Here's a query that computes the average price of different types of cookbooks and its results.

select title_id, type, price 

from titles 

where type like "%cook" 

order by type, price 

compute avg(price) by type 

 title_id type         price                     

 -------- ------------ ------------------------  

 MC3021   mod_cook                         2.99  

 MC2222   mod_cook                        19.99  

                       avg                       

                       ------------------------  

                                          11.49  

 

 title_id type         price                     

 -------- ------------ ------------------------  

 TC4203   trad_cook                       11.95  

 TC7777   trad_cook                       14.99  

 TC3218   trad_cook                       20.95  

                       avg                       

                       ------------------------  

                                          15.96  

Control-of-Flow Language

Transact-SQL provides a control-of-flow language that can be used as part of any SQL statement or batch. It includes these constructs:

You can define local variables with declare and assign them values. Several predefined global variables are supplied by the system.

Generated Primary Keys

You can use the IDENTITY property to generate unique, sequential key values for numeric columns with a scale of 0 (that is, with no decimal places). When you insert a row into a table with an IDENTITY column, SQL Server automatically generates the column value. The first time a user inserts a row into a table, SQL Server assigns the IDENTITY column a value of 1. The IDENTITY column value is incremented by one for each new row inserted. You can use columns with the IDENTITY property as primary keys for applications where no other key exists.

A database owner or system administrator can use the set option identity_insert to explicitly insert values into identity columns. You can check the @@identity global variable to determine the last value inserted into an IDENTITY column.

Stored Procedures

Stored procedures are a key factor in SQL Server's efficiency because the procedure can be precompiled and stored in the procedure cache. Typically, they can be processed in a fraction of the time it takes to process a single ad hoc SQL command. Figure 5-1 shows a client invoking a stored procedure. Stored procedures give a three-part performance gain. First, because the procedure is stored as a precompiled tree on disk, it takes less time to prepare for execution; second, they reduce network traffic because the precompiled procedure constitutes a smaller amount of data to transmit than the non-compiled version; and last, once the procedure is in the procedure cash, there is no disk I/O time associated with running the procedure because it is already in cache.

Figure 5-1: A stored procedure

You can define business rules, transaction logic, and referential integrity as stored procedures. They are batches of Transact-SQL statements that can include commands to begin, commit, and rollback transactions, control the flow of program logic, declare variables, send messages, and initiate an action after a defined time delay.

Stored procedures are both reusable and sharable. When you define a stored procedure, SQL Server compiles it and stores it in shared procedure cache so that multiple users can make use of the same precompiled code. At run time, the application issues a procedure call and passes parameters, if there are any. SQL Server then executes the stored procedure without recompiling.

Stored procedures offer the following advantages over batches:

Constraints

Constraints help maintain data integrity. They are declared as part of a create table statement, and can be added, dropped or changed as part of an alter table statement. They define what kind of data can be stored in a particular column, or the relationship between primary and foreign key columns of related tables. Constraints are discussed in more detail in Chapter 8, "Data Integrity and Consistency."

Rules

Rules are user-defined integrity constraints; they specify the domain of legal values for a particular column or datatype. SQL Server checks data entries against any rules that have been created for the data's column and datatype. Rules are discussed in more detail in Chapter 8, "Data Integrity and Consistency."

Defaults

A default is a user-defined value linked to a particular column or datatype, and inserted by SQL Server if no value is provided at data-entry time. Defaults are discussed in more detail in Chapter 8, "Data Integrity and Consistency."

Triggers

A trigger is a special event-driven stored procedure associated with a specific table; it executes when a data modification statement, such as insert, update or delete, attempts to affect that table; that is, the trigger "fires" even if no rows are affected. Depending on which data modification statement drives the trigger, it is referred to as an update trigger, insert trigger, or delete trigger. Triggers are also discussed in more detail in Chapter 8, "Data Integrity and Consistency."

Figure 5-1 shows a delete trigger called del_title created on the titles table. The trigger fires whenever there is an attempt to delete a row in the titles table.

Figure 5-2: A trigger driven by a delete statement

Triggers can cause the statement that issued them to be rolled back if needed with an appropriate message to the user. They can also perform such actions as cascading deletes, archiving changed or deleted data, or firing other stored procedures.

Triggers provide more complex integrity rules than constraints or rules. The "trigger" aspect together with the "batch" aspect of a trigger make it a very useful feature. Here are the most common way triggers are used:

The first two uses in the list are the most common. Chapter 8, ``Data Integrity and Consistency,'' discusses triggers within the context of data integrity.

Views

Views provide an alternate way of looking at the data in one or more tables. Views are used to focus, simplify, and customize each user's perception of the database. They can also provide a security mechanism for limiting access to the data in the tables.

Unlike many other versions of SQL, Transact-SQL places no restrictions on retrieving data through views, and relatively few restrictions on updating data through views.

Transact-SQL is also different from many other versions of SQL in that it allows you to redefine or change a view without forcing you to redefine other views that depend on it (unless the redefinition makes it impossible for SQL Server to translate the dependent view).

Cursors

Transact-SQL provides cursors that meet ISO/ANSI SQL 89 specifications. A cursor is a symbolic name that you can associate with a select command. A cursor is functionally a pointer to a row in a table. When you execute a select command that doesn't have a cursor, SQL Server processes the results for every row selected and then returns the result as a unit. When you associate a cursor with the select command, you control the forward traversal through the selected columns row by row.

A select operation with cursors offers the following advantages over a select operation without cursors:

Transact-SQL Cursors also have these additional capabilities:

The sp_cursorinfo and sp_lock system procedures provide information on cursor activity.

Error Handling

The Transact-SQL programmer can use a number of error handling tools and techniques. These include capabilities that allow you to:

You can use the raiserror and print commands, in combination with the control-of-flow language, to direct error messages to the Transact-SQL application user.

Transact-SQL System Administration Capabilities

Transact-SQL provides several system administration capabilities not found in other implementations of SQL. Many of the system administration commands are used in conjunction with system procedures. In addition, there are:

Built-in Functions

Transact-SQL provides dozens of built-in functions divided into the following categories:

text and image Datatypes

Transact-SQL supports the text datatype for long entries of printable characters and the image datatype for long entries of binary data. The Transact-SQL extensions readtext and writetext, and comparable library routines, provide rapid retrieval for client applications. Built-in functions for commonly needed operations are provided for text and image data.

Transact-SQL's Debugger

SQL Debug®, a separate Sybase product, provides a graphical user interface for debugging SQL code. It provides full support for all Transact-SQL extended features, even nested stored procedure calls and full cursor debugging. Options include step-level execution, breakpoint setting, conditional tracing, and complete control over variables. You can use separate windows to display SQL commands, results, and variable values. It debugs code generated by third-party tools, and can debug multiple client connections from a single screen. It can identify performance bottlenecks, and highlight logic that might result in performance problems.

Other Transact-SQL Extensions

Other unique or unusual features of Transact-SQL include:



[Top] [Prev] [Next] [Bottom]