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.

Chapter 10: Views<br />

The preceding syntax just represents the minimum, of course, but it’s still all we need in a large percentage<br />

of the situations. The more extended syntax looks like this:<br />

CREATE VIEW []. [()]<br />

[WITH [ENCRYPTION] [[,] SCHEMABINDING] [[,] VIEW_METADATA]]<br />

AS<br />

<br />

[WITH CHECK OPTION][;]<br />

We’ll be looking at each piece of this individually, but, for now, let’s go ahead and dive right in with an<br />

extremely simple view.<br />

Try It Out Creating a Simple View<br />

We’ll call this one our customer phone list, and create it as CustomerPhoneList_vw in the Accounting<br />

database that we created back in Chapter 5:<br />

USE Accounting;<br />

GO<br />

CREATE VIEW CustomerPhoneList_vw<br />

AS<br />

SELECT CustomerName, Contact, Phone<br />

FROM Customers;<br />

Notice that when you execute the CREATE statement in the Management Studio, it works just like all the<br />

other CREATE statements we’ve done — it doesn’t return any rows. It just lets us know that the view has<br />

been created:<br />

Command(s) completed successfully.<br />

Now switch to using the grid view (if you’re not already there) to make it easy to see more than one<br />

result set. Then run a SELECT statement against your view — using it just as you would for a table —<br />

and another against the Customers table directly:<br />

SELECT * FROM CustomerPhoneList_vw;<br />

SELECT * FROM Customers;<br />

How It Works<br />

300<br />

What you get back looks almost identical to the previous result set — indeed, in the columns that they<br />

have in common, the two result sets are identical. To clarify how <strong>SQL</strong> <strong>Server</strong> is looking at your query on<br />

the view, let’s break it down logically a bit. The SELECT statement in your view is defined as:<br />

SELECT CustomerName, Contact, Phone<br />

FROM Customers;<br />

So when you run:<br />

SELECT * FROM CustomerPhoneList_vw;

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

Saved successfully!

Ooh no, something went wrong!