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

Microsoft SQL Server 2000 Programming by Example phần 3 docx

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 (1.06 MB, 71 trang )

Chapter 4. Querying and Modifying Data
127



40

9


263.5000


1937-09-19 00:00:00.000:


3119
The DISTINCT keyword can be used in any aggregate function to consider repeating values just once. For
example, to retrieve how many different titles the Employees table has, you can use the COUNT aggregate
function with the DISTINCT keyword, as shown in Listing 4.19. In this case, the DISTINCT keyword is
needed because more than one employee has the same title, and you want to count each title once to see
how many different titles are in this table.
Listing 4.19 Using DISTINCT in Aggregate Functions


USE Northwind

SELECT COUNT(DISTINCT title)
FROM Employees
GO




4
You use the GROUP BY clause to group rows in a result set, generating a summary row for each group of data.
All columns specified in SELECT must also be specified in GROUP BY. However, columns specified in the
GROUP BY clause don't have to be in the SELECT column list.
Microsoft SQL Server 2000 Programming by Example

128
To illustrate, Listing 4.20 shows an example that retrieves the number of employees per title. SQL Server
generates a row per each title (this is the column specified in the GROUP BY clause) and counts the number of
rows per title.
Listing 4.20 Using the GROUP BY Clause


USE Northwind

SELECT title, COUNT(*)
FROM Employees
GROUP BY title
GO
title

Inside Sales Coordinator 1
Sales Manager 1
Sales Representative 6
Vice President, Sales 1

(4 row(s) affected)
It might be necessary to generate a summary row for a table (just one row and not a row for each group). In

this case, because it is just one group (the whole table), use aggregate functions without the GROUP BY
clause, as previously shown in Listing 4.18. Moreover, you can use more than one aggregate function in the
same query. For example, to get the most recent date in which an order was placed, and the minimum orderid
in the Orders table, use the query shown in Listing 4.21.
Listing 4.21 Summarizing Data


USE Northwind


SELECT MAX(orderdate), MIN(orderid)
FROM orders
GO

Chapter 4. Querying and Modifying Data
129


1998-05-06 00:00:00.000 10248

(1 row(s) affected)
If there's a WHERE clause in the query, it must be specified before the GROUP BY clause. SQL Server
evaluates the WHERE clause first, and then it generates the groups based on the columns specified in GROUP
BY. For example, to retrieve the number of customers in Spain and Venezuela, use the query shown in
Listing 4.22.
Listing 4.22 Restricting the Groups Generated by GROUP BY


USE Northwind



SELECT country, COUNT(*)
FROM Customers
WHERE country IN ('Spain','Venezuela')
GROUP BY country
GO


country

Spain 5
Venezuela 4

(2 row(s) affected)
Tip
As a new feature of SQL Server 2000, BIT columns can be used in a GROUP BY clause. This was
a limitation of GROUP BY in previous versions.

Microsoft SQL Server 2000 Programming by Example

130
The use of column aliases is recommended when working with aggregate functions, because when any
function is applied to a column, the result set doesn't show the original name of the column. Listing 4.23
shows an example of column aliases when using aggregate functions.
Listing 4.23 Using Column Aliases and Aggregate Functions


USE Northwind

SELECT country, COUNT(*) AS [number of customers]

FROM Customers
WHERE country IN ('Spain','Venezuela')
GROUP BY country
GO


country number of customers

Spain 5
Venezuela 4

(2 row(s) affected)
The HAVING Clause
When using GROUP BY in a query to generate groups, you might want to set restrictions on these groups.
Specifically, the HAVING clause sets restrictions on the groups generated by GROUP BY. HAVING is similar to
WHERE in the sense that it restricts the output of the query, but HAVING is evaluated by SQL Server after the
groups are generated.
It's important to know that WHERE is evaluated first, then groups are generated (as a result of GROUP BY), and
finally, the HAVING clause is evaluated. Therefore, aggregate functions cannot be referenced in the WHERE
clause; they can be referenced only in the HAVING clause.
Listing 4.24 retrieves the number of customers of the countries that have more than five customers. This is
done by setting a restriction after the groups are generated (using a HAVING clause); hence, showing only the
countries that have more than five customers.
Listing 4.24 Setting Restrictions on the Groups Generated by GROUP BY Using HAVING
Chapter 4. Querying and Modifying Data
131


USE Northwind


SELECT country, COUNT(*) AS [number of customers]
FROM Customers
GROUP BY country
HAVING COUNT(*) > 5
GO


country number of customers

Brazil 9
France 11
Germany 11
UK 7
USA 16

(5 row(s) affected)
Similar to WHERE, multiple conditions can be specified in the HAVING clause, combining them with a logical
operator (OR or AND). Listing 4.25 shows how conditions can be combined in a HAVING clause.
Listing 4.25 Combining Conditions in a HAVING Clause


USE Northwind


SELECT country, COUNT(*) AS [number of customers]
FROM Customers
GROUP BY country
HAVING COUNT(*) > 5
AND COUNT(*) < 10
GO

Microsoft SQL Server 2000 Programming by Example

132


country number of customers

Brazil 9
UK 7

(2 row(s) affected)
The ORDER BY Clause
A table comprises a set of rows, and a set, by definition, is unordered. Therefore, when retrieving data from
tables, SQL Server doesn't guarantee the order of the rows in the result set. This is because SQL Server
might optimize the query in a different way each time it is executed, depending on the data; resulting in a
different order of the rows each time the same query is executed. To guarantee a specific order in a result set,
use the ORDER BY clause. Listing 4.26 retrieves information from the Shippers table ordered by company
name in ascending order (this is the default in SQL Server).
Listing 4.26 Using ORDER BY to Guarantee the Order of Rows


USE Northwind

SELECT companyname, phone
FROM Shippers
ORDER BY companyname
GO


companyname phone


Federal Shipping (503) 555-9931
Speedy Express (503) 555-9831
United Package (503) 555-3199

(3 row(s) affected)
Chapter 4. Querying and Modifying Data
133
You can include more than one column in the ORDER BY clause, and you also can specify how these values
will be sorted, either ascending (using the ASC keyword), which is the default, or descending (using the DESC
keyword). If more than one column is specified in the ORDER BY clause, SQL Server sorts the result set in the
order in which these columns appear (first, the first column, then the second column, and so on). Listing
4.27 shows how to specify multiple columns and how to order them (either ascending or descending) in the
ORDER BY clause.
Listing 4.27 Using Multiple Expressions in the ORDER BY Clause


USE Northwind

SELECT lastname, firstname
FROM Employees
ORDER BY lastname ASC, firstname DESC
GO


lastname firstname

Buchanan Steven
Callahan Laura
Davolio Nancy

Dodsworth Anne
Fuller Andrew
King Robert
Leverling Janet
NewFamily Michael
Peacock Margaret

(9 row(s) affected)
Tip
As discussed in previous chapters, use TOP if you want to specify the ORDER BY clause when
creating a view.

The TOP N Clause
Microsoft SQL Server 2000 Programming by Example

134
TOP is used to limit the results of a query. It can be used in two ways: to retrieve the first N rows or to retrieve
the first N percent of the rows in the result set. The TOP clause must be used along with ORDER BY; otherwise,
SQL Server doesn't guarantee a specific ordering, and the TOP clause will be meaningless.
TOP returns the least significant values if they are sorted in ascending order. On the other hand, TOP retrieves
the most significant values if they are sorted in descending order. For example, to retrieve the most expensive
products, use a TOP clause and an ORDER BY clause sorting the unitprice column in descending order, as
shown in Listing 4.28.
Listing 4.28 Limiting the Output of a Query Using the TOP Clause


USE Northwind

SELECT TOP 10 productid, productname, unitprice
FROM Products

ORDER BY unitprice DESC

SELECT TOP 1 PERCENT productid, productname, unitprice
FROM Products
ORDER BY unitprice DESC
GO


productid productname unitprice

38 Côte de Blaye 263.5000
29 Thüringer Rostbratwurst 123.7900
9 Mishi Kobe Niku 97.0000
20 Sir Rodney's Marmalade 81.0000
18 Carnarvon Tigers 62.5000
59 Raclette Courdavault 55.0000
51 Manjimup Dried Apples 53.0000
62 Tarte au sucre 49.3000
43 Ipoh Coffee 46.0000
28 Rössle Sauerkraut 45.6000
(10 row(s) affected)

productid productname unitprice

38 Côte de Blaye 263.5000

(1 row(s) affected)
Caution
Chapter 4. Querying and Modifying Data
135

If you're concerned about portability, be careful when using TOP because it is not ANSI standard.
Instead, it is a feature of Transact-SQL.

The argument of TOP is a positive integer in either case (percent or fixed number of rows).
Caution
The argument of the TOP clause must be an integer; it cannot be a variable. If you want to use a
variable, use dynamic queries (EXEC or sp_executesql).

In previous versions of SQL Server (6.5 and earlier), the only way to limit the result set of a query was by
using SET ROWCOUNT, which stops the processing of the query when it reaches the number of rows specified
by SET ROWCOUNT.
Be aware that TOP is more efficient than SET ROWCOUNT because TOP is evaluated at parse time, not at
execution time like SET ROWCOUNT. Another disadvantage of using SET ROWCOUNT is that it remains set
until you execute SET ROWCOUNT 0 to reset it to its original behavior (all rows are returned when executing a
query). When SET ROWCOUNT is enabled, it also affects modification operations (INSERT, UPDATE, and
DELETE). Listing 4.29 demonstrates the usage of SET ROWCOUNT (notice that the result set is equivalent to
the one shown in Listing 4.28).
Listing 4.29 Using SET ROWCOUNT


USE Northwind

Use SET ROWCOUNT 10 to limit the output of all queries to 10 rows
SET ROWCOUNT 10

SELECT productid, productname, unitprice
FROM Products
ORDER BY unitprice DESC

Use SET ROWCOUNT 0 to reset it to its original state (all rows are returned)

SET ROWCOUNT 0
GO
Microsoft SQL Server 2000 Programming by Example

136


productid productname unitprice

38 Côte de Blaye 263.5000
29 Thüringer Rostbratwurst 123.7900
9 Mishi Kobe Niku 97.0000
20 Sir Rodney's Marmalade 81.0000
18 Carnarvon Tigers 62.5000
59 Raclette Courdavault 55.0000
51 Manjimup Dried Apples 53.0000
62 Tarte au sucre 49.3000
43 Ipoh Coffee 46.0000
28 Rössle Sauerkraut 45.6000

(10 row(s) affected)
Caution
If you use SET ROWCOUNT, don't forget to execute SET ROWCOUNT 0 to turn this setting off;
otherwise, it remains set during the connection, affecting all subsequent queries.

Use the WITH TIES keyword of the TOP clause when you want to include ties in the result set. If WITH TIES
is specified, the result set may contain more rows than the number of rows specified in the TOP clause
because all ties would be included. For example, Listing 4.30 shows a query that retrieves the top six units
in stock. Notice that seven rows are returned because there's a tie in the sixth position, and the query returns
all ties (two in this case).

Listing 4.30 Using WITH TIES in TOP Clauses


USE Northwind

SELECT TOP 6 WITH TIES productid, productname, unitsinstock
FROM Products
ORDER BY unitsinstock DESC
GO
Chapter 4. Querying and Modifying Data
137


productid productname unitsinstock

75 Rhönbräu Klosterbier 125
40 Boston Crab Meat 123
6 Grandma's Boysenberry Spread 120
55 Pâté chinois 115
61 Sirop d'érable 113
33 Geitost 112
36 Inlagd Sill 112

(7 row(s) affected)
Using Dynamic Queries
In some situations, you might want to parameterize queries using variables to specify, for example, the table
to query. However, some elements cannot be specified dynamically in queries, such as the table name and
column names. In these specific cases, dynamic queries might be beneficial. Specifically, there are two ways
to execute dynamic queries: using EXEC (or EXECUTE), and using the sp_executesql system stored
procedure. These two ways are listed in Listing 4.31.

Caution
The string (a dynamic query) that is passed as an argument to sp_executesql must be a
Unicode string (to specify Unicode strings, use the N prefix when building the string).

Listing 4.31 Dynamically Generating and Executing Queries Using EXEC and sp_executesql


USE Northwind

DECLARE @tablename VARCHAR(20), @query NVARCHAR(100)
SET @tablename = 'Shippers'
SET @query = N'SELECT * FROM '+ @tablename

Executing the dynamic query using EXEC
EXEC (@query)

Executing the dynamic query using sp_executesql
Microsoft SQL Server 2000 Programming by Example

138
EXEC sp_executesql @query
GO


ShipperID CompanyName Phone

1 Speedy Express (503) 555-9831
2 United Package (503) 555-3199
3 Federal Shipping (503) 555-9931


ShipperID CompanyName Phone

1 Speedy Express (503) 555-9831
2 United Package (503) 555-3199
3 Federal Shipping (503) 555-9931

(3 row(s) affected)
The following are the disadvantages of using dynamic queries:
• The statements inside EXEC or sp_executesql are executed inside its own batch; therefore, these
statements cannot access variables declared in the outside batch.
• If the query to be executed by EXEC is not similar enough to a previously executed query due to
different format, values, or data types, SQL Server cannot reuse a previously executed query plan.
However, sp_executesql overcomes this limitation, allowing SQL Server to reuse the execution
plan of the query (because it can be cached in memory).
Tip
Use sp_executesql whenever possible when executing dynamic queries, because the plan has
a better chance of being reused.

Sometimes the dynamic query is very long and it becomes illegible. In these cases, you can use a variable to
store the entire string and then use this variable as the argument of EXEC or sp_executesql, as shown in
Listing 4.31. Also, you might want to insert carriage returns (using CHAR(13)) in the query to make it more
legible (in case you want to display it). Listing 4.32 indicates how to insert carriage returns in a dynamic
query.
Listing 4.32 Inserting Carriage Returns When Building Dynamic Queries
Chapter 4. Querying and Modifying Data
139


USE Northwind


DECLARE @query NVARCHAR(100)
SET @query = N'SELECT * '+ CHAR(13)+ 'FROM Shippers'

To display the query (which has a carriage return)
SELECT @query

Executing the dynamic query
EXEC sp_executesql @query
GO




SELECT * FROM Shippers

(1 row(s) affected)

ShipperID CompanyName Phone

1 Speedy Express (503) 555-9831
2 United Package (503) 555-3199
3 Federal Shipping (503) 555-9931

(3 row(s) affected)
Caution
In SQL Server, EXECUTE can be used for three different purposes: to execute dynamic queries, to
execute stored procedures, and to assign execute permissions to users on stored procedures
(using GRANT, DENY, or REVOKE). The difference between executing a stored procedure and a
dynamic statement using EXECUTE is that the first one doesn't need to be enclosed in parentheses,
whereas the dynamic statement does.


There are some security issues when dynamic statements are executed inside a stored procedure. Usually, to
be able to execute a stored procedure, a user just needs to have EXECUTE permissions on the stored
procedure. However, if a dynamic query is used, the user also needs permissions on every object referenced
by the dynamic query. This is because the dynamic query is not parsed until the stored procedure is executed,
and SQL Server must check permissions on every object referenced by the dynamic query.
Microsoft SQL Server 2000 Programming by Example

140
Modifying Data
As you already know, SELECT is the element of the Data Manipulation Language (DML) that is used to extract
information from tables. The other elements of the DML are used to add, modify, and remove data from tables.
These elements are INSERT, UPDATE, and DELETE.
The INSERT Statement
INSERT is used to add new rows in a table. The following is the basic syntax to insert a row in a table:

INSERT INTO Table_name (column_1,column_2, ,column_n)
VALUES (value_1,value_2, ,value_n)
The order of the values to be inserted must be the same order of the columns specified in the column list. Also,
the INTO keyword can be omitted when using the INSERT statement, as shown in Listing 4.33.
Listing 4.33 Adding a New Row Using the INSERT Statement


USE Northwind

INSERT Territories (territoryid,territorydescription,regionid)
VALUES ('77777','Fort Lauderdale',4)
GO



(1 row(s) affected)
If you want to insert data in all columns of a table, the column list can be omitted, but keep in mind that the
values must be ordered in the same way that their respective columns appear in the table's definition (you can
see the order of the columns using the sp_help system stored procedure).
For example, Listing 4.34 inserts a row in the Territories table, omitting the column list.
Listing 4.34 Omitting the Column List When Inserting Data in All Columns of the Table


USE Northwind
Chapter 4. Querying and Modifying Data
141

INSERT Territories VALUES ('88888','Miami',4)
GO


(1 row(s) affected)
SQL Server automatically handles IDENTITY columns by default. Therefore, when a row is inserted in a table
that has an IDENTITY column, you don't have to specify the IDENTITY column in the INSERT statement
because SQL Server provides a value automatically, as shown in Listing 4.35.
Listing 4.35 Inserting a Row in a Table with an IDENTITY Column


USE Northwind

INSERT Shippers (companyname, phone)
VALUES ('Super Fast Shipping','(503) 555-6493')
GO



(1 row(s) affected)
However, if you want to explicitly insert a value in an IDENTITY column, use SET IDENTITY_INSERT with
the table's name as an argument. This is demonstrated in Listing 4.36.
Listing 4.36 Inserting a Value in an IDENTITY Column


USE Northwind

Microsoft SQL Server 2000 Programming by Example

142
SET IDENTITY_INSERT Shippers ON
INSERT Shippers (shipperid,companyname, phone)
VALUES (20,'ACME Shipping','(503) 555-8888')
SET IDENTITY_INSERT Shippers OFF
GO


(1 row(s) affected)
There are two ways to insert NULL values in nullable columns: either explicitly (using the NULL keyword when
inserting data) or implicitly (the column is not referenced in the INSERT statement).
Similarly, there are two ways to use default values in INSERT statements: either explicitly (using the DEFAULT
keyword) or implicitly (if the column is not specified in the INSERT statement).
As a result, when columns are omitted in the column list of INSERT, SQL Server automatically provides a
default value (if one is defined on the column) or, if a default value is not defined and the column is nullable, a
NULL is used. On the other hand, if a column doesn't have a default value and it doesn't accept NULLs, a
value must be specified in the INSERT statement; otherwise, the INSERT operation will fail.
Listing 4.37 shows two equivalent INSERT statements. The first one uses the NULL and DEFAULT keywords,
whereas the second one omits these columns, producing the same result.
Listing 4.37 Omitting Specific Columns and Using the NULL and DEFAULT Keywords



USE Northwind

INSERT Products (productname,supplierid,categoryid,quantityperunit,
reorderlevel,discontinued)
VALUES ('Donut',NULL,NULLx,'6 pieces',DEFAULT,DEFAULT)

INSERT Products (productname,quantityperunit)
VALUES ('Donut','6 pieces')
GO


(1 row(s) affected)
Caution
Chapter 4. Querying and Modifying Data
143
Keywords, such as NULL or DEFAULT, don't need to be enclosed in single quotation marks like
strings.

Furthermore, if you want to insert default values in all columns and NULL values in the nullable ones without a
default, use the following syntax (which also takes care of IDENTITY values):

INSERT Table_name DEFAULT VALUES
Be aware that to be able to use this syntax, all columns must meet at least one of these conditions:
• It must be an IDENTITY column.
• The column must have a default value defined on it.
• The column must be nullable.
Listing 4.38 shows an example of this syntax.
Listing 4.38 Inserting Default Values in All Columns



USE Northwind

INSERT Orders DEFAULT VALUES
GO


(1 row(s) affected)
INSERT may also be used to insert multiple rows in a table. This can be done through two approaches:
• Using a SELECT statement along with INSERT. In this case, the output of the SELECT statement is
inserted into the table. Listing 4.39 indicates how to insert multiple rows in a table using this
approach.
Listing 4.39 Inserting a SELECT Statement's Output into a Table
Microsoft SQL Server 2000 Programming by Example

144


USE Northwind

CREATE TABLE #employees_in_wa (
lastname NVARCHAR(40),
firstname NVARCHAR(20)
)

Inserting into the temporary table the last name
and first name of all employees from WA

INSERT #employees_in_wa

SELECT lastname,firstname
FROM Employees
WHERE region = 'WA'

SELECT * FROM #employees_in_wa
GO


(5 row(s) affected)

lastname firstname

Davolio Nancy
Fuller Andrew
Leverling Janet
Peacock Margaret
Callahan Laura

(5 row(s) affected)
• Executing a stored procedure that has a SELECT statement on it, and inserting this output into a table.
Notice that this approach is similar to the first one; the only difference is that the SELECT statement is
wrapped into a stored procedure. Listing 4.40 shows how the output of a stored procedure is
inserted into a table.
Listing 4.40 Inserting the Output of a Stored Procedure into a Table
Chapter 4. Querying and Modifying Data
145


USE Northwind
GO


CREATE PROC get_uk_employees
AS
SELECT lastname,firstname
FROM Employees
WHERE country = 'UK'
GO

CREATE TABLE #employees_in_uk (
lastname NVARCHAR(40),
firstname NVARCHAR(20)
)

Inserting into the temporary table the last name
and first name of all employees from UK

INSERT #employees_in_uk
EXEC get_uk_employees

SELECT * FROM #employees_in_uk
GO


(4 row(s) affected)

lastname firstname

Buchanan Steven
NewFamily Michael
King Robert

Dodsworth Anne

(4 row(s) affected)
The DELETE Statement
You use DELETE to remove one or more rows permanently from a table. A DELETE statement may contain a
WHERE clause to restrict the rows to be deleted. The basic syntax of DELETE is

DELETE Table_name WHERE condition
If WHERE is not used in the DELETE statement, all rows are removed from the table. Listing 4.41 shows how
to delete specific rows from a table (using a WHERE clause).
Microsoft SQL Server 2000 Programming by Example

146
Listing 4.41 Deleting Rows from a Table


USE Northwind

DELETE Orders
WHERE customerid IS NULL
GO


(1 row(s) affected)
The TRUNCATE statement is also used to remove permanently all rows from a table. However, it has some
restrictions:
• The table cannot have foreign keys defined.
• TRUNCATE cannot contain a WHERE clause. Therefore, all rows in the table are removed.
• TRUNCATE reseeds the IDENTITY value of the table (if there is one).
Tip

TRUNCATE is faster than DELETE because SQL Server only logs the deallocation of pages, not the
removal of each row (like it does when dealing with DELETE statements).

Listing 4.42 illustrates the use of the TRUNCATE statement to remove all rows from a table.
Listing 4.42 Using the TRUNCATE Statement to Delete All Rows from a Table


USE Northwind
GO
Chapter 4. Querying and Modifying Data
147

CREATE TABLE #shippers (
companyname NVARCHAR(20),
phone NVARCHAR(20)
)

INSERT #shippers
SELECT companyname,phone FROM Shippers

Using TRUNCATE to remove all rows from the #shippers table
TRUNCATE TABLE #shippers

SELECT * FROM #shippers
GO


(5 row(s) affected)

companyname phone



(0 row(s) affected)
The UPDATE Statement
The UPDATE statement sets new values in existing rows of a specific table. UPDATE modifies information in
just one table. Therefore, if you want to change data in some other table, use another UPDATE statement. The
basic syntax of UPDATE is

UPDATE Table_name
SET column_1 = new_value,
column_2 = new value,
.
.
column_n = new_value
WHERE condition
The new value of a column can be either a constant or an expression that may or may not contain the
previous value of the column.
A WHERE clause can be used to restrict the rows to be modified by the UPDATE statement.
Listing 4.43 shows an UPDATE statement that restricts the column to be modified with a WHERE clause. Also,
the new value of one of the columns, companyname, is based in the old value (concatenating the word
'Express' to the old value).
Listing 4.43 Using the UPDATE Statement
Microsoft SQL Server 2000 Programming by Example

148


USE Northwind

UPDATE Shippers

SET companyname = companyname + 'Express',
phone = '(305) 555 8888'
WHERE shipperid = 20
GO


(1 row(s) affected)
Using an UPDATE statement, the new values of columns can be stored in local variables when updating a
single row. This method is useful because you don't have to update the row first, and then use a SELECT
statement to get the new values. The following is the basic syntax:

UPDATE table
SET @variable = column = value
Listing 4.44 indicates how to store the new value of a column in a local variable.
Listing 4.44 Storing in Variables the New Values of Columns When Updating a Single Row


USE Northwind

DECLARE @availableunits SMALLINT

UPDATE Products
SET @availableunits = unitsinstock = unitsinstock + 20
WHERE productname = 'Chai'

SELECT @availableunits
GO
(1 row(s) affected)



59
Chapter 4. Querying and Modifying Data
149


(1 row(s) affected)
The SELECT INTO Statement
SELECT INTO enables you to create a table on-the-fly and populate it using just one instruction. The new
table is populated with the output of the SELECT statement. SELECT INTO can be used to create either
permanent or temporary tables. Listing 4.45 shows the syntax of SELECT INTO.
Listing 4.45 Using SELECT INTO to Create and Populate Tables


USE Northwind

SELECT lastname, firstname
INTO #salesrep_employees
FROM employees
WHERE title = 'sales representative'

SELECT * FROM #salesrep_employees
GO
(6 row(s) affected)

lastname firstname

Davolio Nancy
Leverling Janet
Peacock Margaret
NewFamily Michael

King Robert
Dodsworth Anne


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

150
Column aliases must be used for calculated columns. These aliases are the column names that SQL Server
will use when creating the new table specified in SELECT INTO. For example, Listing 4.46 uses an alias for
the first column, which is the result of the concatenation of two columns (firstname and lastname).
Listing 4.46 Using Column Aliases with SELECT INTO


USE Northwind

SELECT firstname + ''+ lastname AS fullname, country
INTO #employeescountry
FROM Employees
ORDER BY fullname

SELECT * FROM #employeescountry
GO


(9 row(s) affected)

fullname country

Andrew Fuller USA

Anne Dodsworth UK
Janet Leverling USA
Laura Callahan USA
Margaret Peacock USA
Michael Suyama UK
Nancy Davolio USA
Robert King UK
Steven Buchanan UK

(9 row(s) affected)
The IDENTITY function is used to generate a column with consecutive numbers when using SELECT INTO.
Similar to the IDENTITY property, the IDENTITY function accepts three parameters: the data type, the seed
(or first number), and the increment (the last two are the arguments of the IDENTITY property). Listing 4.47
demonstrates how the IDENTITY function is used in SELECT INTO statements.
Listing 4.47 Using the IDENTITY function
Chapter 4. Querying and Modifying Data
151


USE Northwind

SELECT IDENTITY(INT,1,1) as companyid, companyname
INTO #italiancompanies
FROM Customers
WHERE country = 'Italy'

SELECT * FROM #italiancompanies
GO



(3 row(s) affected)

companyid companyname

1 Franchi S.p.A.
2 Magazzini Alimentari Riuniti
3 Reggiani Caseifici

(3 row(s) affected)
In previous versions of SQL Server (7.0 and earlier), the SELECT INTO/ BULKCOPY database option had to
be set to TRUE if you wanted to use SELECT INTO to create permanent tables. In SQL Server 2000, the
SELECT INTO/ BULKCOPY and the TRUNC. LOG ON CHKPT. database options are no longer used. Now,
SQL Server provides three recovery models (SIMPLE, BULK LOGGED, and FULL), and basically, SELECT
INTO can be used with any of these models. For more information on recovery models, refer to Books Online.
What's Next?
You already know how to interact with single tables and extract data from them. In the next chapter, you will
learn how to extract data from multiple tables through JOINs, the different type of JOINs, and how to combine
the results of more than one query using the UNION operator.

×