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.

HireDate,<br />

TerminationDate,<br />

ManagerEmpID,<br />

Department<br />

FROM Employees;<br />

We are now ready to let everyone have access — directly or indirectly — to the data in the Employees<br />

table. Users who have the “need to know” can now be directed to the Employees table, but we continue<br />

to deny access to other users. Instead, the users who do not have that “need to know” can have access to<br />

our Employees_vw view. If they want to make use of it, they do it just the same as they would against a<br />

table:<br />

SELECT *<br />

FROM Employees_vw;<br />

Views as Filters<br />

Chapter 10: Views<br />

This actually gets into one of the sticky areas of naming conventions. Because I’ve<br />

been using the _vw suffix, it’s pretty easy to see that this is a view and not a table.<br />

Sometimes, you’d like to make things a little more hidden than that, so you might<br />

want to deliberately leave the _vw off. Doing so means that you have to use a different<br />

name (Employees is already the name of the base table), but you’d be surprised<br />

how many users won’t know that there’s a difference between a view and a table if<br />

you do it this way.<br />

This will probably be one of the shortest sections in the book. Why? Well, it doesn’t get much simpler<br />

than this.<br />

You’ve already seen how to create a simple view — you just use an easy SELECT statement. How do we<br />

filter the results of our queries? With a WHERE clause. Views use a WHERE in exactly the same way.<br />

Let’s take our Employees_vw view from the last section, and beef it up a bit by making it a list of only<br />

current employees. To do this, only two changes need to be made.<br />

First, we have to filter out employees who no longer work for the company. Would a current employee<br />

have a termination date? Probably not, so, if we limit our results to rows with a NULL<br />

TerminationDate, then we’ve got what we’re after.<br />

The second change illustrates another simple point about views working just like queries — the column(s)<br />

contained in the WHERE clause do not need to be included in the SELECT list. In this case, it<br />

doesn’t make any sense to include the termination date in the result set as we’re talking about current<br />

employees.<br />

303

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

Saved successfully!

Ooh no, something went wrong!