CHAPTER 6 • SELECT QUERIES232 ‘c:\MSOffice\Access\Samples\northwind.mdb’;’admin’;’mypwd’, Orders AS AccessGO The syntax for OPENROWSET is as follows: sp_addlinkedserver ‘Washington’, ‘SQ
Trang 1CHAPTER 6 • SELECT QUERIES
220
10 On the Start Copying Files screen, click Next to complete the installation.
11 After setup has completed copying files, click Finish.
After the short task of installation has been completed, you are ready to configureFull-Text Search for use The first thing you need to do is create a full-text index Full-text indexes are created with SQL Server tools, such as Enterprise Manager, but theyare maintained by the Microsoft Search Service and stored on the disk as files separatefrom the database To keep the full-text indexes organized, they are stored in catalogs
in the database You can create as many catalogs in your databases as you like to nize your indexes, but these catalogs cannot span databases
orga-When a full-text index is first created, it is completely useless Because theseindexes are maintained by the Microsoft Search Service, you must specifically instructthe Search Service to fill the index with information about the text fields that you
want to search This filling of the full-text indexes is called populating the index As
your data changes over time, you will need to tell the Search Service to rebuild your
full-text indexes to match your data—this process is called repopulating.
In the following steps, you will create a catalog and index for the Employees table
in the Northwind database Employees was chosen because it has a text column in it(actually it’s ntext, which is Unicode as opposed to standard ANSI text) Here’s how tocreate the index and catalog:
1 While still in Enterprise Manager, click the Northwind icon and from the Tools
menu select Full-Text Indexing
2 On the first screen of the Full-Text Indexing Wizard, click Next.
Trang 23 On the second screen, you must select a table to index Here, pick
[dbo].[Employees] because it has a text column and click Next
4 Each table on which you create a full-text index must already have a unique
index associated with it for Full-Text to work In this instance, select the defaultPK_Employees index and click Next
FULL-TEXT SEARCHING
P A R TII
Trang 3CHAPTER 6 • SELECT QUERIES
222
5 On the next screen, you are asked which column you want to full-text index.
Because Notes is your ntext column, select it here by checking the box next to itand click Next
Trang 46 On the next screen, you are asked in which catalog you would like to store this
new index You’ll need to create a new one here, because there are none
avail-able In the Name field, enter Northwind Catalog and click Next.
7 On the next screen, you are asked to create a schedule for automatically
repopu-lating the full-text index If your data is frequently updated, you will want to dothis more often, maybe once a day If it is read more often than it is changed,you should repopulate less frequently You can schedule population for a singletable or an entire catalog at a time Here, you will set repopulation to happenjust once for the entire catalog by clicking the New Catalog Schedule button
8 On the New Schedule Properties screen, enter Populate Northwind and click OK.
FULL-TEXT SEARCHING
P A R TII
Trang 5CHAPTER 6 • SELECT QUERIES
224
9 When you are taken back to the Full-Text Indexing Wizard, click Next.
10 On the final screen of the Wizard, you are given a summary of the choices you
have made Click Finish to create the index
To use your new full-text index, you will need to populate it for the first time.Here’s how:
1 In Enterprise Manager, expand Northwind and select Full-Text Catalogs.
Trang 62 In the contents pane (on the right), right-click the Northwind Catalog and
move to Start Population
3 From Start Population, select Full Population.
With a new, fully populated full-text index in place, you are ready to unleash thepower of the full-text search To do that, you need to know how to modify yourSELECT query to work with the Microsoft Search Service that scans your new index
Let’s look at some new clauses for full-text search
Performing Full-Text Searches
The nice thing about performing a full-text search is that you already know how to do
it, or at least you are very close Full-text searches are just SELECT queries that usefull-text operators Four operators are used to search through a full-text index:
CONTAINS and CONTAINSTABLE: These can be used to get exact or so-exact words or phrases from text columns Not-so-exact means that if you
not-look for cook, you could also find cooks, cooked, cooking, etc.
FREETEXT and FREETEXTTABLE: These are less precise than TAINS; they return the meaning of phrases in the search string For example, ifyou search for the string “SQL is a database server”, you would receive results
CON-containing the words SQL, database, server, and any derivative thereof.
The difference between CONTAINS/FREETEXT and TABLE is that the latter don’t return a normal result set Instead, they create a wholenew table for you to search through These operators are generally used in complexqueries that require you to join the original table with the newly created table thatcame from the CONTAINSTABLE/FREETEXTTABLE query
CONTAINSTABLE/FREETEXT-To see how to use the CONTAINS/FREETEXT operators, let’s execute some queries:
1 Open Query Analyzer and log in using Windows NT Authentication.
2 Execute the following code:
USE NorthwindSELECT notes FROM EmployeesWHERE CONTAINS (Notes, ‘”French”’)
FULL-TEXT SEARCHING
P A R TII
Trang 7CHAPTER 6 • SELECT QUERIES
226
3 In the result set, notice that each record returned contains the word French Now
execute the following code to test FREETEXT:
USE NorthwindSELECT notes FROM EmployeesWHERE FREETEXT (Notes, ‘“selling peace”’)
4 In the result set, notice that each record contains either selling or peace in
some form
Trang 8The FREETEXTTABLE and CONTAINSTABLE operators function quite a bit ently from their counterparts These two operators look through the full-text indexesand create a brand-new table with two columns: key and rank The key column tellsyou the record number of the record that matches your query, so if record number 3
differ-in the queried table matches your query, the key column would simply say 3 Therank column tells you how closely the record matches your query: 1000 indicates anexact match, and 1 indicates a low chance of a match You can use the new table that
is created by FREETEXTTABLE in a JOIN to see how closely each record in your tablematches your query For example, if you want to know who in your company speaksFrench and German, you could use the following query (also see Figure 6.21):
USE Northwind SELECT new.[key], new.rank, emp.lastname, emp.firstname, emp.notesFROM employees AS emp
INNER JOINFREETEXTTABLE(employees, notes, ‘German French’) AS new
Trang 9CHAPTER 6 • SELECT QUERIES
228
FIGURE 6.21
FREETEXTTABLE generates a completely new table with a rank column.
Let’s examine the result set that comes from this query, as displayed in Figure 6.21.First you told SQL to select the key and rank columns from the table that the FREE-TEXTTABLE operator creates The key column tells you the record number of thematching record, and the rank column tells you how closely that record matches.Take a look at the first record: The key is 2, which means that the record number is 2(literally, it is the second record in the table) The rank column is 174—this is thehighest matching record in the table Now read the notes column and notice that it
has both German and French The same is true of the second record in the result set— both German and French are mentioned In the third record of the result set, you will
notice that the rank is 0, which means that it has a very low chance of containing thedata you want In fact, if you look at the notes column for the third record of the
result set, you will see that only French is mentioned, not German The same is true of
the other records as well, each having no chance of meeting your requirements.These full-text search queries can be very powerful tools for locating data in largetext columns, but they are valueless if you don’t maintain them Let’s see what ittakes to administer your newfound indexes
Trang 10Administering Full-Text Search
There is not a lot of work involved in administering Full-Text Search The most tant thing to remember is the repopulation of the full-text indexes, and that can bescheduled when you first create the catalog However, if you underestimate the fre-quency of data updates, you may need to change that schedule To change the repop-ulation schedule, follow these steps:
impor-1 In Enterprise Manager, expand the database containing the full-text catalog you
want to modify In this instance, it is Northwind
2 Click the Full-Text Catalog icon.
3 In the contents (right) pane, right-click the Northwind Catalog icon and select
Schedules
4 In the Schedules dialog box that pops up, select the schedule to change and
click Edit, then select Recurring
FULL-TEXT SEARCHING
P A R TII
Trang 11CHAPTER 6 • SELECT QUERIES
230
5 Click the Change button and select Daily, and then click OK.
6 Click OK on each screen until you are returned to Enterprise Manager.
If you have just made a massive amount of changes, such as a bulk insert, to atable, you may not have time to wait for the scheduled repopulation of the index.You can force repopulation by right-clicking the catalog and selecting Start Popula-tion, and then selecting either Full or Incremental Population A full population willrebuild the entire full-text index, and an incremental population will update only thechanges to the index since the last repopulation
Trang 12The only other administrative activity you need to engage in for Full-Text Search isbacking up the indexes themselves Although full-text indexes are managed throughEnterprise Manager, they are not actually part of the SQL Server database structure Infact, they are stored outside of SQL Server in an entirely separate directory, which ismanaged by the Microsoft Search Service To back these indexes up, you need toremember to stop the Microsoft Search Service and include the MSSQL2000\DATAdirec-tory in your Windows NT backup strategy
Using all of the tools we have discussed thus far, you can get any data you wantout of your server However, many companies have data spread across many servers
To get to that multiserver data, you need to link your servers and perform linkedserver queries
Linked Server Queries
A growing number of companies have more than one server from which they need toextract data to formulate reports With all of the queries you have seen thus far, thistask would be very difficult, because all of these SELECT queries are designed to workwith only one server at a time To get data from multiple servers with standard querymethods, you would need to execute SELECT queries on each server and then manu-ally try to combine the results into something meaningful To ease the process of get-
ting result sets that comprise data from multiple servers, there are linked server queries (also known as distributed or heterogeneous queries)
When you perform a query using Query Analyzer, you are asked to log in everytime The process of linking servers allows one SQL Server to log in to another data-base server, just the way you log in with Query Analyzer This allows SQL Server toperform queries on the remote server on behalf of the end user The database server inquestion does not even have to be SQL Server, which means that you can query anAccess or Oracle database with this type of query Two different types of linked server
queries are at your disposal: ad hoc and permanent.
If you are going to use a particular linked server query infrequently, you should use
ad hoc linked server queries The ad hoc queries do not take up space in your base, and they are simple to write The code to perform an ad hoc linked server queryinvolves using the OPENROWSET command OPENROWSET creates a new temporarytable from a foreign database that can be searched by a standard SELECT statement
data-For example, code to run an ad hoc query against the Access version of Northwindlooks as follows:
Trang 13CHAPTER 6 • SELECT QUERIES
232
‘c:\MSOffice\Access\Samples\northwind.mdb’;’admin’;’mypwd’, Orders)
AS AccessGO
The syntax for OPENROWSET is as follows:
sp_addlinkedserver ‘Washington’, ‘SQL Server’
To query the Northwind database on the Washington SQL Server machine, all youneed to do is add it to your SELECT query, as follows:
SELECT * FROM Washington.Northwind Employees
Linking to a non-SQL server is just as easy—it just requires a little more typing.Here’s how to link to the Northwind database on an Access machine named Market-ing on a more permanent basis:
sp_addlinkedserver ‘Marketing’,’Microsoft.Jet.OLEDB.4.0’, ‘OLE DB Providerfor Jet’, ‘C:\MSOffice\Access\Samples\Northwind.mdb’
To query the newly linked Access database, all you need to do is use the following:
SELECT * FROM Marketing.Northwind Employees
Summary
That was a lot of information—but rest assured that you will use everything you haveread here at some point in your illustrious career as a SQL Server guru The first thingyou learned here was how to use a basic SELECT query to retrieve data from a singletable in your database After examining the result sets from the basic queries, you dis-covered that there is just too much information displayed, so you learned how to useWHERE to limit what is returned in the result set
Next, because most databases have more than one table in them, you learned how
to use JOINs to combine the information from multiple tables in a single result set
Trang 14Then, you figured out that the result sets are not in any particular order when theyare displayed, so you learned how to bestow organization upon them using theORDER BY clause
Even with ORDER BY, though, your result sets still didn’t look enough like reports
to be easily read, so you went through the process of adding summary and detailedinformation using GROUP BY with the HAVING, ROLLUP, and CUBE operators
COMPUTE and COMPUTE BY were then used to generate the same detailed andsummary information, just in a slightly different format After that, you learned the
proper use of TOP N to retrieve the top percentage of a group of values, such as the
top 5% of salespeople in a company
Afterward, you found that Full-Text Search could greatly enhance SELECT queries
by allowing you to find words or phrases in your text fields
Finally, you discovered the power of the linked server query, which allows you toaccess data from more than one server at a time during the same query
With SELECT queries under your belt, you are ready to move on to action queries
SUMMARY
P A R TII
Trang 15This page intentionally left blank
Trang 17As you saw in Chapter 6, SELECT queries allow you to retrieve the data from
your database in a flexible manner However, there’s more to using a base than just retrieving existing data There are three other fundamentaloperations you need to be able to perform:
data-• Deleting existing data from tables
• Making changes to existing data in tables
• Inserting new data in tablesFortunately, the T-SQL language provides a mechanism to accomplish all of thesetasks That mechanism is the action query, and in this chapter, you’ll learn how toconstruct and use action queries to perform these three fundamental operations
What Are Action Queries?
Action queries are SQL statements that modify one or more records in an existing
table These statements include:
• DELETE statements, which can delete individual records or even every record in
a table
• TRUNCATE TABLE statements, which delete every record in a table
• UPDATE statements, which can make changes to one or more columns withinone or more records in a table
• UPDATETEXT statements, which can make changes to text or image columns
• WRITETEXT statements, which can insert new values in text or image columns
• INSERT statements, which can insert one or more rows into an existing table
• SELECT INTO statements, which can create an entire new table from existing data
In the rest of this chapter, we’ll explain the syntax of each of these seven types ofstatements and show how you can use them in your own applications
NOTE Action queries work on existing tables To create a new table, you can use aCREATE TABLE statement; to completely destroy a table, you use a DROP TABLE statement.You’ll learn about creating and dropping tables in Chapter 11
Trang 18Delete Queries
There are two different statements that you can use to delete records from an existingtable DELETE statements are the more flexible of the two and allow you to specifyexactly which records you wish to delete When you want to delete every record in atable, you’ll find that TRUNCATE TABLE is faster and uses fewer system resources
Syntax of DELETE
The DELETE statement has a number of options, but the basic syntax is fairly forward:
straight-DELETE[FROM]
Taken piece by piece, here’s what’s in a DELETE statement:
• The DELETE keyword identifies the statement
• The optional FROM keyword can be used if you think it makes the SQL moreunderstandable
• You have to specify either a table name, a view name, or the results of an QUERY, OPENROWSET, or OPENDATASOUCE function as the source for therows to delete OPENQUERY, OPENROWSET, and OPENDATASOURCE are dis-cussed in Chapter 8
OPEN-• The optional WITH clause can be used to provide optimizer hints for the table
Optimizer hints are also discussed in Chapter 8
• The FROM clause has the same syntax and options as the FROM clause in aSELECT statement, which you’ve already seen in Chapter 6
• The WHERE clause has the same syntax and options as the WHERE clause in aSELECT statement
• The OPTION clause can be used to provide further hints, which are also cussed in Chapter 8
dis-DELETE QUERIES
P A R TII
Trang 19CHAPTER 7 • ACTION QUERIES
238
Overall, the DELETE statement is very similar to the SELECT statement In fact, aslong as a SELECT statement doesn’t contain any aggregate functions, you can create aDELETE statement to delete the corresponding rows simply by replacing the SELECTkeyword with the DELETE keyword
Limitations of DELETE
If a DELETE statement uses a view rather than a table as the source for the rows to bedeleted, that view must be an updateable view Updateable views have no aggregatefunctions or calculated columns In addition, a view in a DELETE statement mustcontain precisely one table in its FROM clause (the FROM clause used to create theview, not the FROM clause in the DELETE statement)
NOTE For more on updateable views, see Chapter 13
If you omit the WHERE clause from a DELETE statement, the statement will deleteall of the rows in the target table If you include a WHERE clause, the statementdeletes only the rows that the WHERE clause selects
A DELETE statement cannot remove rows from a table on the nullable side of anouter join For example, consider a DELETE statement with the following FROMclause:
FROM Customers LEFT JOIN Orders ONCustomers.CustomerID = Orders.CustomerID
In this case, the Orders table is nullable That is, the columns from that table willcontain null values for rows corresponding to Customers who have not placed anorder In this case, the DELETE statement cannot be used to delete rows from theOrders table, only from the Customers table
If a DELETE statement attempts to violate a trigger or a referential integrity straint, the statement will fail Even if only one row from a set of rows being deletedviolates the constraint, the statement is cancelled, SQL Server returns an error, and norows will be deleted
con-If you execute a DELETE statement on a table that has an INSTEAD OF DELETEtrigger defined, the DELETE statement itself will not be executed Instead, the actions
in the trigger will be executed for each row in the table that would have been deleted.You’ll learn about triggers in Chapter 15
Trang 20Optionally, if you’d like the SQL statement to be a bit more readable, you caninclude the FROM keyword:
DELETE FROM authors
To delete a single row, you need to include a WHERE clause that specifies that ticular row:
par-DELETE FROM authorsWHERE au_fname = ‘Dean’
Or, with a less restrictive WHERE clause, you can delete multiple rows, but lessthan the entire table:
DELETE FROM authorsWHERE phone LIKE ‘415%’
WARN I NG To check that a DELETE statement will delete the rows you intend it todelete, you might want to use SQL Query Analyzer to examine the results of the corre-sponding SELECT statement (SELECT * FROM authors WHERE phone LIKE '415%'in thecase above)
You can also delete rows from one table based on rows from another table by usingthe second FROM clause Consider the case where you have Customers and Ordersjoined on a common CustomerID field In this case, you could delete all of the Ordersfor Customers who are in France with the following statement:
DELETE FROM OrdersFROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerIDWHERE Customers.Country = ‘France’
DELETE QUERIES
P A R TII
Trang 21CHAPTER 7 • ACTION QUERIES
240
TIP In this case, the corresponding SELECT statement is one that retrieves only the datafrom the Orders table: SELECT Orders.* FROM Customers INNER JOIN Orders ON Cus-tomers.CustomerID = Orders.CustomerID WHERE Customers.Country = ‘France’
You can also use a subquery as the table that you’re deleting from (a subquery is a
SELECT query embedded in another query) For example, consider the problem ofdeleting the first 10 entries in a table, alphabetically sorted You could do that withthe following statement:
DELETE authorsFROM (SELECT TOP 10 * FROM authors ORDER BY au_lname) AS t1
WHERE authors.au_id = t1.au_id
Here the SELECT statement inside the parentheses is a subquery that gives the basicset of rows for the DELETE statement to operate on The result of this subquery is aliased
as t1, and the WHERE clause specifies how to match rows from t1 to the permanentauthors table The DELETE clause then automatically deletes all the matching rows.Finally, consider the problem of deleting all the customers who don’t have any orders.You can do this by using a LEFT JOIN and putting a condition on the Orders table:
DELETE CustomersFROM Customers LEFT JOIN Orders ONCustomers.CustomerID = Orders.CustomerIDWHERE Orders.OrderID IS NULL
This works because the LEFT JOIN creates rows for every customer and fills thecolumns from the Orders table with null values for any customer who has no infor-mation in the joined table
Syntax of TRUNCATE TABLE
The other statement that you can use to delete rows is TRUNCATE TABLE The syntax
of TRUNCATE TABLE is just about as simple as you can get:
TRUNCATE TABLE table_name
That’s it Functionally, TRUNCATE TABLE is the equivalent of a DELETE statement
on a single table with no WHERE clause However, TRUNCATE TABLE is more cient if what you want to do is get rid of all the data in a table, because the DELETEstatement removes rows one at a time and makes individual entries in the transactionlog for each row By contract, the TRUNCATE TABLE statement removes all the rows
effi-by deallocating the data pages assigned to the table, and only these deallocations arerecorded in the transaction log
Trang 22WARN I NG Because TRUNCATE TABLE is an unlogged statement, you must make afull backup after using TRUNCATE TABLE to ensure that your database can be restoredwithout data loss if there is any problem
Limitations of TRUNCATE TABLE
When you use TRUNCATE TABLE to delete all the rows from a table that has an tity column, the identity counter is reset, so that the next row added gets the initialseed value for this column If you want to preserve the counter, so the next row addedgets the next available value that hasn’t yet been assigned, you should use a DELETEstatement instead of a TRUNCATE TABLE statement
Iden-You can’t use TRUNCATE TABLE to delete rows from a table that’s referenced by aforeign-key constraint from another table Again, you must use a DELETE statement
in this case
Deletions made via TRUNCATE TABLE will not activate delete triggers on the table
In some cases, this is a way to get around a limitation of the DELETE statement, butyou must be cautious If you’re expecting a delete trigger to take some automaticcleanup or logging action when rows are deleted, you must avoid TRUNCATE TABLE
If a table is part of a view and the view is indexed, you can’t use TRUNCATE TABLE
on that table If you try, you’ll get error message 3729 (“Could not TRUNCATE TABLE
‘tablename’ It is being referenced by object ‘viewname’.”)
Example of TRUNCATE TABLE
To remove all the data from a table named authors, simply execute:
TRUNCATE TABLE authors
WARNING If you try this statement, be sure you’re trying it on data you can afford tolose All rows will be deleted from the table without any warning
DELETE QUERIES
P A R TII
Trang 23CHAPTER 7 • ACTION QUERIES
242
Update Queries
In most databases, the data stored in tables isn’t static Sure, some data (such as a list
of US state names) rarely or never changes However, other data (such as customeraddress information) is more dynamic The UPDATE statement provides you with themeans to change any or all of the data contained in a table You can write an UPDATEstatement in such a way that it affects only a single field in a single row, or morebroadly so that it calculates changes in a column for every row in a table—or even sothat it makes changes to multiple columns in every row
In addition to the UPDATE statement, there are two specialized statements fordealing with large values stored in text, ntext, or image columns The WRITETEXTstatement replaces a value in one of these columns with an entirely new value, whilethe UPDATETEXT statement can make a change to part of such a column
Syntax of UPDATE
The UPDATE statement has a fairly complex syntax:
UPDATE{
table_name [WITH (table_hint […n])]
| view_name
| OPENQUERY | OPENROWSET | OPENDATASOURCE}
SET{
column_name = {expression | DEFAULT | NULL}
Here’s some information on the various pieces of the UPDATE statement:
• The UPDATE keyword identifies the statement
• You have to specify either a table name, a view name, or the results of an QUERY, OPENROWSET, or OPENDATASOURCE function as the source for the
Trang 24rows to delete OPENQUERY, OPENROWSET, and OPENDATASOUCE are cussed in Chapter 8
dis-• The optional WITH clause can be used to provide optimizer hints for the table
Optimizer hints are also discussed in Chapter 8
• The SET keyword introduces the changes to make
• You can set a column equal to an expression, to its default value, or to null
• You can also set a local variable equal to an expression
• You can combine setting a local variable and a column to the same expression
• You can also set multiple columns in a single SET clause
• The FROM clause has the same syntax and options as the FROM clause in aSELECT statement, which you’ve already seen in Chapter 6
• The WHERE clause has the same syntax and options as the WHERE clause in aSELECT statement
• The OPTION clause can be used to provide further hints, which are also cussed in Chapter 8
dis-Limitations of UPDATE
If you’re using an UPDATE statement to update through a view, the view must beupdateable (of course) In addition, the UPDATE statement can affect only one of thetables in the view
You can’t use an UPDATE statement to update the view in an Identity column Ifyou need to update an Identity column, you’ll need to use DELETE to remove the cur-rent row and then INSERT to insert the changed data as a new row
You can only use an expression that returns a single value in an UPDATE statement
If you use the SET @variable = column = expression form of the SET clause, both
the variable and the column are set equal to the results of the expression This differs
from SET @variable = column = expression = expression (which would set the
variable to the preupdate value of the column) In general, if the SET clause containsmultiple actions, these actions are evaluated left to right
In general, if the UPDATE would violate a constraint on the table, whether that’s
an actual constraint, a rule, the nullability rules for a column, or the datatype settingfor the column, the UPDATE statement is cancelled, and an error is returned If theUPDATE would have updated multiple rows, no changes are made, even if only asingle row would violate the constraint
UPDATE QUERIES
P A R TII
Trang 25CHAPTER 7 • ACTION QUERIES
244
If an expression in an UPDATE statement generates an arithmetic error (for example,divide by zero), the update isn’t performed, and an error is returned In addition, sucherrors cancel the remainder of any batch containing the UPDATE statement
An UPDATE statement that updates a text or image column can update only asingle row
UPDATE statements are logged, which means that all of their data is written to thetransaction log If you’re inserting a large value in a text or image column, you shouldconsider using UPDATETEXT or WRITETEXT instead
If an UPDATE statement that contains columns and variables updates multiplerows, the variables will contain the values for only one of the updated rows (and it’snot defined which row will supply this value)
If an UPDATE statement affects rows in a table that has an INSTEAD OF UPDATEtrigger, the statements in the trigger are executed instead of the changes in theUPDATE statement
WARN I NG If you execute this statement in the pubs database, you’ll change data.For a technique that allows you to experiment with updates without altering data, see thesidebar “Updating within Transactions,” just below