Lab– SQL Programming Views, Stored Procedures, Functions

advertisement
L AB – SQL P ROGRAMMING V IEWS , S TORED P ROCEDURES , F UNCTIONS
O VERVIEW
In this lab, we will practice using SQL program units (views, stored procedures, and functions) to create the
external data model. We will use the following concepts from class:

Views.

Stored Procedures

Functions

The Execute command to run a stored procedure
L EARNING O BJECTIVES
Upon completion of this learning unit you should be able to:

Describe views, functions, stored procedures, and triggers.

Explain the importance of procedural language constructs in the SQL environment.

Demonstrate how to solve business problems with SQL programming.

Describe the many advantages of the external data model.
L AB G OALS
This lab consists of 3 parts:
1.
The first part will set the stage for the lab, giving you the background you need to understand the external
portion of the data model.
2.
In the second part, you will mainly respond by following along and typing in the provided SQL statements.
3.
In part three, you will have to solve problem using SQL based on the provided requirements. Much of the
details are left for you to figure out on your own. 
Once again, you will have to hand in pieces from parts 2 and 3 on this week’s learning assessment.
W HAT
1.
YOU WILL NEED TO BEGIN
Connect to your SQL Server instance.
P ART 1: T HE F UDGEMART D ATABASE S CHEMA (R E -R ELOADED )
Throughout the semester we will use several different case studies to help reinforce the concepts we learn in class.
One of the recurring case-studies we will use in class and the labs is the Fudgemart database. This database
supports the business operations of a fictitious mega-store retailer and retailer called Fudgemart. The Fudgemart
1 / 12
database supports all aspects of the business from human resources and payroll to sales transactions, and ecommerce. In each lab we will add new database objects and data to the Fudgemart schema.
1A: F UDGEMART I NTERNAL M ODEL (S CHEMA )
By now, you’ve seen this diagram a few times and should be quite familiar with it. The reason we call this an
internal model is because it represents how we actually store data for Fudgemart. There’s one critical element the
internal model doesn’t show us - how our applications use the Fudgemart schema to store and retrieve data. This is
the responsibility of the external model and the topic of today’s lab.
1B: F UDGEMART E XTERNAL M ODEL
The external data model represents the interface applications will use to store and retrieve data in the database. It
is an abstraction of the internal model; hiding the complexity from the developers who are tasked with building
the user-interface for the database.
The following table outlines a sample subset of a typical external model which might be required for the
Fudgemart database. Notice how the external model looks more like business processes than procedures or rules.
In the external model implementation, we use:
2 / 12



Stored Procedures to represent the business logic or processes in our database, like Fill Out Timesheet, or
Give Department Raise. Stored procedures insert, update, or delete data from multiple tables.
Views to represent logical displays of information, like Vendors without products or Employees and their
Managers. Views are stored SELECT statements.
Functions to perform custom calculations over our data, like Total Employee Hours Worked or Vendor
Product Count. Functions are like procedures, but they return one value, and can be used in SQL SELECT
statements.
Here’s an Example of the Fudgemart External Model. Some of these portions we will implement in this lab:
Scope
Fudgemart Employees
Fudgemart Products
Fudgemart Vendors
Task (What it does)
Add new employee
Give Raise to Department
Terminate employee
Total Employee Hours Worked
List of Employees and their Managers
Add A new Product
Increase Retail Price For Department
Delete product
De-Activate product
Display active products
Vendor Product Count
SQL Object Name
p_fudgemart_hire_employee
p_fudgemart_give_raise_to_department
p_fudgemart_terminate_employee
f_fudgemart_total_hours_worked
v_fudgemart_employees_and_managers
p_fudgemart_add_product
p_fudgemart_increase_retail_price_for_dept
p_fudgemart_delete_product
p_fudgemart_deactivate_product
v_fudgemart_display_active_products
f_fudgemart_vendor_product_count
NOTE: DO NOT ATTEMPT TO CREATE THE EXTERNAL MODEL AT THIS TIME. THIS WILL BE DONE
IN LATER PORTIONS OF THE LAB.
3 / 12
P ART 2: W ALK -T HROUGHS
In this part, we will explore stored procedures, views and functions step by step. This will give you an opportunity
to learn as you go by typing in prepared commands and seeing how they execute.
2.a) Creating a stored procedure
Let’s write an SQL stored procedure called p_fudgemart_add_product which implements logic for adding a new
product to the fudgemart_products table. It is important to note the procedure doesn’t add any data; it defines a
process which adds data.
Type the following:
These are the parameters of
the procedure. They
represent the data required
to execute the procedure
properly.
This returns product_id which was inserted
Execute the code and create the procedure. If everything goes well you should see this in the messages window.
TIP: You can also query INFORMATION_SCHEMA to see your if your procedure is there. Try this:
And you will see this output:
4 / 12
FYI ONLY: Finally, since the procedure is meta-data, you can use the ALTER and DROP DDL commands to change or
delete the procedure. For example, if you create the procedure incorrectly, you can always execute
DROP PROCEDURE p_fudgemart_add_product to delete the procedure, then execute your create procedure code
again. (No need to do this, it’s only an FYI.)
2.b) Running a stored procedure using the execute statement
Now let’s execute the procedure and add a new product, Stanlee’s Monkey-Wrench. To do this we need to supply
data for each parameter the procedure requires. Try this:
Notice the data after the procedure name appears in the same order as our accepted parameters in the
procedure’s definition. Also notice how much cleaner and simpler this looks as opposed to the equivalent INSERT
statement.
After you press [F5] to execute it you should see:
This tells us the product was inserted into the fudgemart_products table.
Let’s query the table and find this new product. Try this:
And if your procedure did its job you should see this output:
(NOTE: your product_id and product_add_date might be different, of course)
IMPORTANT: If your procedure is not working properly, troubleshoot your create procedure statement in 2.a. To fix
any problems, you will need to drop the procedure, execute the fixed create procedure statement again, then
repeat the steps in 2.b.
2.c) Advanced procedure execution: Specifying parameters and getting return values.
As we’ll see in this next example, SQL allows you to call the procedure and specify the parameters by name. This
looks cleaner and eliminates the need for us to remember the order of the parameters of the procedure. We’ll also
see how we can obtain and use the value that our procedure returns. Try this:
5 / 12
After you execute this script you will see the new product inserted:
IMPORTANT: The @product_id variable is playing an important role in this example. In this case it gets set to the
return value of the executing procedure, and then we use it to find the exact row which was inserted. This is a much
more reliable approach than our method in 2.b. Using the select top 1 approach only works if you happen to
execute the procedure and the select sequentially. In a high-volume multi user environment this is next to
impossible.
2.d) Creating a view
Views are stored SQL SELECT statements. They are virtual tables which help us simplify the retrieval of complex
information. In this step, we’ll put that to practice and create the v_fudgemart_display_active_products view.
Try this:
After you execute this code, you should see:
You don’t you see the output of the select statement because the create view statement only defines a virtual table
based on the SQL statement.
TIP: You can query INFORMATION_SCHEMA to verify you view definition is there. Try this:
6 / 12
And you should see this output, showing you your view is there.
2.e) Using your view in a SELECT statement
Since views are virtual tables, you access your view as you would a table – using the SELECT statement. For
example, this statement list vendors and active products supplied to the ‘Hardware’ department. Try this:
NOTE: You can join views to other tables or views.
2.f) Creating a user-defined function
At this point you’re undoubtedly familiar with functions. For example the LEN() function retrieves the length of text
data:
And when you execute this SQL you see this output:
If you want to define your own function, you’re in luck because SQL provides a means for creating just that. You can
then use the functions you create in other SQL constructs (just like you do with the built-in functions).
A user-defined function is like a stored procedure in that it takes 0 or more input parameters and does something
with those parameters. Functions are different from stored procedures in that they:
1.
2.
Do not manipulate data ( no INSERT, UPDATE or DELETE statements allowed)
Must return a value.
Here’s a function definition for “product markup.” Try this:
7 / 12
Execute the code and create the function. If everything goes well you should see this in the messages window.
TIP: You can also query INFORMATION_SCHEMA to see if your function is there. Try this:
And you will see this output:
2.f) Using (aka calling) user-defined function
Creating your own function is like buying a hammer for your toolbox; it doesn’t serve a purpose until you use it. The
act of using a function is known as a function call. Here’s a simple example of calling our function we made in 2.e.
Try this:
And of course you should see the output:
8 / 12
Functions are often called in-line with a SELECT statement, such as this one which lists the prices and markup of
‘Soney’ products in the ‘Electronics’ department. Try this:
you should see this output:
9 / 12
P ART 3: O N Y OUR O WN
In this part you will attempt to write SQL statements to create and then execute views, stored procedures and
functions.
3.a) Create an SQL view called v_fudgemart_employee_managers which displays all the employee information for
only those employees who supervise others. In other words if you’re not a supervisor, you should not appear in
the list. HINT: You should try to write the SQL SELECT statement first, and when you think it’s correct execute it
with the create view statement.
The correct SQL for the view logic should display output like this:
3.b) Use v_fudgemart_employee_managers to write an SQL statement which displays name, title, department,
and wage of all supervisors making more than $19/hr who are not the CEO. Sort by hourly wage, like this:
3.c) Create a stored procedure titled p_fudgemart_markup_retail_by_department which when given the
following parameters:


@department varchar(20)
@amount money
The procedure will update the current retail price and add @amount for all products in that @department.
3.d) Write SQL which uses the stored procedure you created in 3.c) to markup All Clothing by $2.50 and all
Housewares by $3.75 HINT: you will need to execute the stored procedure twice.
Here’s a sample of the output so you can verify the stored procedure worked correctly.
10 / 12
3.e) Create a stored procedure titled p_fudgemart_deactivate_product which when given a product’s ID will then
update that product so it is no longer active.
3.f) Write an SQL script which uses the stored procedure you created in 3.e) to deactivate the ‘Slot Screwdriver’
and ‘Monkey-Wrench’ products you added in steps 2.b and 2.c.
HINT: Since the procedure accepts product_id and not product_name, you will need to first use a SELECT
statement to retrieve the product_id by searching the product’s name, and store that in a variable.
3.g) Write an SQL SELECT statement v_fudgemart_display_active_products from 2.d to prove you deactivated the
two products in 3.f) You can accomplish this by only showing the ‘Hardware’ department. Here’s my sample
output… notice it’s missing ‘Slot Screwdriver’ and ‘Monkey-Wrench’ products:
11 / 12
3.h) Write an SQL function called dbo.f_fudgemart_vendor_product_count which given a @vendor_id as input
will return the count of products that vendor supplies. HINT: your function should return the output of a SELECT
statement which counts the products for @vendor_id.
3.i) Write SQL to create a view called v_fudgemart_vendors which displays all rows and columns from
fudgemart_vendors and includes a column called vendor_product_count which calls the function you created in
3.h) Output of the view when executed in a select statement should look like this:
3.j) Write an SQL SELECT statement that uses v_fudgemart_vendors to display all vendors supplying less than 5
products. Here’s sample output:
12 / 12
Download