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.

JOIN Sales.Customer sc<br />

ON pp.BusinessEntityID = sc.CustomerID<br />

UNION<br />

SELECT FirstName + ‘ ‘ + LastName AS Name, pe.EmailAddress<br />

EmailAddress<br />

FROM Person.Person pp<br />

JOIN Person.EmailAddress pe<br />

ON pp.BusinessEntityID = pe.BusinessEntityID<br />

JOIN Purchasing.Vendor pv<br />

ON pp.BusinessEntityID = pv.BusinessEntityID<br />

This gets back just one result set:<br />

Name EmailAddress<br />

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

A. Scott Wright ascott0@adventure-works.com<br />

Aaron Adams aaron48@adventure-works.com<br />

Aaron Allen aaron55@adventure-works.com<br />

…<br />

…<br />

Zachary Wilson zachary36@adventure-works.com<br />

Zainal Arifin zainal0@adventure-works.com<br />

Zheng Mu zheng0@adventure-works.com<br />

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

How It Works<br />

We have our one result set from what would have been two.<br />

<strong>SQL</strong> <strong>Server</strong> has run both queries and essentially stacked the results one on top of the other to create one<br />

combined result set. Again, notice that the headings for the returned columns all came from the SELECT<br />

list of the first of the queries.<br />

Moving on to a second example, let’s take a look at how a UNION deals with duplicate rows — it’s actually<br />

just the inverse of a normal query in that it assumes you want to throw out duplicates. (In your previous<br />

queries, the assumption was that you wanted to keep everything unless you used the DISTINCT<br />

keyword.) This demo has no real-world potential, but it’s quick and easy to run and see how things work.<br />

In this case, we are creating two tables from which we will select. We’ll then insert three rows into each<br />

table, with one row being identical between the two tables. If our query is performing an ALL, then every<br />

row (six of them) will show up. If the query is performing a DISTINCT, then it will only return five rows<br />

(tossing out one duplicate):<br />

CREATE TABLE UnionTest1<br />

(<br />

idcol int IDENTITY,<br />

col2 char(3),<br />

)<br />

Chapter 4: JOINs<br />

109

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

Saved successfully!

Ooh no, something went wrong!