Download presentation
Presentation is loading. Please wait.
Published byPatricia Armstrong Modified over 9 years ago
1
1 Agenda – 03/25/2014 Login to SQL Server 2012 Management Studio. Answer questions about HW#7 – display answers. Exam is 4/1/2014. It will be in the lab and the database will be the same one used for the SQL homework assignments. Open book, open notes, open web. Not open people. Introduce SQL View database object. Practice using views.
2
If you did not attend class on 3/13/2014 and did not do SQL Lab 4: (1) Execute the file called “SQLLab4.sql”. It is located on the k: drive in the IS475\LabFiles folder. You will see errors, and then the tables will create and populate. There are six tables created and populated with this file. (2) Look at the content of the tables. The database structure is on the next page.
3
Database for Sample Code in this Presentation 3
4
What is a SQL View? A “virtual” table. A set of SQL statements that creates a result table which can be accessed by other SQL statements. A database object. The code for a view is stored in the database. A view contains no data of its own. A view relies on the data in the base tables used to create the view. A set of stored SQL code. Stores code; not data. 4
5
Let’s say we frequently look at all the information about time in our database and we always convert the time to hours and we always like to include the name of the employee who worked the time as well as the description of the type of work performed: SELECTISNULL(emp.empid,tw.empid) empid, emp.lastname, tw.contractid, tw.startwork, tw.worktypeid, work.description, ISNULL(minutes/60,0) FROMxemp emp FULL OUTER JOINxtimeworked tw ONemp.empid = tw.empid LEFT OUTER JOINxwork work ONwork.worktypeid = tw.worktypeid ORDER BY emp.lastname; 5
6
Creating a view is easy!! CREATE VIEW viewname AS Make sure that all fields in the SELECT list using any kind of function, calculation or conditional logic has an appropriate alias (without spaces in the alias) Remove ORDER BY statement Run it!! 6
7
7 Create a view out of the code CREATE VIEW vEmptime AS SELECTISNULL(emp.empid,tw.empid) empid, emp.lastname, tw.contractid, tw.startwork, tw.worktypeid, work.description, ISNULL(minutes/60,0) hoursworked FROMxemp emp FULL OUTER JOINxtimeworked tw ONemp.empid = tw.empid LEFT OUTER JOINxwork work ONwork.worktypeid = tw.worktypeid; Must eliminate the ORDER BY clause Must add the CREATE VIEW statement Must alias any field with a calculation, aggregation or function
8
How is the view used via SQL? Views are used just as tables are used in SQL. In this example, the join is predefined, so it is easier to write queries to access the data. SELECT * FROMVEmpTime ORDER BYempid; SELECT * FROM VEmpTime WHEREhoursworked = 0; SELECTlastname, startwork, hoursworked FROMVEmpTime WHERE lastname = 'Polanski'; 8
9
Using a view is easy!!! 9 SELECT* FROMvEmpTime WHEREyear(StartWork) = year(getdate()) and month(StartWork) = month(getdate()); SELECTempid, lastname, description, sum(hoursworked) TotalHoursWorked FROMvEmpTime GROUP BYempid, lastname, description ORDER BYlastname
10
Can a view be joined with tables? SELECTVEmpTime.empid, VEmpTime.lastname, VEmpTime.startwork, VEmpTime.contractid, client.name FROMVEmpTime INNER JOINXcontract contract ONcontract.contractid = VEmpTime.contractid INNER JOINxclient client ONcontract.clientid = client.clientid ORDER BYVEmpTime.empid, VEmpTime.contractid desc; Must have a “shared” column to access the data between tables and view – the “shared” column is the same as using a foreign key between tables. 10
11
Let’s go back to that correlated sub-query from Lab 4 (Thursday before Spring Break) 11 SELECTempID, lastname, empOuter.jobtitleID, title, billingrate "Employee Billing Rate", (SELECTAVG(billingrate) FROMxemp empSelect WHEREempOuter.jobtitleID = empSelect.jobtitleID) "Average Billing Rate" FROMxemp empOuter LEFT OUTER JOINxjobtitle ON empOuter.jobtitleID = xjobtitle.jobtitleID WHEREbillingrate > (SELECT AVG(billingrate) FROMxemp empInner WHEREempOuter.jobtitleID = empInner.jobtitleID)
12
12 The relatively complex correlated subquery on the previous page displays those employees who have a billing rate that is greater than the billing rate for their job title
13
Group Functions and Joins are Complex Must have all non-group attributes that are in the SELECT list also in the GROUP BY statement. Difficult to do a group function of a group function. Examples: The maximum of the sum of hours. The minimum of a count of products. Joining multiple tables can yield full or partial cartesian products making it difficult to trouble- shoot the SQL code. 13
14
Create a “view” database object CREATE VIEW vAvgRateByTitle AS SELECTjobtitleID, AVG(billingrate) AverageBillRate FROMxemp GROUP BY jobtitleID; Remember: when using a VIEW, any derived column (calculated, aggregate and/or SQL function) must have an alias
15
Look at the VIEW results and use the VIEW in another query 15 SELECT * FROMvAvgRateByTitle; SELECTemp.empid, emp.lastname, emp.billingrate, emp.jobtitleid, vAvgRateByTitle.AverageBillRate FROMxempemp LEFT JOINvAvgRateByTitle ONemp.jobtitleid = vAvgRateByTitle.jobtitleid WHEREemp.billingrate > AverageBillRate; How would you add the actual job title in the SELECT list?
16
So, what’s the big deal? Views allow you to break down difficult queries into smaller pieces for easier design, coding and debugging. Views allow you to create a layer of abstraction between the data structure and the user or programmer allowing greater security. Programmers do not know the structure of the base tables. Less risk of fraud. Users can see “pre-joined” tables for their queries. Users don’t have to understand the complexity of the actual database. No one sees data that is secure (salary, for example). Views allow you to access the results of aggregate functions more easily. 16
17
Examples of more complex questions Which employee worked the most total hours in February? What is the description of the work type with the most time in the time table and how much time was reported for that work type description? For which contract have we spent the most time? What is the name of the client for whom we worked the most time? What is the name of the client for whom we worked the most time during the month of March in the current year? 17
18
Let’s find out which employee worked the most hours in February of the current year 18 Where do the columns come from (which tables)? What is the basic logic of the query? What is the simplest component that can be written to accomplish the basic logic?
19
Write the basic logic in pseudocode 19 SELECT employee stuff FROM timeworked WHEREsum(timeworked) for month of February in current year = max(sum(timeworked)) for month of February in current year This code doesn’t work!! It is just written to get an understanding of the basic logic necessary to accomplish the query.
20
Use a view to summarize data 20 CREATE VIEW vEmpHours AS SELECT empID, month(startwork) MonthWork, year(startwork) YearWork, sum(minutes/60) TotalHours FROMxtimeworked GROUP BY empid, month(startwork) year(startwork) Look at the result table created by the view: SELECT* FROMvEmpHours
21
21 Look only at those hours in February of the current year: SELECT* FROMvEmpHours WHEREmonthwork = 2 and yearwork = year(getdate()) Create another view from the view (not necessary, but easier to understand the results): CREATE VIEW vFebHours AS SELECT* FROMvEmpHours WHEREmonthwork = 2 and yearwork = year(getdate())
22
Use the view to work on the basic logic 22 SELECT * FROM vFebHours WHERE totalhours = (SELECT MAX(totalhours) FROM vFebHours)
23
Now add the extra data to make the result table “pretty”, piece at a time... 23 SELECTvFeb.empid, firstname + ' ' + lastname "Employee Name", officephone, totalhours FROM vFebHours vFeb LEFT OUTER JOIN xemp emp on vFeb.empid = emp.empid WHERE totalhours = (SELECT MAX(totalhours) from vFebHours)
24
Finish it up! 24 SELECTvFeb.empid, firstname + ' ' + lastname "Employee Name", officephone, title, totalhours FROM vFebHours vFeb LEFT OUTER JOIN xemp emp ON vFeb.empid = emp.empid LEFT OUTER JOIN xjobtitle jt ON jt.jobtitleid = emp.jobtitleid WHERE totalhours = (SELECT MAX(totalhours) from vFebHours)
25
Uses of views Views are used to: Provide easier access to data. Enhance security. Lessen the visible complexity of the database. Views are usually created by the DBA for a defined workgroup of people. Programmers. Users. Users in a specific functional area. 25
26
Time to write a few of your own. 26 1. What is the description of the work type with the most time in the time table and how much time was reported for that work type description? Don’t use the SELECT TOP 1 statement – do this with a view and a sub-query.
27
2. What is the name of the client for whom we worked the most time and how much total time have we worked for that client? This one is a little more complicated because the clientID is not directly in the TimeWorked table. Group the TimeWorked table by contractID and then use the Contract table to get the clientID. Don’t use the SELECT TOP 1 statement in any of the queries. 27
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.