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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

An Alternative INNER JOIN<br />

Let’s do a déjà vu thing and look back at the first INNER JOIN we did in this chapter:<br />

USE AdventureWorks<strong>2008</strong><br />

SELECT *<br />

FROM Person.Person<br />

INNER JOIN HumanResources.Employee<br />

ON Person.Person.BusinessEntityID = HumanResources.Employee.BusinessEntityID<br />

This got us approximately 290 rows back. Instead of using the JOIN, however, let’s rewrite it using a<br />

WHERE-clause–based join syntax. It’s actually quite easy — just eliminate the words INNER JOIN, add a<br />

comma, and replace the ON operator with a WHERE clause:<br />

SELECT *<br />

FROM Person.Person, HumanResources.Employee<br />

WHERE Person.Person.BusinessEntityID = HumanResources.Employee.BusinessEntityID<br />

It’s a piece of cake and it yields us the same 290 rows we got with the other syntax.<br />

This syntax is supported by virtually all major <strong>SQL</strong> systems (Oracle, DB2, My<strong>SQL</strong>, and so on) in the<br />

world today, but can create some ambiguity at what point in the query processing the restriction should be<br />

applied. It is very rare to run into such an ambiguity, but it can happen, so use the JOIN syntax for any<br />

new queries and edit old queries to the new syntax as you are able.<br />

An Alternative OUTER JOIN<br />

Note that the alternative syntax for OUTER joins is only available if you tell <strong>SQL</strong><br />

<strong>Server</strong> you want to run in <strong>SQL</strong> <strong>Server</strong> 2000 compatibility mode (setting the compatibility<br />

level to 80 in the ALTER DATABASE command).<br />

The alternative syntax for OUTER JOINs works pretty much the same as the INNER JOIN, except that,<br />

because we don’t have the LEFT or RIGHT keywords (and no OUTER or JOIN for that matter), we need<br />

some special operators especially built for the task. These look like this:<br />

Alternative ANSI<br />

*= LEFT JOIN<br />

=* RIGHT JOIN<br />

Let’s pull up the first OUTER JOIN we did in this chapter. It made use of the pubs database and looked<br />

something like this:<br />

SELECT sso.SpecialOfferID, Description, DiscountPct, ProductID<br />

FROM Sales.SpecialOffer sso<br />

Chapter 4: JOINs<br />

105

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

Saved successfully!

Ooh no, something went wrong!