agenda – 03/25/2014
DESCRIPTION
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. - PowerPoint PPT PresentationTRANSCRIPT
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.
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.
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.
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 xemp empFULL OUTER JOIN xtimeworked tw ON
emp.empid = tw.empidLEFT OUTER JOIN xwork workON
work.worktypeid = tw.worktypeidORDER BY emp.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!!
Create a view out of the code
CREATE VIEW vEmptime ASSELECT ISNULL(emp.empid,tw.empid) empid,
emp.lastname,
tw.contractid,
tw.startwork,
tw.worktypeid,
work.description,
ISNULL(minutes/60,0) hoursworkedFROM xemp empFULL OUTER JOIN xtimeworked tw ON emp.empid = tw.empidLEFT OUTER JOIN xwork workON work.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 * FROM VEmpTimeORDER BY empid;
SELECT *FROM VEmpTimeWHERE hoursworked = 0;
SELECT lastname, startwork, hoursworkedFROM VEmpTimeWHERE lastname = 'Polanski';
Using a view is easy!!!
SELECT *FROM vEmpTimeWHERE year(StartWork) = year(getdate()) and month(StartWork) = month(getdate()); SELECT empid,
lastname,description,sum(hoursworked) TotalHoursWorked
FROM vEmpTimeGROUP BY empid,
lastname,description
ORDER BY lastname
Can a view be joined with tables?
SELECT VEmpTime.empid,VEmpTime.lastname,VEmpTime.startwork,VEmpTime.contractid,client.name
FROM VEmpTimeINNER JOIN Xcontract contractON contract.contractid = VEmpTime.contractidINNER JOIN xclient clientON contract.clientid = client.clientidORDER BY VEmpTime.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.
Let’s go back to that correlated sub-query from Lab 4 (Thursday before Spring Break)
SELECT empID,lastname,empOuter.jobtitleID,title,billingrate "Employee Billing Rate",(SELECT AVG(billingrate)
FROM xemp empSelect WHERE empOuter.jobtitleID = empSelect.jobtitleID)
"Average Billing Rate" FROM xemp empOuterLEFT OUTER JOIN xjobtitleON empOuter.jobtitleID = xjobtitle.jobtitleIDWHERE billingrate >
(SELECT AVG(billingrate) FROM xemp empInner WHERE empOuter.jobtitleID = empInner.jobtitleID)
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.
Create a “view” database object
CREATE VIEW vAvgRateByTitleASSELECT jobtitleID,
AVG(billingrate) AverageBillRateFROM xempGROUP BY jobtitleID;
Remember: when using a VIEW, any derived column
(calculated, aggregate and/or SQL function) must
have an alias
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 xemp empLEFT JOIN vAvgRateByTitleON emp.jobtitleid = vAvgRateByTitle.jobtitleidWHERE 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?
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?
Write the basic logic in pseudocode
SELECT employee stuffFROM timeworkedWHERE 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.
Use a view to summarize data
CREATE VIEW vEmpHours ASSELECT empID,
month(startwork) MonthWork,year(startwork) YearWork,sum(minutes/60) TotalHours
FROM xtimeworkedGROUP BY empid,
month(startwork)year(startwork)
Look at the result table created by the view:
SELECT *FROM vEmpHours
Look only at those hours in February of the current year:
SELECT *FROM vEmpHoursWHERE monthwork = 2 and yearwork = year(getdate())
Create another view from the view (not necessary, but easier to understand the results):
CREATE VIEW vFebHours ASSELECT *FROM vEmpHoursWHERE monthwork = 2 and yearwork = year(getdate())
Use the view to work on the basic logic
SELECT * FROM vFebHours WHERE totalhours = (SELECT MAX(totalhours) FROM vFebHours)
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 vFebHours vFebLEFT OUTER JOIN xemp empon vFeb.empid = emp.empidWHERE totalhours = (SELECT MAX(totalhours)
from vFebHours)
Finish it up!
SELECT vFeb.empid,firstname + ' ' + lastname "Employee Name",officephone,title,totalhours
FROM vFebHours vFebLEFT OUTER JOIN xemp empON vFeb.empid = emp.empidLEFT OUTER JOIN xjobtitle jtON jt.jobtitleid = emp.jobtitleidWHERE 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.
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.
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.