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 4: JOINs<br />

84<br />

Using an INNER JOIN, the result set would look like this:<br />

FilmID FilmName YearMade FirstName LastName<br />

1 My Fair Lady 1964 Rex Harrison<br />

1 My Fair Lady 1964 Audrey Hepburn<br />

2 Unforgiven 1992 Clint Eastwood<br />

Notice that Bogey was left out of this result set. That’s because he didn’t have a matching record in the<br />

Films table. If there isn’t a match in both tables, then the record isn’t returned. Enough theory — let’s<br />

try this out in code.<br />

The preferred code for an INNER JOIN looks something like this:<br />

SELECT <br />

FROM <br />

<br />

[ON ]<br />

This is the ANSI syntax, and you’ll have much better luck with it on non-<strong>SQL</strong> <strong>Server</strong> database systems<br />

than you will if you use the proprietary syntax required prior to version 6.5 (and still used by many<br />

developers today). We’ll take a look at the other syntax later in the chapter.<br />

It is probably worth noting that the term “ANSI syntax” is there because the original foundations of it<br />

were created as part of an ANSI standard in the mid 1980s. That standard has since been taken over by<br />

the International Standards Organization (ISO), so you may hear it referred to based on either standards<br />

organization.<br />

Fire up the Management Studio and take a test drive of INNER JOINs using the following code against<br />

AdventureWorks<strong>2008</strong>:<br />

SELECT *<br />

FROM Person.Person<br />

INNER JOIN HumanResources.Employee<br />

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

The results of this query are too wide to print in this book, but if you run this, you should get something<br />

on the order of 290 rows back. There are several things worth noting about the results:<br />

❑ The BusinessEntityID column appears twice, but there’s nothing to say which one is from<br />

which table.<br />

❑ All columns were returned from both tables.<br />

❑ The first columns listed were from the first table listed.

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

Saved successfully!

Ooh no, something went wrong!