17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3: The Foundation Statements of T-<strong>SQL</strong><br />

<strong>SQL</strong> <strong>Server</strong> still chose the least-cost method of giving us our desired results, but the particular set of<br />

tasks it actually needed to perform changed somewhat because the nature of the query changed.<br />

We can also do our sorting using numeric fields (note that we’re querying a new table):<br />

SELECT Name, SalesPersonID<br />

FROM Sales.Store<br />

WHERE Name BETWEEN ‘g’ AND ‘j’<br />

AND SalesPersonID > 283<br />

ORDER BY SalesPersonID, Name DESC;<br />

This one results in:<br />

Name SalesPersonID<br />

-------------------------------------------------- -------------<br />

Inexpensive Parts Shop 286<br />

Ideal Components 286<br />

Helpful Sales and Repair Service 286<br />

Helmets and Cycles 286<br />

Global Sports Outlet 286<br />

Gears and Parts Company 286<br />

Irregulars Outlet 288<br />

Hometown Riding Supplies 288<br />

Good Bicycle Store 288<br />

Global Bike Retailers 288<br />

Instruments and Parts Company 289<br />

Instant Cycle Store 290<br />

Impervious Paint Company 290<br />

Hiatus Bike Tours 290<br />

Getaway Inn 290<br />

(15 row(s) affected)<br />

Notice several things in this query: We’ve made use of many of the things that we’ve talked about up to<br />

this point. We’ve combined multiple WHERE clause conditions and also have an ORDER BY clause in place.<br />

In addition, we’ve added some new twists in our ORDER BY clause. First, we now have an ORDER BY<br />

clause that sorts based on more than one column. To do this, we simply comma delimited the columns<br />

we wanted to sort by. In this case, we’ve sorted first by SalesPersonID and then added a sub-sort based<br />

on Name. Second, the DESC keyword tells <strong>SQL</strong> <strong>Server</strong> that our ORDER BY should work in descending order<br />

for the Name sub-sort, rather than the default of ascending. (If you want to explicitly state that you want<br />

it to be ascending, use ASC.)<br />

While we usually sort the results based on one of the columns that we are returning,<br />

it’s worth noting that the ORDER BY clause can be based on any column in any table<br />

used in the query, regardless of whether it is included in the SELECT list.<br />

53

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!