Configuration Functions These functions return information about different settings and constants for the SQL Server implementation: @@@CONNECTIONS Returns the number of connections sinc
Trang 1Function Description
number of the currentstored procedure
TYPEPROPERTY(type, property) Returns information
about the datatype
Security Functions
SQL Server 7.0 has introduced many improvements in the area of
security The most important of these is the introduction of the “role”
concept Roles in SQL Server correspond to roles in MS Transaction
Server and groups in Windows NT
In earlier versions of SQL Server, users could belong to only one
group This restriction led to problems when a developer wanted to
implement more complex security rules The result was often a security
hierarchy of groups, where each “higher” group could perform all
activities that “lower” groups could perform Unfortunately, this model
does not always correspond to the requirements of a particular business
environment Some implementations involved a considerable number
of groups, all of which had to be managed
In SQL Server 2000 and SQL Server 7.0, one user can be associated
with many roles Thus, you can assign a set of permissions to a role
and then assign each user a set of required roles
Security functions return information about users, roles, and their
assignments:
IS_MEMBER(group | role) Indicates whether the
current user is a member
of a Windows NT group
or SQL Server role
IS_SERVERROLEMEMBER(role[, login]) Indicates whether
the current user is amember of the specifiedserver role
Trang 2Function Description
SUSER_ID([login]) Returns the user’s login
identification number.SUSER_NAME([user_id]) Returns the user’s login
identification name.SUSER_SID([login]) Returns the user’s security
identification number.SUSER_SNAME([user_sid]) Returns the login
identification namefor the user’s securityidentification number.USER_ID([user]) Returns the database
user’s identificationnumber
name
Text and Image Functions
SQL Server does not have an elaborate set of text and imagefunctions, since you should generally not keep your documents orpictures inside the database The proper place for these files is in thefile system You should keep only descriptions of and pointers (that
is, the path) to those files in the database itself
PATINDEX(%pattern%, expression) Returns the starting position
of the first occurrence of thepattern
TEXTPTR(column) Returns the text pointer
value
TEXTVALID(column, text_pointer) Validates the given text
pointer
Trang 3Cursor Functions
These functions are designed to return status information about
cursors and cursor operations
@@@CURSOR_ROWS Returns the number of
rows that are in the lastcursor opened in theconnection
@@@FETCH_STATUS Returns status of the last
cursor fetch statement
Configuration Functions
These functions return information about different settings and
constants for the SQL Server implementation:
@@@CONNECTIONS Returns the number of connections
since SQL Server was started
@@@DATEFIRST Returns the value of theSET
DATEFIRSTparameter that indicatesthe specified first day of each week
@@@DBTS Returns the value of thetimestamp
datatype
@@@LANGUAGE Returns the name of the language that
is currently in use by SQL Server
Trang 4Function Description
@@@LANGID Returns the language ID for the
language that is currently in use bySQL Server
@@@LOCK_TIMEOUT Returns the lock time-out setting
(milliseconds)
@@@MAX_CONNECTIONS Returns the maximum number of
simultaneous connections allowed onSQL Server
@@@MAX_PRECISION Returns the level of precision used by
decimal and numeric datatypes on theserver
@@@OPTIONS Returns information about currentSET
options
@@@NESTLEVEL Returns the nesting level for the
current stored procedure
@@@REMSERVER Returns the name of a remote server
@@@SPID Returns the server process ID for the
current process
@@@SERVERNAME Returns the name of the server
@@@SERVICENAME Returns the name of the registry key
under which SQL Server is running
@@@TEXTSIZE Returns the current value of the
TEXTSIZEoption specified by theSETstatement (maximum length in bytes
of text and image data in theSelectstatement)
@@@VERSION Returns date, processor type, and
version of Microsoft SQL Server
A stored procedure can call or execute another stored procedure.Such stored procedures are said to be “nesting.” SQL Server 7.0 andSQL Server 2000 have a limit of 32 stored procedure nesting levels.Earlier versions could nest up to 16 stored procedures
Trang 5The@@NESTLEVELglobal variable keeps track of the number of
nesting levels and can be used before executing a stored procedure to
determine whether the number of nesting levels will cause the stored
procedure to fail
TIP: Although the number of nesting levels is limited, there is no limit on
the number of stored procedures that can becalled from a single stored
procedure You can use this capability to construct a workaround if you ever
encounter a problem with this issue You will seldom have this problem, but
the function has value as a debugging tool You should not bother to test this
value before each procedure call
System Statistical Functions
SQL Server maintains statistics about its performance and execution
from the moment that it is started The following functions are
designed to obtain statistical information:
@@@CPU_BUSY Returns the time the CPU spent
performing a task since SQL Server waslast started Time is in milliseconds
@@@IDLE Returns the time (in milliseconds) that
SQL Server has been idle since it wasstarted
@@@IO_BUSY Returns the time (in milliseconds) that
SQL Server spent performing input andoutput operations since it was started
@@@PACK_RECEIVED Returns the number of input packets
read from the network
@@@PACK_SENT Returns the number of output packets
written to the network
@@@PACKET_ERRORS Returns the number of network packet
errors since SQL Server was started
Trang 6Function Description
@@@TIMETICKS Returns the number of microseconds
per tick
@@@TOTAL_ERRORS Returns the number of read/write errors
since SQL Server was started
@@TOTAL_READ Returns the number of disc reads
without cache reads by SQL Server since
it was started
@@@TOTAL_WRITE Returns the number of disc writes by
SQL Server since it was started
Aggregate Functions
These functions perform an operation on a set of fields and return asingle value Their use is relatively limited They can be used in thefollowing situations:
▼ The selection list of theSelectstatement
Trang 7Function Description
GROUPING(Column_Name) Creates an additional column
with a value of 1 when a row isadded by theCUBEorROLLUPoperator or 0 if it is not the result
of aCUBEorROLLUPoperator
MAX(expression) Returns the maximum value in
STDEV(expression) Returns the statistical standard
deviation for the values in theexpression
STDEVP(expression) Returns the statistical standard
deviation for the population forthe values in the expression
VAR(expression) Returns the statistical variance of
the values in the expression
VARP(expression) Returns the statistical variance for
the population for the values inthe expression
Except for theCOUNTfunction, all aggregate functions remove
records that have null in the specified field from the set
select AVG(Rent) [Average Rent] from Inventory
As you can see, SQL Server will even print a warning about nulls:
Average Rent
Trang 8
(1 row(s) affected)
Warning: Null value eliminated from aggregate.
You applyCOUNTon a specific field:
select COUNT(Rent) [Rentals] from Inventory
SQL Server will count only records that do not have null in theRent field:
Rentals - 241
(1 row(s) affected)
Warning: Null value eliminated from aggregate.
You can applyCOUNTon all fields:
select COUNT(*) [Assets] from Inventory
SQL Server counts all records in the table:
Assets - 7298
(1 row(s) affected)
Rowset Functions
Functions from this set are unusual in that they return a completerecordset to the caller They cannot be used (as scalar functions) inany place where an expression is acceptable They can be used inTransact-SQL statements only in situations where the server expects
a table reference An example of such a situation is theFromclause oftheSelectstatement These functions were introduced in MicrosoftSQL Server 7.0
Trang 9TheOPENQUERYfunction is designed to return a recordset from a
linked server It can be used as a part ofSelect,Update,Insert,
andDeleteTransact-SQL statements TheQueryparameter must
contain a valid SQL query in the dialect of the linked server, since the
query will be executed (as-is—as a pass-through query) on the linked
server This function uses the following syntax:
OPENQUERY(linked_server, 'query')
NOTE: Linked servers are OLE DB data sources that are registered on the
local SQL Server After registration, the local server knows how to access
data on the remote server All that is needed in your code is a reference to
the name of the linked server
You can register a linked server to be associated with the
Northwind.mdb sample database either from Enterprise Manager or
using the following code:
EXEC sp_addlinkedserver
@server = 'Northwind_Access',
@provider = 'Microsoft.Jest.OLEDB.4.0',
@srvproduct = 'OLE DB Provider for Jet',
@datasrc = 'c:\program files\Microsoft '
+ 'Office2000\Office\Samples\northwind.mdb' Go
Then, you can use theOPENQUERYfunction to return records from
the linked server:
SELECT *
FROM OPENQUERY(Northwind_Access, 'SELECT * FROM Orders')
OPENROWSETis very similar to theOPENQUERYfunction:
Trang 10It is designed for connecting to a server that is not registered
as a linked server Therefore, the developer must supply both theconnection parameters and the query to use it There are severaloptions for defining the connection, such as OLE DB, ODBC, andOLE DB for ODBC, along with two options for specifying a resultset:
a pass-through query or a valid name for a database object
The following query joins one table from the remote SQL Serverwith two tables on the local SQL Server:
SELECT a.au_lname, a.au_fname, titles.title
FROM OPENROWSET('MSDASQL', 'DRIVER={SQLServer};SERVER=Toronto;UID=sa;PWD=pwd', pubs.dbo.authors) AS a
INNER JOIN titleauthor
ON a.au_id = titleauthor.au_id INNER JOIN titles
ON titleauthor.title_id = titles.title_id
TIP: Although this code will work fine, if you plan repetitive use of some
data source, you should consider registering it as a linked server In thisway, you can join data residing on different servers and different databases.Depending on the features of the OLE DB provider, you can also usethis function to delete, update, or insert information on other servers
SUMMARY
We have described a large number, perhaps an overwhelmingnumber, of SQL Server functions If you think there are just too manyfunctions defined in Transact-SQL, or that you will never rememberthem all, don’t worry We described all of these functions to give you
an idea of the possibilities It is first of all important to have a sense ofwhat is achievable and what is not, and then you can easily consult
Trang 11documentation and work out the details As with many other human
pursuits, knowing something is often not as important as knowing
where to find out about something
A more frequent problem is that the function that you need does
not exist in Transact-SQL Sometimes you will be able to find a
system stored procedure or extended stored procedure with the
functionality you require
3 Create a table to store contact information The last columnshould contain a binary checksum value so that later you cansee if the record has changed
Trang 13CHAPTER 6
Composite Transact-SQL Constructs—Batches,
Scripts, and Transactions
223
Terms of Use
Trang 14Transact-SQL statements can be grouped and executed together
in a variety of ways They can be
▼ Recompiled as a part of a stored procedure, user-definedfunction, or trigger
■ Written and executed individually or in groups from clientutilities in the form of batches
■ Grouped and stored in external script files that can be openedand executed from various client utilities
▲ Grouped in transactions that succeed completely or failcompletely
After completing this chapter you will understand
▼ The concept of a batch
■ How to set a batch explicitly
■ How a batch functions when errors are present
■ The effects of deferred name resolution on batch execution
■ Which Transact-SQL statement has to be alone in a batch
■ How to use variables, comments, and database objects in
a batch
■ What a script is
■ How to generate scripts to generate database objects
■ What a transaction is
■ What types of transactions MS SQL Server supports
■ How to set transactions explicitly
■ How to create nested transactions
■ Restrictions on use
▲ Common mistakes and how to avoid them
It is not necessary to run examples from the text against the Assetdatabase, but if you do, you must first make sure that the databasecontains the following table:
Trang 15Create Table Part(PartId int identity,
Make varchar(50),
Model varchar(50), Type varchar(50))
We will use this table to demonstrate the many features of batches
Some of the changes are destructive, so we will not use existing tables
such as Equipment, which we may need for other purposes later Just
run the statement against the database using Query Analyzer
BATCHES
A batch is a set of Transact-SQL statements that are sent to and
executed by SQL Server simultaneously The most important
characteristic of a batch is that it is parsed and executed on the server
as an undivided entity In some cases, batches are set implicitly For
example, if you decide to execute a set of Transact-SQL statements
from Query Analyzer, the program will treat that set as one batch
and do so invisibly:
Insert Into Part (Make, Model, Type)
Values ('Toshiba', 'Portege 7010CT', 'notebook')
Insert Into Part (Make, Model, Type)
Values ('Toshiba', 'Portege 7020CT', 'notebook')
Insert Into Part (Make, Model, Type)
Values ('Toshiba', 'Portege 7030CT', 'notebook')
Some tools, such as Query Analyzer, osql, and isql, use theGo
command to divide Transact-SQL code into explicitly set batches In
the following example, the code for dropping a stored procedure is
in one batch and the code for creating a new stored procedure is in
another The batch is explicitly created using theGocommand:
If Exists (Select * From sysobjects
Where id = object_id(N'[dbo].[prPartList]') And OBJECTPROPERTY(id, N'IsProcedure') = 1) Drop Procedure [dbo].[prPartList]
Trang 16In other utilities and development environments, batches may
be divided in some other manner In ADO, OLEDB, ODBC, andDB-Library, each command string prepared for execution (in therespective object or function) is treated as one batch
Figure 6-1. Executing selected code in Query Analyzer
Trang 17Using Batches
Batches reduce the time and processing associated with transferring
statements from client to server, as well as that associated with parsing,
compiling, and executing Transact-SQL statements If a developer decides
to execute a set of 100 insert commands against a database, it is preferable
to group them in one batch rather than send them to the server as 100
separate statements The overhead involved in sending 100 separate
statements and receiving 100 separate results is very high Network traffic
will be increased unnecessarily, and the whole operation will be slower
for the user
Batches and Errors
The fact that the batch is compiled as an undivided entity has
interesting implications for syntax errors Results will vary according
to whether the syntax error occurs in a statement or in the name of a
database object If a DBA writes a batch with a statement that
contains a syntax error, the whole batch will fail to execute
Consider the following batch:
Insert into Part (Make, Model, Type)
Values ('Toshiba', 'Portégé 7020CT', 'Notebook')
Selec * from Part
It consists of two commands The second contains a syntax error—
a missing letter in theSelectkeyword If you execute this batch
in Query Analyzer, SQL Server will not compile or execute but will
return the following error:
Server: Msg 170, Level 15, State 1, Line 3
Line 3: Incorrect syntax near 'Selec'
If you make a typo in the name of the database object (for
instance, in a table or column name), the situation is very different
Note that the name of the table in the followingInsertstatement
is incorrect:
Insert into art (Make, Model, Type)
Values ('Toshiba', 'Portege 7020CT', 'Notebook')
Select * from Part
Trang 18In this example, the application will notice an error and stopexecution as soon as it encounters it:
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'art'.
SQL Server executes the batch in three steps: it parses, compiles,then executes In the first phase, SQL Server verifies batch syntax Itfocuses on the sequence of keywords, operators, and identifiers Thefirst batch used a statement with a typo in a keyword SQL Serverpicked up the error during the parsing phase
The error in the second batch (an invalid object name) was picked
up during execution To further demonstrate this fact, let’s investigatethe following example, where the error is in the second statement:Insert into Part (Make, Model, Type)
Values ('Toshiba', 'Portege 7020CT', 'Notebook')
Select * from art
In this case, the application behaves differently:
Microsoft SQL Server versions 2000 and 7.0 have a feature called
deferred name resolution It allows the server to compile Transact-SQL
statements even when underlying objects do not yet exist in thedatabase This feature can prove to be very useful when you aretransferring objects from one database or server to another You donot have to worry about dependencies and the order in which objectsare created Unfortunately, the introduction of this feature also hassome strange secondary effects In the case of the last example:
Trang 19▼ The server has successfully compiled a batch, since the name
resolution is not part of the compilation
■ The first command was executed without a problem
▲ When a problem was encountered in the second command,
the server canceled all further processing and returned a
runtime error
Keep this problem in mind when writing batches Developers
in modern programming languages like Visual Basic or Visual C++
usually employ sophisticated error-handling strategies to avoid
situations like this Transact-SQL also contains programming
constructs for error handling We will explore them in the next
chapter
The situation could be worse Particular runtime errors (for
example, constraint violations) do not stop execution of the batch
In the following case, we attempt to use anInsertstatement to
insert a value in the identity column
NOTE: Identity columns are a feature used by SQL Server to generate
unique, sequential numbers for each record inserted in a table It is
equivalent to the AutoNumber datatype in Microsoft Access Naturally,
you should not attempt to specify values in such columns
Select PartId, Make + ' ' + Model Part from Part
Insert into Part (PartId, Make, Model, Type)
Values (1, 'IBM', 'Thinkpad 390D', 'Notebook')
Select PartId, Make + ' ' + Model Part from Part
Trang 20Server: Msg 544, Level 16, State 1, Line 1 Cannot insert explicit value for identity column in table 'Part' when IDENTITY_INSERT is set to OFF.
PartId Part - -
In some cases this may be useful, but in most it may not be whatthe user expects to happen In the following example, a user tries todelete one column from the Part table One way to perform thisaction (very popular until DBAs got spoiled with fancy tools likeEnterprise Manager or theAlter Table … Drop Columnstatement)would be to
▼ Create a temporary table to preserve the information that iscurrently in the Part table
■ Copy information from the Part table to the temporary table
■ Drop the existing Part table
■ Create a Part table without the irrelevant columns
■ Copy the preserved information back to the Part table
▲ Drop the temporary table
A code to implement this functionality could be created in a set offive batches:
Trang 21Create Table TmpPart (PartId int identity,
Make varchar(50), Model varchar(50), Type varchar(50)) Go
Insert into TmpPart (PartId, Make, Model, EqTypeId)
Select PartId, Make, Model, EqTypeId from Part
Insert into Part (PartId, Make, Model)
Select PartId, Make, Model from TmpPart
Go
Drop Table TmpPart
Go
In theory, this set of batches would work perfectly However, there
is just one problem—the developer didn’t take errors into account For
example, if a syntax error occurs in the first batch, a temporary table
will not be created, Part information will not be preserved in it, and
when the code drops the table, the information will be lost To observe
a method that experienced developers use to handle errors, read the
next chapter
DDL Batches
Data Definition Language (DDL) is that part of Transact-SQL
dedicated to the creation of database objects For internal reasons,
Trang 22some DDL statements must stand alone in the batch, including thefollowing statements:
Scope of Objects Some DDL statements can be inside batchestogether with other commands, but keep in mind that the resultingobject will not be accessible until the batch is completed Forexample, it is not possible to add new columns to the table and toaccess those new columns in the same batch Therefore, the followingbatch will fail:
Alter Table Part ADD Cost money NULL select PartId, Cost from Part
Trang 23Alter Table Part ADD Cost money NULL
Exec ('ALTER TABLE Part ADD Cost money NULL')
Select PartId, Cost from Part
Go
Scope of Variables All (local) variables referenced in a batch must
also be declared in that batch The following code will result in the
failure of the second batch:
Declare @Name as varchar (50)
Go
Select @Name = 'Dejan'
Go
Scope of Comments Comments must be started and finished within
the same batch Ignoring this requirement will result in some very
interesting outcomes, becauseGocommands are preprocessed on the
client side, before the code is sent to the server Take a look at the
comment in the following sample:
Select * From Part
Set Type = 'Notebook'
Where Type = 'Laptop'
Go
Trang 24Select * from Part Go
Update Part Set Type = 'desktop' Where Type = 'computer' Go
PartId Make Model Type - - - -
1 Toshiba Portege 7020CT Laptop (1 row(s) affected)
Server: Msg 113, Level 15, State 1, Line 2 Missing end comment mark '*/'.
Trang 25The first batch is the only batch that behaves in accordance with
the administrator’s intention The second batch fails because the
comments are not complete:
Update Part
Set Type = 'desktop'
Where Type = 'PC'
/*
The third batch is executed because the server is not aware of the
administrator’s intention to comment it out:
Update Part
Set Type = 'Notebook'
Where Type = 'Laptop'
The fourth batch is also executed, because the server is not aware of
the administrator’s intention to comment it out:
Select * from Part
The fifth batch is also executed:
Update Part
Set Type = 'desktop'
Where Type = 'computer'
The last batch fails:
*/
Select * from Part
TIP: Comments must be started and finished within the same batch.
If the administrator wants to comment out theGocommand, he
must use two dashes as a comment marker at the beginning of the row:
Go
Trang 26A script is usually defined as a collection of Transact-SQL statements
(in one or more batches) in the form of an external file Client tools,such as Query Analyzer, isql, osql, and Enterprise Manager, usuallyhave support for managing script files
Scripts are usually stored in plain text files with a sql extension.This makes them manageable from any text editor as well as frommany sophisticated tools, such as the Microsoft application for codecontrol, Visual SourceSafe
Query Analyzer has the usual features (File | Open, Save) of anytext editor isql and osql are command line utilities that allow theuser to specify script files with code to be executed against the server
Database Scripting
One of the most exciting features in Enterprise Manager for bothjunior and senior administrators is the ability to perform reverseengineering on the database The result of this process is a scriptwith DDL statements, which can be used to re-create all databaseobjects This script can be used to
▼ Explore user and system database objects
■ Back up source code
■ Establish a source control process
▲ Transfer the complete database (or just some objects) toanother server (and/or another database)
The process of database scripting is very simple The user selects
a database in Enterprise Manager and runs Tools | Generate SQLScript The program prompts the user to specify the objects to bescripted:
Trang 27On the Formatting tab, the user can decide in which format each
database object is to be generated A small preview template helps
users make the right choice among several options:
The Options tab allows the user to specify options for supporting
objects such as indexes, triggers, constraints, logins, users, roles, and
permissions The ability to specify a character set is very important
for multilanguage environments
Trang 28TIP: If you want to be able to open a script file from regular editors (that
do not support Unicode) such as Notepad, you should select Windows Text(ANSI) as your file format
The reason you are generating script and the use that you haveplanned for it will influence the decision to generate a single file (forexample, when you want to transfer the object) or one file per object(for example, when you want to use scripts to establish source codecontrol)
TIP: Use database scripting to explore the sample databases delivered with
this book and the sample and system databases published with SQL Server.Exploration of other styles and methods in coding will help you to gainknowledge and build experience
THE TRANSACTION CONCEPT
Even from the very name of the Transact-SQL language, you can
conclude that transactions play a major role in SQL Server They are
an important mechanism for enforcing the consistency and integrity
of the database
Trang 29Transactions are the smallest units of work in SQL Server To
qualify a unit of work as a transaction, it must satisfy the four criteria
often referred to as the ACID test (Atomicity, Consistency, Isolation,
Durability):
▼ Atomicity All data changes must be completed successfully,
or none of them will be written permanently to the database
■ Consistency After a transaction, the database must be left in
a consistent state All rules must be applied during processing
to ensure data integrity All constraints must be satisfied Allinternal data structures must be left in an acceptable state
■ Isolation Changes to the database made by a transaction
must not be visible to other transactions until the transaction
is complete Before the transaction is committed, othertransactions should see the data only in the state it was inbefore the transaction
▲ Durability Once a transaction is completed, changes must
not revert even in the case of a system failure
Autocommit Transactions
In fact, every Transact-SQL statement is a transaction When it is
executed, it either finishes successfully or is completely abandoned
To illustrate this, let’s try to delete all records from EqType table
Take a look at the following diagram:
Trang 30A foreign key relationship exists between the EqType andEquipment tables The foreign key will prevent the deletion ofrecords in the EqType table that are referenced by records in theEquipment table.
Let’s try to delete them anyway You can see the result of such anattempt in Figure 6-2
TwoSelectstatements that will count the number of records inEqType are placed around theDeletestatement As expected, theDeletestatement is aborted because of the foreign key The count
of records before and after theDeletestatement is the same, whichconfirms that all changes made by theDeletestatement werecanceled So the database remains in the state that it was in beforethe change was initiated
If there were no errors, SQL Server would automatically committhe transaction (that is, it would record all changes) to the database
This kind of behavior is called autocommit.
Figure 6-2. Complete failure of attempt to delete records
Trang 31In this case, SQL Server deleted records one after the other from
the EqType table until it encountered a record that could not be
deleted because of the foreign key relationship, at which point the
operation was canceled
Explicit Transactions
The most popular and obvious way to use transactions is to give
explicit commands to start or finish the transaction Transactions
started in this way are called explicit transactions Developers can
group two or more Transact-SQL statements into a single transaction
using the following statements:
▼ Begin Transaction
■ Rollback Transaction
▲ Commit Transaction
If anything goes wrong with any of the grouped statements, all
changes need to be aborted The process of reversing changes is
called rollback in SQL Server terminology If everything is in order
with all statements within a single transaction, all changes are
recorded together in the database In SQL Server terminology, we
say that these changes are committed to the database.
We will demonstrate the use of these processes on the
prClearLeaseSchedule stored procedure Its main purpose is to set
monthly lease amounts to zero for each asset associated with an
expired lease schedule It also sets the total of the lease amounts to
zero These two suboperations must be performed simultaneously
to preserve the integrity of the database
Create Procedure prClearLeaseShedule
Set value of Lease of all equipment
associated with expired Lease Schedule to 0.
Set total amount of Lease Schedule to 0.
@intLeaseScheduleId int As
Trang 32Begin Transaction
Set value of Lease of all equipment associated with expired Lease Schedule to 0 Update Inventory
Set Lease = 0 Where LeaseScheduleId = @intLeaseScheduleId
If @@Error <> 0 goto PROBLEM
Set total amount of Lease Schedule to 0 Update LeaseSchedule
Set PeriodicTotalAmount = 0 Where ScheduleId = @intLeaseScheduleId
If @@Error <> 0 goto PROBLEM
Trang 33Implicit Transactions
The third transaction mode is called the implicit transaction To use this
mode, you set a connection using theSet Implicit_Transactions
Onstatement Any of the following statements will serve as an implicit
To finish the transaction, a developer must use theCommit
TransactionorRollback Transactionstatement After that,
any of the specified commands will start another transaction
Transaction Processing Architecture
An explanation of how transactions are implemented in Microsoft
SQL Server will give you some insight into many processes
Every change to the database is recorded in a transaction log
before it is written to the appropriate tables In SQL Server 2000 and
SQL Server 7.0, transaction logs are implemented in separate files (or
a set of files) with the extension ldf All modifications are written to
this file chronologically The records in this transaction log can later
be used to roll back the transaction (thus providing Atomicity), or to
Trang 34commit the changes to the database (thus providing Durability) Twotypes of records can be stored in transaction logs:
▼ Logical operations performed (for instance, insert, delete, start
of transaction)
▲ Before and after images of the changed data (that is, copies ofdata before and after the change is made)
The transaction log mechanism helps to resolve many issues:
▼ If a client application loses its connection before a transaction
is finished, SQL Server will detect a problem and roll backchanges (thus providing Consistency)
▲ If the machine loses power during processing, SQL Serverwill recover the database when services are restored Alltransactions that were recorded in the transaction log in anundivided manner (that is, as part of a complete transactionset) are rolled forward (written to data tables) as if nothingunusual has happened (Durability) All transactions that werenot completed before the problem occurred are rolled back(deleted) from the database
The transaction log plays an important role in the implementation
of backups in SQL Server When a user starts a full backup, SQL Server
records a complete snapshot of the data tables in backup files At thatpoint, SQL Server marks the current position in the transaction log andcontinues to record all changes to the database in the transaction log.Transactions logged during the process are also recorded as part of thefull backup When the backup is complete, SQL Server makes another
mark in the transaction log At the time of the next backup, a transaction log backup will suffice To restore the database, an administrator first
uses the full backup and then one or more transaction log backups thathave been run since the full backup SQL Server runs through thetransaction log and applies changes to the data tables
Trang 35Nested Transactions
SQL Server allows you to nest transactions Basically, this feature
means that a new transaction can start even though the previous one
Usually this situation occurs when one stored procedure containing
a transaction calls another stored procedure that also contains a
transaction In the following example, prCompleteOrder completes
an order by setting its completion date and changing the status of the
order, and then looping through associated order items and calling
prCompleteOrderItem to complete each of them; prCompleteOrderItem
sets the completion date of an order item to the last ChargeLog date
associated with that OrderItem Both of these procedures contain a
transaction:
Alter Procedure prCompleteOrder_1
complete all orderItems and then complete order
Trang 36Select @intErrorCode = @@Error End
loop through OrderItems and complete them
If @intErrorCode = 0
Begin
Create Table #OrderItems(
id int identity(1,1), OrderItemId int)
Select @intErrorCode = @@Error End
Trang 37Alter Procedure prCompleteOrderItem_1
Set CompletionDate of OrderItem to date
Trang 38of last ChargeLog record associated with OrderItem.
@intOrderItemId int As
set nocount on
Declare @intErrorCode int
Select @intErrorCode = @@Error
If @intErrorCode = 0
Begin Transaction
Set CompletionDate of OrderItem to date
of last ChargeLog record associated with OrderItem.
If @intErrorCode = 0
Begin
update OrderItem Set CompletionDate = (Select Max(ChargeDate)
from ChargeLog where ItemId = @intOrderItemId) Where ItemId = @intOrderItemId
Select @intErrorCode = @@Error End
If @intErrorCode = 0 and @@trancount > 0
The interesting question is how SQL Server knows whichtransaction is the last one It keeps the number of opened transactions