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

Microsoft SQL Server 2000 Programming by Example phần 2 pdf

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 (1012.82 KB, 71 trang )

Microsoft SQL Server 2000 Programming by Example

56


The command(s) completed successfully.
The UNIQUEIDENTIFIER data type has an associated system function, NEWID, that generates new values
for these data types. Therefore, if you use the UNIQUEIDENTIFIER data type in a table, you can use the
NEWID system function as the column's default value, as Listing 2.15 shows.
Listing 2.15 Using the NEWID System Function


USE Northwind

CREATE TABLE Bigidentifiers
(
col1 UNIQUEIDENTIFIER DEFAULT NEWID()
)
GO


The command(s) completed successfully.
The new SQL_VARIANT data type can store up to 8,016 bytes of almost any base data type. Listing 2.16
shows how to use the SQL_VARIANT with character and integer data.
Listing 2.16 Using the SQL_VARIANT Data Type


USE Northwind

DECLARE @integer_data SQL_VARIANT, @char_data SQL_VARIANT
Chapter 2. Elements of Transact-SQL


57
SET @integer_data = 845
SET @char_data = 'This is character data'
GO


The command(s) completed successfully.
The TIMESTAMP data type is not related at all to DATETIME or SMALLDATETIME. Moreover, you cannot
directly update a TIMESTAMP column because it updates itself when you insert or update a row that contains
a TIMESTAMP. Also, there can be only one TIMESTAMP column per table.
Creating Customized Data Types: User-Defined Data Types
Users can create their own data types using the data types provided by Transact-SQL as the base types. To
create user-defined data types, or UDDT, use the sp_addtype system stored procedure, and to drop them,
use sp_droptype. The basic syntax of the sp_addtype system stored procedure is

sp_addtype uddt_name, uddt_base_type, nullability
For example, suppose that you want to create a UDDT to store phone numbers that could be null. You can
define this user-defined data type using the CHAR data type as the base type with a length of 12, as shown in
Listing 2.17.
Listing 2.17 Creating User-Defined Data Types (UDDTs)


USE Northwind

EXEC sp_addtype phone_number,'CHAR(12)',NULL
GO


1 row(s) affected)


Type added.
Information about user-defined data types is stored in the systypes system table, which is located in all
databases. When created, the properties of user-defined data types can be displayed using the sp_help
Microsoft SQL Server 2000 Programming by Example

58
system stored procedure, which receives an object name as a parameter, which, in this case, would be the
name of the user-defined data type, as shown in Listing 2.18.
Listing 2.18 Using sp_help to Display UDDT's Properties


USE Northwind

EXEC sp_help phone_number
GO


Type_name Storage_type Length Prec Scale Nullable Default_name Rule_name

phone_number char 12 12 NULL yes none none
Tip
UDDTs are stored in the database where they are created. However, if you want all your user
databases to have a set of predefined, user-defined data types when they're created, create these
UDDT in the model database. This is because every new database that is created in SQL Server is
a copy of the model database.

Listing 2.19 creates a UDDT called ssn in Model. This UDDT will be automatically transferred to every user
database that is created afterward.
Listing 2.19 Creating UDDTs in Model



USE Model

EXEC sp_addtype ssn,'CHAR(11)','NOT NULL'
Chapter 2. Elements of Transact-SQL
59
GO


1 row(s) affected)

Type added.
UDDTs can be created also in Enterprise Manager. To accomplish this, right-click User Defined Data Types
(which is located inside the database folder) and then choose New User-Defined Data Type, which opens the
window shown in Figure 2.1.
Figure 2.1. Creating UDDTs in Enterprise Manager.

Data Type Selection Criteria
You should be very careful when choosing data types. Always make sure that the data type you're choosing is
the correct one and the length is appropriate, because it is very common to choose data types that are
oversized. For example, let's say that you choose VARCHAR(100) as the data type and length for a ZIP code
column. Although VARCHAR(100) is able to store this kind of data, you will waste a lot of space because ZIP
codes have only five characters. In a small table, this isn't a problem, but in big tables this can lead to
performance problems.
The same rule applies for integer data. Take a look at the maximum and minimum value of each integer data
type when choosing among them. This way, you avoid using a big data type when you could have used a
smaller one. For example, a very efficient way to store IP addresses in a table is to use four TINYINT
columns, because this data type can store integers from 0 to 255.
If the length is not specified when declaring character (CHAR, NCHAR, VARCHAR, and NVARCHAR) or binary
(BINARY and VARBINARY) data, SQL Server uses 1 as the length by default. Listing 2.20 shows the

Microsoft SQL Server 2000 Programming by Example

60
declaration of a variable in which you will be able to store just one character because the length was not
specified. Notice that although you don't get an error if you assign more than one character to the variable,
SQL Server stores only the first character.
Listing 2.20 Using the Default Length with Character Data


USE Northwind

DECLARE @onecharacter VARCHAR
SET @onecharacter = 'String'
SELECT @onecharacter
GO

S


(1 row(s) affected)
Be aware that fixed-length data types always use the length you defined. On the other hand, variable-length
data types use only the actual space that is being used by the value. For example, look at the table shown in
Listing 2.21. If you insert a row and the length of the lastname is 5, SQL Server will use just 5 bytes for the
storage of this value because the data type is VARCHAR. On the other hand, if the length of the firstname is
5, SQL Server has to use 20 bytes to store this value because the data type is CHAR. Therefore, when using
the CHAR data type, even if the length of the value is less than the length of the column, SQL Server uses the
length of the whole column to store this value.
Listing 2.21 Using Variable- and Fixed-Length Character Data



USE Northwind

CREATE TABLE Authors
(
lastname VARCHAR(20),
firstname CHAR(20)
)
GO
Chapter 2. Elements of Transact-SQL
61


The command(s) completed successfully.
If you want to store data that can hold more than 8,000 bytes, use the TEXT, NTEXT, or IMAGE data types,
which can store up to 2GB. However, make sure that you really need to store more than 8,000 bytes, because
these data types use another set of statements (WRITETEXT, READTEXT, and UPDATETEXT).
Tip
You can use standard DML commands with TEXT, NTEXT, and IMAGE data, but only a portion of
the data can be accessed (using the SUBSTRING function, for example).

Be careful when you use approximate numeric data because, by definition, these data types (FLOAT and
REAL) store an approximation of the number. Therefore, they should not be used to perform exact
comparisons in WHERE clauses.
The TABLE data type cannot be used as a column data type when creating tables; thus, it is not possible to
have tables inside tables. Whenever possible, use the TABLE data type instead of temporary tables because
the first one is stored in memory, improving performance considerably. Usually, the TABLE data type is used
to store temporary result sets, as shown in Listing 2.22, in which a variable is created using the TABLE data
type and then two rows are inserted.
Listing 2.22 Using the TABLE Data Type



USE Northwind

DECLARE @Authors TABLE(lastname VARCHAR(20), firstname VARCHAR(20))
INSERT @Authors VALUES ('Guerrero','Fernando')
INSERT @Authors VALUES ('Rojas','Carlos')
SELECT * FROM @Authors
GO
Microsoft SQL Server 2000 Programming by Example

62


(1 row(s) affected)

(1 row(s) affected)

lastlame firstname

Guerrero Fernando
Rojas Carlos

(2 row(s) affected)
Although TIMESTAMP and ROWVERSION are synonyms, you should use ROWVERSION instead of TIMESTAMP,
because Microsoft could change the functionality of TIMESTAMP in the future to be compliant with the ANSI
SQL-92 standard, which states that the TIMESTAMP data type stores date and time data.
Additional Elements
In addition to DDL, DML, DCL, and data types, Transact-SQL has some additional elements or extensions
that make life easier for programmers and administrators, and also make Transact-SQL a more powerful
language. Be aware that these extensions are not ANSI-SQL standard; therefore, they are not portable. If you

are concerned about portability, you should avoid using any of these extensions.
SQL Server is not the only relational database management system that adds new elements to the standard
language; this is done by the majority of the commercial database systems today. If you want to check that
your code is compliant with the ANSI standard, use the SET FIPS_FLAGGER statement provided by SQL
Server, which receives as a parameter the level of compliance that you want to check: ENTRY,
INTERMEDIATE, or FULL. Listing 2.23 shows how this statement is used to check the compliance of a
query that contains the TOP clause, which is a Transact-SQL extension.
Listing 2.23 Using the SET FIPS_FLAGGER Statement to Check for ANSI Compliance


USE Northwind

SET FIPS_FLAGGER 'FULL'

SELECT TOP 3 lastname
FROM Employees
ORDER BY hiredate

GO
Chapter 2. Elements of Transact-SQL
63


FIPS Warning: Line 1 has the non-ANSI statement 'USE'.
FIPS Warning: Line 3 has the non-ANSI statement 'SET'.
FIPS Warning: Line 5 has the non-ANSI clause 'TOP'.
lastname

Leverling
Davolio

Fuller
To deactivate the checking of the ANSI compliance (because it remains activated for the session), use the
same statement (SET FIPS_FLAGGER) with the OFF parameter; that is, SET FIPS_FLAGGER OFF.
Variables
In Transact-SQL, local variables are used in stored procedures, user-defined functions, triggers, and user
scripts. Variables are valid in the session that created them; for example, if a stored procedure creates a
variable, it is valid only during the execution of the stored procedure.
Variables are first declared, using the DECLARE statement and specifying the variables'name (which has to
begin with @) and data type. The syntax is

DECLARE @variable_name datatype
Then, a value is set to the variable using either SET or SELECT. When a variable is declared, its value is
initialized to NULL until a value is assigned. Listing 2.24 shows the creation of the @firstname variable,
which uses the VARCHAR data type with a length of 20. Next, its value is set using the SET statement, and
finally, its value is shown using the SELECT statement.
Listing 2.24 Using Variables in Transact-SQL



DECLARE @firstname VARCHAR(20)
SET @firstname = 'Maria'
SELECT @firstname
GO

Microsoft SQL Server 2000 Programming by Example

64


Maria

You can also assign values to variables in a query. Using this approach, make sure that the query returns only
one row because, otherwise, you will get just one value in the variable. For example, Listing 2.25
demonstrates how to assign variables (@ln and @fn) in a query to the Employees table. This query stores
the value of the first and last name of the employee whose ID equals 1 in the @fn and @ln variables. Then, it
shows the value that was assigned to each one of these variables.
Listing 2.25 Assigning Values to Variables in Queries


USE Northwind

DECLARE @ln VARCHAR(20), @fn VARCHAR(20)

SELECT @ln = lastname, @fn = firstname
FROM Employees
WHERE employeeid = 1

SELECT @fn, @ln
GO



Nancy Davolio
System functions that begin with @@ used to be called global variables. In fact, they are system functions that
don't have any parameters, and they are not global variables because you cannot declare and assign a value
to them; they are managed by SQL Server instead. Table 2.3 lists some of these system functions and the
value they return.
Table 2.3. System Functions That Begin with @@
System Function Return Value
@@CONNECTIONS
Number of connections to SQL Server since the service was started.

@@ERROR
Error code of the last statement executed (if it succeeded, it returns 0).
@@IDENTITY
Last identity value inserted in the current session.
@@MAX_CONNECTIONS
Maximum number of connections allowed.
Chapter 2. Elements of Transact-SQL
65
@@OPTIONS
Information about set options in the current session.
@@ROWCOUNT
Number of rows affected by the last statement executed.
@@SERVERNAME
Name of the server where SQL Server is installed.
@@SPID
ID of the current process.
@@VERSION
Current version of SQL Server.
For example, Listing 2.26 shows how to use these system functions, specifically @@servername (the name
of this server is SQLBYEXAMPLE).
Listing 2.26 Using System Functions


SELECT @@servername
GO




SQLBYEXAMPLE

Caution
There are no global variables in SQL Server. The @@ prefix is used just by SQL Server's system
functions. Although you can declare variables using the @@ prefix, they won't behave as global
variables; they will behave just as local ones.

Operators
Operators are used in Transact-SQL to deal with variables, scalars, and, in general, expressions. There are
different kinds of operators, and each kind is used to manipulate different kinds of data types.
The assignment operator is the equal sign (=). It is used to set values to variables, as shown in the preceding
section (see Listings 2.24 and 2.25).
The arithmetic operators are + (addition), – (subtraction), * (multiplication), / (division), and % (modulo or
remainder of division). These operators are used to work with integers, approximate numeric, and exact
numeric. The + and – operators also behave as unary operators (positive and negative), which deal with only
one expression. In Listing 2.27, you can see an example of the use of the division and modulo operators
and the negative unary operator.
Listing 2.27 Using Arithmetic Operators
Microsoft SQL Server 2000 Programming by Example

66


SELECT 8/4
SELECT 9%4
SELECT -7
GO



2



1


-7
The comparison operators are = (equal to), <> (not equal to), < (less than), > (greater than), <= (less than or
equal to), and >= (greater than or equal to). Comparison operators are used to deal with any kind of data
types but TEXT, NTEXT, and IMAGE. Listing 2.28 shows an example that uses the less than or equal to
(<=) operator.
Listing 2.28 Using the Less Than or Equal to Operator


USE Northwind


SELECT employeeid, lastname, firstname
FROM Employees
WHERE employeeid <= 8
GO
Chapter 2. Elements of Transact-SQL
67


employeeid lastname firstname

1 Davolio Nancy
2 Fuller Andrew
3 Leverling Janet
4 Peacock Margaret
5 Buchanan Steven

6 Suyama Michael
7 King Robert
8 Callahan Laura

(8 row(s) affected)
The logical operators are AND, OR, NOT, BETWEEN, IN, and LIKE. These operators check a condition and
evaluate to true or false. AND evaluates to true if all expressions are true. OR evaluates to true if any of the
expressions are true. NOT evaluates to false if the expression is true, and true if the expression is false.
Listing 2.29 shows how to use the AND logical operator in the WHERE clause of a SELECT statement.
Listing 2.29 Using the AND Logical Operator


USE Northwind


SELECT employeeid, lastname, firstname, city
FROM Employees
WHERE firstname='anne'AND city='london'
GO


employeeid lastname firstname city

9 Dodsworth Anne London

(1 row(s) affected)
Microsoft SQL Server 2000 Programming by Example

68
BETWEEN is used to check for an inclusive range (in an inclusive range the limits are included), and its syntax

is

1st_expression BETWEEN 2nd_expression AND 3rd_expression.
The first expression, usually a column, is checked to see whether it falls within the range of the second
expression and the third expression (both included in the range). The syntax of BETWEEN is equivalent to
(using >= and <=):

(1st_expression >= 2nd expression) AND (1st_expression <= 3rd_expression)
Listing 2.30 shows an example of BETWEEN, which gets all the rows in the Employees table whose ID is
between 2 and 5 (including 2 and 5).
Listing 2.30 Checking for Ranges Using the BETWEEN Operator


USE Northwind


SELECT employeeid, firstname, lastname
FROM Employees
WHERE employeeid BETWEEN 2 AND 5
GO


employeeid firstname lastname

2 Andrew Fuller
3 Janet Leverling
4 Margaret Peacock
5 Steven Buchanan

(4 row(s) affected)

The IN operator is, at some level, similar to BETWEEN. Instead of a range, it checks whether the first
expression is contained in a list of expressions. The syntax is the following:

expression IN (expression_1, expression_2, , expression_n)
Listing 2.31 shows an example of IN, which gets all the rows from the Employees table whose ID is 2, 6, or
9.
Listing 2.31 Using the IN Logical Operator
Chapter 2. Elements of Transact-SQL
69


USE Northwind


SELECT employeeid, firstname, lastname
FROM Employees
WHERE employeeid IN (2,6,9)
GO


employeeid firstname lastname

2 Andrew Fuller
6 Michael Suyama
9 Anne Dodsworth

(3 row(s) affected)
The LIKE operator is used to find patterns in strings (pattern matching). Typically, you will want to look for a
specific pattern in the values of the rows in a given table. The syntax of LIKE is (the expression is usually a
column)


expression LIKE pattern_to_find
You specify the pattern you are looking for by using wildcards. Transact-SQL provides four types of wildcards
you can use with the LIKE operator. The first wildcard, and the most commonly used, is the percentage
character (%), which is used to specify any string of any length (0 or more). For those of you who have
previously worked with DOS or Access, the percentage character (%) is similar to * in these environments.
Listing 2.32 shows three queries that use %: The first one gets all employees whose first name begins with a,
the second one gets all employees whose first name ends with e, and the last one gets all employees whose
last name contains the character sequence ae, no matter the position.
Listing 2.32 Using the Percentage (%) Wildcard with LIKE


USE Northwind

SELECT firstname, lastname
FROM Employees
Microsoft SQL Server 2000 Programming by Example

70
WHERE firstname LIKE 'a%'

SELECT firstname, lastname
FROM Employees
WHERE firstname LIKE '%e'

SELECT firstname, lastname
FROM Employees
WHERE firstname LIKE '%ae%'
GO



firstname lastname

Andrew Fuller
Anne Dodsworth

firstname lastname

Anne Dodsworth

firstname lastname

Michael Suyama
The second wildcard is the underscore character (_), which denotes any single character. The third wildcard is
used to search for a character within a range or a set, which is delimited by brackets. For example, [a–z]
denotes a range that contains all characters between a and z, and [abc] denotes a set that contains three
characters: a, b, and c. The last wildcard is a variation of the third one, in which you want to search for a
character not within a range or set. Listing 2.33 shows an example of each of these wildcards. The first
query gathers all the employees whose first name begins with any character, and the last four characters are
anet. The second one returns all employees whose first name begins with either j or s. The third query gets all
employees whose first name does not begin with the character a, m, j, s, l, or r.
Listing 2.33 Using Wildcards with LIKE


USE Northwind

SELECT firstname, lastname
FROM Employees
WHERE firstname LIKE '_anet'


SELECT firstname, lastname
FROM Employees
WHERE firstname LIKE '[js]%'
Chapter 2. Elements of Transact-SQL
71

SELECT firstname, lastname
FROM Employees
WHERE firstname LIKE '[^amjslr]%'
GO


firstname lastname

Janet Leverling

firstname lastname

Janet Leverling
Steven Buchanan

firstname lastname

Nancy Davolio
The last operator is the plus sign (+), which is used to concatenate strings, as shown in Listing 2.34.
Listing 2.34 Using the String-Concatenation Operator


DECLARE @first VARCHAR(10), @second VARCHAR(10)
SET @first = 'SQL '

SET @second = 'Server'
SELECT @first + @second
GO



SQL Server
Generally, + is used to concatenate columns when querying tables, as Listing 2.35 shows.
Listing 2.35 Using the String-Concatenation Operator to Concatenate Columns
Microsoft SQL Server 2000 Programming by Example

72


USE Northwind

SELECT firstname + ''+lastname
FROM Employees
WHERE employeeId = 1
GO



Nancy Davolio
Control of Flow Statements
Transact-SQL provides statements that you can use to control the flow of the code in your scripts. The most
common statements are IF ELSE and WHILE, which are very common among modern programming
languages.
Note
Transact-SQL does not provide a FOR statement, like many other programming languages. Instead,

it provides a WHILE statement, which can expose basically the same functionality of the FOR
statement.

IF ELSE
The IF statement contains a condition that is evaluated by SQL Server; if it is true, the code right after IF is
executed, and if it is not true, the code right after ELSE is executed. Notice that the ELSE statement is optional.
If there is more than one statement to execute in IF or ELSE, these have to be delimited by the BEGIN and
END statements. For example, Listing 2.36 demonstrates the use of IF ELSE with multiple statements.
This example uses EXISTS, which evaluates to true if there is at least one row in the query (in this case, the
query is SELECT * FROM Shippers), or false if there are no rows in the query. Also, this example returns a
message to the client using the PRINT statement, which takes a string as a parameter (this is why the integer
must be converted to character).
Listing 2.36 Using IF ELSE Control of Flow Statements
Chapter 2. Elements of Transact-SQL
73


USE Northwind

IF EXISTS (SELECT * FROM Shippers)
BEGIN
DECLARE @number_rows INT
SELECT @number_rows = count(*) FROM Shippers
PRINT 'There are '+ CAST(@number_rows AS VARCHAR(10))
+ 'rows in the Shippers table'
END
ELSE
PRINT 'This table does not contain any rows'

GO



There are 3 rows in the Shippers table
RETURN
RETURN is used to exit unconditionally from a script or stored procedure. When used in stored procedures,
RETURN receives a parameter, the return code. As a standard coding convention, a return code of 0 means
success, and any other number than 0 indicates than an error occurred.
Listing 2.37 shows an example of RETURN. Observe that the statement that is right after RETURN is not
executed.
Listing 2.37 Aborting Script Execution Using RETURN


PRINT 'First step'
RETURN 2
PRINT 'Second step (this is not executed)'
GO
Microsoft SQL Server 2000 Programming by Example

74


First step
WAITFOR
WAITFOR can be used in one of two ways. Using the first one, it instructs SQL Server to wait until a specific
time, and the syntax is

WAITFOR TIME 'time'
Using the second way, WAITFOR indicates SQL Server to wait a specific amount of time.

WAITFOR DELAY 'time'

Listing 2.38 shows an example of each of these two approaches. The first WAITFOR statement waits until
8:00 a.m., and the second one waits until 1 minute after 8:00 a.m.
Listing 2.38 Using WAITFOR


WAITFOR TIME '08:00:00'
PRINT getdate()
WAITFOR DELAY '00:01:00'
PRINT getdate()
GO


Jan 9 2001 8:00AM
J9n 9 2001 8:01AM
WHILE
WHILE iterates (executing some statements) until a certain condition is true. If there is more than one
statement to execute until the condition is true, enclose them between BEGIN and END.
Listing 2.39 shows an implementation of multiplication that uses WHILE to loop as many times as the
second number indicates.
Chapter 2. Elements of Transact-SQL
75
Listing 2.39 Looping with WHILE Statements


DECLARE @a INT, @b INT, @result INT
SET @a = 3
SET @b = 4
SET @result = 0
WHILE @b > 0
BEGIN

SET @result = @result + @a
SET @b = @b - 1
END
SELECT @result
GO



12

(1 row(s) affected)
BREAK
BREAK is used inside a WHILE statement to exit unconditionally from the WHILE loop. When SQL Server finds
a BREAK inside a WHILE, it continues the execution with the instruction right after the END of the WHILE.
CONTINUE
CONTINUE is used inside a WHILE statement to transfer the execution to the beginning of the WHILE
statement, restarting the loop. Listing 2.40 demonstrates how CONTINUE and BREAK are used inside a
WHILE loop.
Listing 2.40 Using CONTINUE and BREAK


DECLARE @count INT
Microsoft SQL Server 2000 Programming by Example

76
SET @count = 0
WHILE @count < 10
BEGIN
IF @count = 3
BREAK

SET @count = @count + 1
PRINT 'This line is executed'
CONTINUE
PRINT 'This line is never executed'
END
GO


This line is executed
This line is executed
This line is executed
GOTO
GOTO directs SQL Server to continue the execution in the place where a label is defined. It is very useful for
error handling because you can define a generic error handler and then use GOTO to execute this error
handler in the code. Listing 2.41 shows how to alter the execution of a script using GOTO.
Listing 2.41 Altering the Execution Using GOTO


IF NOT EXISTS (SELECT * FROM Suppliers)
GOTO no_rows

IF NOT EXISTS (SELECT * FROM Employees)
GOTO no_rows

GOTO finished
no_rows:
PRINT 'An error occurred'

finished:
PRINT 'The program has finished its execution'

Chapter 2. Elements of Transact-SQL
77


The program has finished its execution
Comments
Transact-SQL provides two ways to include comments inside code. Using the first way, you can include one-
line comments, which are specified using " " (two dashes). In this case, anything that follows " " in a
specific line is considered a comment and is not evaluated by SQL Server.
The other type of comments are multiline comments, which are delimited by "/*" and "*/". Anything between
these two delimiters is considered as a comment.
Listing 2.42 shows an example of both kinds of comments that can be used in Transact-SQL.
Listing 2.42 Inserting Comments in the Code


/*
This is an example of the use
of comments in Transact-SQL
*/
SELECT @@version this query shows the current version of SQL Server
GO



Microsoft SQL Server 2000 - 8.00.194 (Intel X86)
Aug 6 2000 00:57:48
Copyright (c) 1988-2000 Microsoft Corporation
Enterprise Edition on Windows NT 5.0 (Build 2195: )

(1 row(s) affected)

Programming Scripts and Batches
The main characteristic of a batch is that it is processed by SQL Server as a unit, similar to stored procedures.
A batch might contain one or more Transact-SQL instructions, and the last statement in a batch is the GO
Microsoft SQL Server 2000 Programming by Example

78
statement. However, some restrictions apply to batches. The statements CREATE DEFAULT, CREATE
PROCEDURE, CREATE RULE, CREATE TRIGGER, and CREATE VIEW cannot appear more than once in a
batch. If any of these statements appears in a batch, it must be the only statement. Hence, if you want to have
more than one of these statements in the code, add a GO statement right after each one of them (thus creating
multiple batches).
A script comprises one or more batches— each of them separated by a GO statement. Using scripts, you can
store the schema of your database (DDL that creates all database objects) in a file. Scripts can be generated
using the Generate scripts utility in the Enterprise Manager. To use this utility, go to the databases folder in
the Enterprise Manager, then right-click the database name, and choose All Tasks, Generate SQL Script. This
window appears in Figure 2.2.
Figure 2.2. Generating scripts in Enterprise Manager.

The GO Statement
The GO statement is used to separate batches. Even though it is not a Transact-SQL element; it is used just
by the SQL Server utilities. Actually, it can be changed in the Query Analyzer to any other word, if you go to
the Options menu and then to the Connections tab. This tab appears in Figure 2.3.
Figure 2.3. Changing the batch separator in the Query Analyzer.
Chapter 2. Elements of Transact-SQL
79

What's Next?
You already know the basics of the Data Definition Language (DDL) and the data types that can be used in
Transact-SQL. In the next chapter, we will use these two elements to create tables and views. In the case of
tables, we will show you how to create different types of tables and to alter the definition of tables. Regarding

views, you will learn how to create, maintain, and manipulate data through views.

×