1 / 27

Agenda – 03/25/2014

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.

Download Presentation

Agenda – 03/25/2014

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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

  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.

  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: SELECT ISNULL(emp.empid,tw.empid)empid, emp.lastname, tw.contractid, tw.startwork, tw.worktypeid, work.description, ISNULL(minutes/60,0) FROM xempemp FULLOUTERJOIN xtimeworkedtw ON emp.empid=tw.empid LEFTOUTERJOIN xworkwork ON work.worktypeid=tw.worktypeid ORDERBYemp.lastname;

  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!!

  7. Create a view out of the code Must add the CREATE VIEW statement CREATE VIEW vEmptime AS SELECT ISNULL(emp.empid,tw.empid) empid, emp.lastname, tw.contractid, tw.startwork, tw.worktypeid, work.description, ISNULL(minutes/60,0) hoursworked FROM xempemp FULL OUTER JOIN xtimeworkedtw ON emp.empid = tw.empid LEFT OUTER JOIN xwork work ON work.worktypeid = tw.worktypeid; Must alias any field with a calculation, aggregation or function Must eliminate the ORDER BY clause

  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 * FROM VEmpTime ORDER BY empid; SELECT * FROM VEmpTime WHERE hoursworked = 0; SELECT lastname, startwork, hoursworked FROM VEmpTime WHERE lastname= 'Polanski';

  9. Using a view is easy!!! SELECT * FROM vEmpTime WHERE year(StartWork) = year(getdate()) and month(StartWork) = month(getdate()); SELECT empid, lastname, description, sum(hoursworked) TotalHoursWorked FROM vEmpTime GROUP BY empid, lastname, description ORDER BY lastname

  10. Can a view be joined with tables? SELECT VEmpTime.empid, VEmpTime.lastname, VEmpTime.startwork, VEmpTime.contractid, client.name FROM VEmpTime INNER JOIN Xcontract contract ON contract.contractid = VEmpTime.contractid INNER JOIN xclient client ON contract.clientid = client.clientid ORDER BY VEmpTime.empid, VEmpTime.contractiddesc; 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.

  11. Let’s go back to that correlated sub-query from Lab 4 (Thursday before Spring Break) SELECTempID, lastname, empOuter.jobtitleID, title, billingrate "Employee Billing Rate", (SELECTAVG(billingrate) FROM xemp empSelect WHEREempOuter.jobtitleID = empSelect.jobtitleID) "Average Billing Rate" FROM xemp empOuter LEFT OUTER JOIN xjobtitle ON empOuter.jobtitleID = xjobtitle.jobtitleID WHERE billingrate > (SELECTAVG(billingrate) FROM xemp empInner WHEREempOuter.jobtitleID = empInner.jobtitleID)

  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.

  14. Create a “view” database object CREATE VIEW vAvgRateByTitle AS SELECT jobtitleID, AVG(billingrate) AverageBillRate FROM xemp 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 SELECT * FROM vAvgRateByTitle; SELECT emp.empid, emp.lastname, emp.billingrate, emp.jobtitleid, vAvgRateByTitle.AverageBillRate FROM xempemp LEFT JOIN vAvgRateByTitle ON emp.jobtitleid = vAvgRateByTitle.jobtitleid WHERE emp.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.

  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?

  18. Let’s find out which employee worked the most hours in February of the current year 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 SELECT employee stuff FROM timeworked WHERE sum(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 CREATE VIEW vEmpHours AS SELECT empID, month(startwork) MonthWork, year(startwork) YearWork, sum(minutes/60) TotalHours FROM xtimeworked GROUP BY empid, month(startwork) year(startwork) Look at the result table created by the view: SELECT * FROM vEmpHours

  21. Look only at those hours in February of the current year: SELECT * FROM vEmpHours WHERE monthwork = 2 and yearwork = year(getdate()) Create another view from the view (not necessary, but easier to understand the results): CREATE VIEW vFebHours AS SELECT * FROM vEmpHours WHERE monthwork = 2 and yearwork = year(getdate())

  22. Use the view to work on the basic logic 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... SELECT vFeb.empid, firstname+ ' ' + lastname "Employee Name", officephone, totalhours FROM vFebHoursvFeb LEFT OUTER JOIN xempemp on vFeb.empid= emp.empid WHERE totalhours= (SELECT MAX(totalhours) from vFebHours)

  24. Finish it up! SELECT vFeb.empid, firstname + ' ' + lastname "Employee Name", officephone, title, totalhours FROM vFebHoursvFeb LEFT OUTER JOIN xempemp ON vFeb.empid = emp.empid LEFT OUTER JOIN xjobtitlejt 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.

  26. Time to write a few of your own. 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.

More Related