Tải bản đầy đủ (.pdf) (76 trang)

SQL Server 2000 Stored Procedure Programming phần 4 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (569.13 KB, 76 trang )

Function Description
@@@PROCID
Returns the identification
number of the current
stored 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:
Function Description


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 a
member of the specified
server role.
Chapter 5: Functions
211
Function 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 name
for the user’s security
identification number.
USER_ID([
user
])
Returns the database
user’s identification
number.
USER
Returns the database user
name.
Text and Image Functions
SQL Server does not have an elaborate set of text and image
functions, since you should generally not keep your documents or
pictures inside the database. The proper place for these files is in the
file system. You should keep only descriptions of and pointers (that
is, the path) to those files in the database itself.
Function Description
PATINDEX(%

pattern
%,
expression
)
Returns the starting position
of the first occurrence of the
pattern.
TEXTPTR(
column
)
Returns the text pointer
value.
TEXTVALID(
column
,
text_pointer
)
Validates the given text
pointer.
212
SQL Server 2000 Stored Procedure Programming
Chapter 5: Functions
213
Cursor Functions
These functions are designed to return status information about
cursors and cursor operations.
Function Description
@@@CURSOR_ROWS
Returns the number of
rows that are in the last

cursor opened in the
connection.
CURSOR_STATUS({‘local’,
‘cursor_name
’}
CURSOR_STATUS {‘global’,

cursor_name
’}
CURSOR_STATUS {‘variable’,

cursor_variable
’})
Determines whether a
procedure returned a
cursor and result set for
the given parameter.
@@@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:
Function
Description
@@@CONNECTIONS
Returns the number of connections
since SQL Server was started.
@@@DATEFIRST
Returns the value of the SET

DATEFIRST parameter that indicates
the specified first day of each week.
@@@DBTS
Returns the value of the timestamp
datatype.
@@@LANGUAGE
Returns the name of the language that
is currently in use by SQL Server.
Function
Description
@@@LANGID
Returns the language ID for the
language that is currently in use by
SQL Server.
@@@LOCK_TIMEOUT
Returns the lock time-out setting
(milliseconds).
@@@MAX_CONNECTIONS
Returns the maximum number of
simultaneous connections allowed on
SQL Server.
@@@MAX_PRECISION
Returns the level of precision used by
decimal and numeric datatypes on the
server.
@@@OPTIONS
Returns information about current SET
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
TEXTSIZE option specified by the SET
statement (maximum length in bytes
of text and image data in the Select
statement).
@@@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 and
SQL Server 2000 have a limit of 32 stored procedure nesting levels.
Earlier versions could nest up to 16 stored procedures.
214
SQL Server 2000 Stored Procedure Programming
The @@NESTLEVEL global 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 be
called
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:
Function Description
@@@CPU_BUSY
Returns the time the CPU spent
performing a task since SQL Server was
last started. Time is in milliseconds.
@@@IDLE
Returns the time (in milliseconds) that
SQL Server has been idle since it was
started.
@@@IO_BUSY
Returns the time (in milliseconds) that
SQL Server spent performing input and
output 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.
Chapter 5: Functions
215
Function 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 a
single value. Their use is relatively limited. They can be used in the
following situations:
▼ The selection list of the Select statement

A Having clause

A Compute clause
Function Description

AVG( [ALL | DISTINCT]
expression
)
Returns the average value in the
group.
COUNT( [ALL | DISTINCT]
expression
|*)
Counts the number of items in the
group.
COUNT_BIG( [ALL | DISTINCT]
expression
|*)
Counts the number of items in the
group. The result is returned in
the form of a bigint number.
This function is available only in
SQL Server 2000.
216
SQL Server 2000 Stored Procedure Programming
Chapter 5: Functions
217
Function Description
GROUPING(
Column_Name
)
Creates an additional column
with a value of 1 when a row is
added by the CUBE or ROLLUP
operator or 0 if it is not the result

of a CUBE or ROLLUP operator.
MAX(
expression
)
Returns the maximum value in
the expression.
MIN (
expression
)
Returns the minimum value in
the expression.
SUM(
expression
)
Returns the sum of the
expression’s values.
STDEV(
expression
)
Returns the statistical standard
deviation for the values in the
expression.
STDEVP(
expression
)
Returns the statistical standard
deviation for the population for
the 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 in
the expression.
Except for the COUNT function, 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

218
SQL Server 2000 Stored Procedure Programming
200.0000
(1 row(s) affected)
Warning: Null value eliminated from aggregate.
You apply COUNT on a specific field:
select COUNT(Rent) [Rentals] from Inventory
SQL Server will count only records that do not have null in the
Rent field:
Rentals

241
(1 row(s) affected)
Warning: Null value eliminated from aggregate.
You can apply COUNT on 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 complete
recordset to the caller. They cannot be used (as scalar functions) in
any place where an expression is acceptable. They can be used in
Transact-SQL statements only in situations where the server expects
a table reference. An example of such a situation is the From clause of
the Select statement. These functions were introduced in Microsoft
SQL Server 7.0.
The OPENQUERY function is designed to return a recordset from a
linked server. It can be used as a part of Select, Update, Insert,
and Delete Transact-SQL statements. The Query parameter 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 the OPENQUERY function to return records from
the linked server:
SELECT *
FROM OPENQUERY(Northwind_Access, 'SELECT * FROM Orders')
OPENROWSET is very similar to the OPENQUERY function:
OPENROWSET(
'provider_name',
{'datasource';'user_id';'password' | 'provider_string' },
{ [catalog.][schema.]object | 'query'}
)
Chapter 5: Functions
219
220
SQL Server 2000 Stored Procedure Programming
It is designed for connecting to a server that is not registered
as a linked server. Therefore, the developer must supply both the
connection parameters and the query to use it. There are several
options for defining the connection, such as OLE DB, ODBC, and
OLE 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 Server
with 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 this
way, you can join data residing on different servers and different databases.
Depending on the features of the OLE DB provider, you can also use
this function to delete, update, or insert information on other servers.
SUMMARY
We have described a large number, perhaps an overwhelming
number, of SQL Server functions. If you think there are just too many
functions defined in Transact-SQL, or that you will never remember
them 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 of
what is achievable and what is not, and then you can easily consult
documentation 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.
EXERCISES
1. Create a Select statement that returns the quarter from the

current date in the following format: ‘3Q2000’.
2. Create a table called ExpectedShippingDate that contains the
following fields:

ExpectedShippingDateId (offset from the starting date)
■ ExpectedShippingDate
■ ExpectedShippingDateOfMonth
■ ExpectedShippingMonth

ExpectedShippingYear

ExpectedShippingQuarter
The table should be filled with one record for each
date since 1/1/2000. Create a stored procedure
Setup_ExpectedShippingDate to fill it.
3. Create a table to store contact information. The last column
should contain a binary checksum value so that later you can
see if the record has changed.
Chapter 5: Functions
221
CHAPTER
6
Composite
Transact-SQL
Constructs—Batches,
Scripts, and
Transactions
223
Terms of Use

224
SQL Server 2000 Stored Procedure Programming
T
ransact-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-defined
function, or trigger

Written and executed individually or in groups from client
utilities in the form of batches

Grouped and stored in external script files that can be opened
and executed from various client utilities

Grouped in transactions that succeed completely or fail
completely
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 Asset
database, but if you do, you must first make sure that the database
contains the following table:
Create 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 the Go
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 the Go command:
If Exists (Select * From sysobjects
Where id = object_id(N'[dbo].[prPartList]')
And OBJECTPROPERTY(id, N'IsProcedure') = 1)
Drop Procedure [dbo].[prPartList]
Chapter 6: Composite Transact-SQL Constructs—Batches, Scripts, and Transactions
225
Go
Create Procedure prPartList
As
Select * from Part
Return 0
Go
In Query Analyzer, you can highlight (that is, select with the
mouse) part of the code and execute it. Query Analyzer treats the
selected piece of code as a batch and sends it to the server. It ignores
the rest of the code (see Figure 6-1).
In other utilities and development environments, batches may

be divided in some other manner. In ADO, OLEDB, ODBC, and
DB-Library, each command string prepared for execution (in the
respective object or function) is treated as one batch.
226
SQL Server 2000 Stored Procedure Programming
Figure 6-1. Executing selected code in Query Analyzer
Chapter 6: Composite Transact-SQL Constructs—Batches, Scripts, and Transactions
227
Using 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 the Select keyword. 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 following Insert statement
is incorrect:
Insert into art (Make, Model, Type)
Values ('Toshiba', 'Portege 7020CT', 'Notebook')
Select * from Part
228
SQL Server 2000 Stored Procedure Programming
In this example, the application will notice an error and stop
execution 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. It
focuses on the sequence of keywords, operators, and identifiers. The
first batch used a statement with a typo in a keyword. SQL Server
picked 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 investigate
the 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:
(1 row(s) affected)

Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'art'.
Both commands are parsed and compiled, then the first command is
executed, and finally the second command is canceled. Users with
experience on earlier versions of Microsoft SQL Server will remember
that such a scenario would produce very different results in those
earlier versions.
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 the
database. This feature can prove to be very useful when you are
transferring objects from one database or server to another. You do
not have to worry about dependencies and the order in which objects
are created. Unfortunately, the introduction of this feature also has
some strange secondary effects. In the case of the last example:
Chapter 6: Composite Transact-SQL Constructs—Batches, Scripts, and Transactions
229

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 an Insert statement 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
Go
The result is a “partial failure”:
PartId Part

1 Toshiba Portege 7020CT
(1 row(s) affected)
Server: 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

1 Toshiba Portege 7020CT
(1 row(s) affected)
In some cases “partial success” may be tolerable, but in the real
world it is generally not acceptable.

Let’s investigate a case in which several batches are written,
divided by a Go statement, and executed together. Although the user
has issued a single command to execute them, the client application
will divide the code into batches and send them to the server
separately. If an error occurs in any batch, the server will cancel its
execution. However, this does not mean that execution of the other
batches is canceled. The server will try to execute the next batch
automatically.
In some cases this may be useful, but in most it may not be what
the user expects to happen. In the following example, a user tries to
delete one column from the Part table. One way to perform this
action (very popular until DBAs got spoiled with fancy tools like
Enterprise Manager or the Alter Table … Drop Column statement)
would be to

Create a temporary table to preserve the information that is
currently 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 of
five batches:
230

SQL Server 2000 Stored Procedure Programming
Create 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
Go
Drop Table Part
Go
Create Table Part (PartId int identity,
Make varchar(50),
Model varchar(50))
Go
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,

Chapter 6: Composite Transact-SQL Constructs—Batches, Scripts, and Transactions
231
232
SQL Server 2000 Stored Procedure Programming
some DDL statements must stand alone in the batch, including the
following statements:

Create Procedure

Create Trigger

Create Default

Create Rule

Create View

Set Showplan_Text

Set Showplan_All
If these statements are combined with other statements in a batch, the
batch will fail.
Self-Sufficient Content
During compilation, the batch is converted into a single execution
plan. For this reason, the batch must be self-sufficient. In the real
world, this concept has vast implications for the scope of database
objects, variables, and comments.
Scope of Objects
Some DDL statements can be inside batches
together with other commands, but keep in mind that the resulting

object will not be accessible until the batch is completed. For
example, it is not possible to add new columns to the table and to
access those new columns in the same batch. Therefore, the following
batch will fail:
Alter Table Part ADD Cost money NULL
select PartId, Cost from Part
Go
The Select statement is not able to access the Cost column, and the
whole batch will fail:
Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'Cost'.
Therefore, the batch has to be divided in two:
Alter Table Part ADD Cost money NULL
Go
Select PartId, Cost from Part
Go
However, a workaround with the Execute statement will not work
either:
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, because Go commands 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
Go
Update Part
Set Type = 'desktop'
Where Type = 'PC'
/*
Go
Update Part
Set Type = 'Notebook'
Where Type = 'Laptop'
Go
Chapter 6: Composite Transact-SQL Constructs—Batches, Scripts, and Transactions
233
234
SQL Server 2000 Stored Procedure Programming
Select * from Part
Go
Update Part
Set Type = 'desktop'
Where Type = 'computer'
Go
*/
Select * from Part
Go
To developers of other programming languages, this might look

perfectly legal. Query Analyzer will even change the color of the code
that is commented out. Unfortunately, this code is a complete disaster.
Due to errors, the server will cancel execution of parts that the user
expects to run and execute other parts that are commented out:
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 '*/'.
(1 row(s) affected)
PartId Make Model Type

1 Toshiba Portege 7020CT Notebook
(1 row(s) affected)
Server: Msg 170, Level 15, State 1, Line 4
Line 4: Incorrect syntax near '/'.
Query Analyzer will ignore the comments and send everything
between the Go commands as separate batches.
Chapter 6: Composite Transact-SQL Constructs—Batches, Scripts, and Transactions
235
The 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 the Go command, he
must use two dashes as a comment marker at the beginning of the row:
Go

×