See Books Online formore details.For example, you could define a function named TwoTimes in the following way: CREATE FUNCTION TwoTimes @input int=0 RETURNS intAS BEGINRETURN 2 * @input
Trang 1TABLE 5.8: SQL SERVER DATEPART CONSTANTS
PRINT DATEADD(d, 3, GETDATE())
WARNING The datepart constants are not strings and thus should not be enclosed
in single quotes
Here’s the full list of available date and time functions:
• DATEADD adds time to a date
• DATEDIFF reports the number of dateparts between two dates
• DATENAME extracts textual names (for example, February or Tuesday) from
a date
• DATEPART returns the specified datepart from a specified date
• DAY returns the day from a date
• GETDATE returns the current date and time
• MONTH returns the month from a date
Trang 2Mathematical Functions
SQL Server supplies almost two dozen mathematical functions for manipulating ger and floating-point values These functions include all the common functions thatyou’d naturally expect to find in any programming language Table 5.9 lists the avail-able mathematical functions
inte-TABLE 5.9: MATHEMATICAL FUNCTIONS IN T-SQL
FLOOR Largest integer smaller than the expression
LOG10 Base 10 logarithm
POWER Exponentiation operatorRADIANS Converts degrees to radiansRAND Random number generatorROUND Rounds floating-point numbers by precisionSIGN Sign of the expression
Trang 3TIP SQL Server uses radians to measure angles for trigonometric functions.
System and Metadata Functions
System and metadata functions return internal information about SQL Server and thedata it’s storing Most of these functions are pretty obscure, and you can find a full list
in the T-SQL help in Books Online However, you might find a few of the followingfunctions useful in your databases:
• The CONVERT function converts one type of data to another (for example, ger to character)
inte-• The CURRENT_USER function returns the name of the current user (the onerunning the SQL batch)
• The ISDATE function will tell you whether its input represents a valid date
• The ISNULL function replaces any null value with a specified replacementvalue
• The ISNUMERIC function will tell you whether its input is a number
Figure 5.8 demonstrates the use of these functions in SQL Query Analyzer
Trang 4CREATE FUNCTION [owner_name].function_name
Trang 5NOTE This definition has been simplified somewhat In particular, we’ve omitted theclauses you’d use to return a table from a user-defined function See Books Online formore details.
For example, you could define a function named TwoTimes in the following way:
CREATE FUNCTION TwoTimes( @input int=0 )
RETURNS intAS
BEGINRETURN 2 * @inputEND
After it’s been created, you could call this function as part of a SELECT statement:
SELECT OrderID, dbo.TwoTimes(Quantity) AS ExtraFROM [Order Details]
Figure 5.9 shows the result set from this query Note that you need to specify theowner of the function (by default, the creating user—in this case, dbo, the owner ofthe database) when you call the function, even if you don’t specify the owner whenyou create the function
NOTE You’ll learn more about the SELECT statement in Chapter 6
Trang 6Using Query Analyzer
In addition to simply executing queries, Query Analyzer offers some additional tionality to make it both easier to use and more powerful In this section, you’ll learnhow to create, save, and retrieve queries; how to view results in several formats; and
P A R TII
Trang 7how to view the execution plan of a query, which is a list of the actions that SQLServer will undertake to deliver the results of the query.
Creating a Query
You’ve already learned how to create a query to test arbitrary SQL statements, but let’sreview the steps here:
1 Launch Query Analyzer from the Start menu by choosing Programs ➢ Microsoft
SQL Server ➢ Query Analyzer
2 Choose the SQL Server that you want to connect to from the combo box This
box will show servers with which you’ve recently connected To see otherservers on your network, click the Browse button You can also use the specialname “(local)” to connect to a server on the computer that you’re using
3 Either click the Windows NT Authentication option button or click the SQL
Server Authentication option button, and supply your SQL Server username andpassword If you don’t know how to log on, try Windows NT Authenticationfirst, before you call your database administrator We recommend this optionfor all new installations of SQL Server
4 Click OK to log on to the server
5 A new query window appears You can select a database to use from the combo
box on the main Query Analyzer toolbar You can also type in as many SQLstatements as you’d like to execute
6 Click the Execute Query button or press F5 to see the results.
You can also use the New Query button on the toolbar to open additional querywindows Query Analyzer will let you open an almost unlimited number of windows,
so you don’t have to lose one set of results to try something else
Saving a Query
Query Analyzer lets you save SQL batches for later This is useful for complex queriesthat you might want to run again in the future It’s also useful if you need to keeptrack of versions of a SQL batch during development; you can save the SQL batch anduse a source code control tool such as Visual Sourcesafe to store it For example, youmight have a query that gives you aggregate sales results by joining half a dozentables from your sales database Once you’ve perfected the query, you’ll want to save
it so you don’t have to type in the complex SQL code again the next time that youwant to see current results
Trang 8To save a query, choose File ➢ Save from the Query Analyzer menu or click theSave button You’ll need to supply a filename, of course By default, Query Analyzeruses SQL as an extension for queries
Opening a Saved Query
To open a previously saved query, choose File ➢ Open from the Query Analyzer menu
or click the Open button Browse to the query you want to open and click OK Thequery will be displayed in the current query window, and you’ll be able to execute itimmediately
Viewing Results
Query Analyzer lets you view results in two formats The first format, results in text, isthe format that we’ve used for all of the examples so far in this chapter This format ismost useful for queries that return only a bit of information
The other format is to view the results in a grid This is useful if the query returns aset of records Figure 5.10 shows a set of results in a Query Analyzer grid
P A R TII
Trang 9TIP As you can see in Figure 5.10, white space is generally not significant in the T-SQLlanguage You can insert new lines, spaces, and tabs to make your SQL statements morereadable.
You can also select Query ➢ Results to File to save the results instead of seeingthem immediately on-screen
Viewing the Execution Plan
Query Analyzer can also show you the execution plan for any query The executionplan is the set of steps that SQL Server will use to execute the query This information
is useful because each step will show its estimated relative cost (in time) You can usethis tool to locate bottlenecks in your applications and to help you make changes toslow queries to make them faster To see the execution plan for a query, select Query
➢ Display Estimated Execution Plan or use the Ctrl+L shortcut
Figure 5.11 shows the execution plan for a query Each step is represented by anicon If you make the mouse hover over an icon, you’ll see detailed information forthat step
FIGURE 5.11
Viewing a query’s execution plan
Trang 10N OTE There’s more information on using execution plans to optimize queries in Chapter 26.
Viewing a Server Trace
Query Analyzer can show you exactly which operations were performed on the serverwhen executing a query This is similar to the tracing provided by SQL Server Profiler,which we mentioned in Chapter 3 To see a server trace for a query, select Query ➢Show Server Trace Figure 5.12 shows a sample server trace
com-Using SQL Server Enterprise Manager
SQL Query Analyzer is not the only tool that will let you execute SQL statements
You can also use the tools within SQL Server Enterprise Manager to evaluate queries
To do so, you need to save the queries as either views or stored procedures within adatabase, so this method is less useful for ad hoc exploration of the language On theother hand, the visual designer for views makes it easy to create quite complex queries
P A R TII
Trang 11To launch SQL Server Enterprise Manager, choose Programs ➢ Microsoft SQLServer ➢ Enterprise Manager from the Start menu This will open an instance ofMicrosoft Management Console, with a treeview of SQL Servers and their contentsalready loaded You can expand the treeview to navigate to any part of any database
on any server that you have permissions to use
N OTE For more information about SQL Server Enterprise Manager, see Chapter 9
Creating a View
A view is a SQL Server SELECT statement that’s been saved in a database A view can
be used to retrieve data from one or more tables, and to summarize, sort, or filter thisdata You’ll learn more about views in Chapter 13 Until then, here’s how you can cre-ate a very simple view within SQL Server Enterprise Manager:
1 Select the Views node in the treeview for the database that you want to query.
2 Click the New button on the toolbar.
3 Right-click in the top pane of the view and choose Add Table Select the table
that contains the data of interest and click Add, then click Close
4 Check the columns in the table that contain the data you want to view.
5 Click the Run button to see the results of the view.
Figure 5.13 shows a simple view in SQL Server Enterprise Manager
Trang 12FIGURE 5.13
A SQL Server view
The view designer consists of four panes:
• The diagram pane shows the tables and columns that the view is using toretrieve data
• The grid pane shows column aliases, sorts, and criteria
• The SQL pane shows the SQL statement that the view is creating
• The results pane shows the results of the view
Changes in any of these panes are reflected in the other panes For example, if youcheck a new field in the diagram pane, that field will show in the grid pane and in theSQL statement in the SQL pane
P A R TII
Trang 13TI P If you experiment with the view designer, you’ll find that you can also select datafrom multiple tables at the same time You’ll find the view designer to be especially useful
as you work through the SELECT statement syntax in Chapter 6
Creating a Stored Procedure
You can also create a stored procedure to execute arbitrary SQL statements using SQLServer Enterprise Manager Unlike a view, a stored procedure can contain multipleSQL statements, so in that way it’s similar to the queries you’ve seen in SQL QueryAnalyzer You’ll learn more about stored procedures in Chapter 14
To create and execute a simple stored procedure:
1 Select the Stored Procedures node in the treeview for the database that you want
to query
2 Click the New button on the toolbar.
3 Replace the “[PROCEDURE NAME]” placeholder in the Stored Procedure
Proper-ties dialog box with the name you’d like to use for this stored procedure
4 Type the SQL statements that make up the stored procedure Click the Check
Syntax button if you’d like to verify that your SQL code is correct Figure 5.14shows this step of defining the stored procedure
FIGURE 5.14
Defining a stored procedure
Trang 145 Click OK to save the stored procedure.
6 Launch SQL Query Analyzer.
7 Type the name of the stored procedure into the SQL Query Analyzer query
win-dow and execute it
Figure 5.15 shows the results of executing the stored procedure that you justdefined
FIGURE 5.15
Results of a stored procedure
WARN I NG There’s no way to view results of a stored procedure within SQL ServerEnterprise Manager
Using OSQL
You may sometimes want to see the results of a SQL statement without any of theoverhead of a graphical tool In those cases, you can use OSQL to execute your SQLstatement OSQL is a command line tool that takes input as text and delivers itsresults right to the command prompt
Figure 5.16 shows the use of OSQL to retrieve the results of a query in the wind database Here, the -d argument tells OSQL the name of the database, the -Qargument contains the SQL statement to execute, and the -E argument specifies thatOSQL should use Windows NT integrated security
P A R TII
Trang 15FIGURE 5.16
Using OSQL
OSQL is a rather powerful utility, if you can remember all of its command lineoptions As you can see in this example, if an option requires more information, it’ssupplied immediately after the argument Table 5.10 lists all of the arguments thatyou can use with OSQL
TABLE 5.10: OSQL ARGUMENTS
-a packet_size Specifies packet size to use when talking to the server If
you’re sending a very long batch, you may wish to increasethis from the default size of 512
error occurs
-c command_terminator Specifies an end of batch marker By default, this is GO
-d database Uses the specified database
-D datasourcename Uses the specified ODBC Data Source Name (DSN) to
con-nect to a database The DSN must point to a SQL Serverdatabase
-h rows Sets number of rows to print before repeating column
headers
Trang 16TABLE 5.10: OSQL ARGUMENTS (CONTINUED)
-H workstation Sets the workstation name to use when communicating
with the server
-I input_file Designates a file containing SQL statements to execute
-l timeout Sets number of seconds to wait for a login to complete
-m error_level Sets minimum severity error to display
-o output_file Designates a file to create or overwrite with results
-O Disables new features so OSQL acts like the defunct ISQL
utility
-p Prints performance statistics when the query is completed
-R Uses local client settings when displaying numbers, dates,
and currency
-q “query” Executes the supplied query, but does not exit OSQL
-Q “query” Executes the supplied query and immediately exits OSQL
-r0 Sends error messages to the screen even when piping
results to a file
-s separator Sets a separator character to use between columns By
default, this is a blank space
-S server Sets the server with which to connect If this is not
sup-plied, OSQL uses the local server
-t timeout Sets the number of seconds to wait for results before
abort-ing a batch
-U login_id Designates the SQL Server login ID
-w width Sets the number of columns to print before wrapping
output
WARNING OSQL arguments are case-sensitive
P A R TII
Trang 17This chapter has introduced you to the basics of the Transact-SQL programming guage, which is the native language of SQL Server You learned about SQL standardsand compatibility, and how to configure SQL Server for various levels of compatibil-ity You’ve also seen T-SQL datatypes and functions, as well as some of the tools thatwill let you execute T-SQL batches
lan-Now it’s time to move on to the most important statement in the SQL language,the SELECT statement The SELECT statement is used to retrieve data from databasetables, and is both complex and flexible You’ll learn about this powerful statement inthe next chapter
Trang 18CHAPTER 6
SELECT Queries
F E A T U R I N G : Using Basic SELECT Queries 188
Turning Result Sets into Reports 201 Full-Text Searching 217 Linked Server Queries 231
Trang 19Y ou now have the knowledge you need to create databases and fill them
with data, but that knowledge is useless without the ability to pull that databack out in a meaningful fashion, a fashion that is well-organized and easy
to read To do this, you must understand the SELECT statement and its ous options
vari-In this chapter, we will discuss the various ways that you can get your data fromone or more tables by using joins We’ll also look at how to limit the data that isreturned by using the WHERE clause Once you have the data you want, we’ll showyou how to organize it by using such clauses as GROUP BY, HAVING, COMPUTE,
COMPUTE BY, TOP N, ROLLUP, and CUBE.
After SELECT queries are mastered, we’ll move into Full-Text Search, a marveloustool for searching through massive amounts of text with accuracy Finally we’ll dis-cover how to make all of this happen when the data spans more than one server byusing linked server queries So hold on, it’s going to be quite a ride
Using Basic SELECT Queries
As was already mentioned, SELECT queries are the primary method for reading thedata that is stored in your tables These queries can be very complex (as you will soonsee) or very simple The simplest of SELECT queries is one that pulls all of the data out
of a table and displays it in no particular order In fact, let’s take a gander at just such
a query—the following example will display all of the records in the authors table ofthe pubs database:
1 Open Query Analyzer in the SQL Server 2000 group in Programs on the Start
menu
2 Connect using Windows NT Authentication.
3 Type the following code:
USE pubsSELECT * from authors
4 Click the green arrow or press CTRL+E to execute You should see the results
shown in Figure 6.1
Trang 20data-and test out your SQL skill set.
This query returned every single record and every single column from the authorstable That would be fine if you really needed to see all of this information, but that isseldom the case In fact, it is recommended that you do not use such queries regularly
because they cause SQL Server to perform a table scan A table scan occurs when SQL
Server must read every record of your table to return a result set, which creates a bit of
a strain on your server It is much better to limit the information returned by theSELECT query The first bit of information to limit is the number of columns that arereturned in your result set by listing them in the SELECT query This next set of stepswill show you how to limit the number of columns that are returned by a SELECTquery by adding a list of columns to the query:
1 Click the New Query button on the toolbar just above your query—it looks like
a piece of paper with a folded corner at the far left
P A R TII
Trang 212 In the new windows, execute the following code:
USE pubsSELECT au_lname, au_fname, phone FROM authors
3 Click the green arrow or press CTRL+E to execute You should see the results
shown in Figure 6.2
FIGURE 6.2
Limiting the columns returned by SELECT can make your result sets easier to read.
Compare the result set from Figure 6.2 with the result set in Figure 6.1 and noticethe difference This time you listed the columns that you wanted to see: au_fname,au_lname, and phone Because you supplied a list of columns, the SELECT statementreturned only the information from the columns listed Now you’re making progress,but you still have too much information because you are still retrieving every singlerecord in the table Let’s try limiting the number of records that are returned byemploying the WHERE clause
Limiting Records with the WHERE Clause
Trang 22returned because you probably do not need to see all of them By using the WHEREclause with a SELECT query, you can restrict the number of records that are returned
by instructing SQL to return only records that meet certain criteria For example, pose that you want to see only authors with a last name of White By using theWHERE clause, you can instruct SQL to return only those records In fact, let’s try thatvery clause here:
sup-1 Click the New Query button on the toolbar just above your query—it looks like
a piece of paper with a light on it at the far left
2 In the new windows, execute the following code:
USE pubsSELECT au_lname, au_fname, phone FROM authors
WHERE au_lname = ‘White’
3 Click the green arrow or press CTRL+E to execute You should see the results
shown in Figure 6.3
FIGURE 6.3
Use the WHERE clause
to limit the number of records returned by a SELECT query.
You should have only one record in the result set shown in Figure 6.3, the record inwhich au_lname = 'White' By using the WHERE clause, you were able to restrict the
P A R TII
Trang 23number of records to only the one record you wanted to see Now let’s get a little fancierwith the WHERE clause This time you’re going to find everyone except Mr White.
1 Click the New Query button on the toolbar just above your query—it looks like
a piece of paper with a light on it at the far left
2 In the new windows, execute the following code:
USE pubsSELECT au_lname, au_fname, phone FROM authors
WHERE au_lname <> ‘White’
3 Click the green arrow or press CTRL+E to execute You should see the results
shown in Figure 6.4
FIGURE 6.4
The <> (not equal) operator with the WHERE clause can be used to further refine a SELECT query.
Now scroll through that result set (as shown in Figure 6.4) and see whether youcan find anyone with a last name of White They’re just not there, are they? That isbecause you threw in the <> operator, which means not equal Essentially you told
Trang 24the last name of Ringer in the database If you base your search on only the last-namecolumn, you will return all of the Ringers in the database, which is not a very cleansolution If you need to base your query on more than one column (first and lastname, for example), you need to use the AND clause In this next example, you aregoing to first verify that there is more than one Ringer in the database by basing yoursearch on a single column (au_lname) and then narrow the search by searching ontwo columns (au_fname and au_lname) using the AND clause:
1 Click the New Query button on the toolbar just above your query—it looks like
a piece of paper with a light on it at the far left
2 In the new windows, execute the following code:
USE pubsSELECT au_lname, au_fname, phone FROM authors
WHERE au_lname = ‘Ringer’
3 Click the green arrow or press CTRL+E to execute—notice that you get two
records in the result set
4 Execute the following code to restrict the result set even further:
USE pubsSELECT au_lname, au_fname, phone FROM authors
WHERE au_lname = ‘Ringer’ and au_fname = ‘Anne’
P A R TII
Trang 25In the first query listed, you found more than one Ringer in the database Becauseyou were interested in only Anne, you were able to screen out all of the unwantedrecords by combining the first- and last-name columns in your search by using theAND clause But wait, it gets better.
How many times have you forgotten the exact spelling of someone’s last name?That happens to most of us and can cause some problems with querying Because theoperators you have been working with thus far (<> and =) require exact spelling forthe search criteria, you would need to remember the exact spelling If you cannotremember the exact spelling, but you can remember small sections (starts with St, forinstance), you can use the LIKE operator to fill in the blanks
The LIKE operator works with wild-card characters that are used to fill in the acters that you don’t remember The % wild-card character can be used to fill in anynumber of characters and can be used anywhere in the clause For example, if youuse the % wild card at the front (%st), your query will retrieve any values that end in
char-ST, no matter how many characters are in front of the ST You could also have placedthe wild cards at the front and back (%st%) and returned values that had ST any-where in the value You also have the ? character, which is used to replace a singlecharacter in the value For instance, if you searched for ST?, your query would returnSTY and STU, but not STIE, because the latter has four characters, and you are specif-ically searching for three character values starting with ST
In the following example, you will specifically search for anything that begins with
ST to demonstrate the power of the LIKE operator:
1 Click the New Query button on the toolbar just above your query—it looks like
a piece of paper with a light on it at the far left
2 In the new windows, execute the following code:
USE pubsSELECT au_lname, au_fname, phone FROM authors
WHERE au_lname LIKE ‘St%’
3 Click the green arrow or press CTRL+E to execute—notice that you get two
records in the result set (see Figure 6.5)