sql: views and advanced stored prcedures
DESCRIPTION
a basic guide to using stored procedures in sqlTRANSCRIPT
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
1/17
National University of Computer and Emerging Sciences
Lab Manual 8Views and Stored Procedures(Advanced Concepts)
Database Systems
Lab Instructor(s) Anam MansoorSemester Spring 2014
Department of Computer Science
FAST-NU, Lahore, Pakistan
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
2/17
Table of Contents
1. Task Distribution ........................................................................................................................................... 3
2. Objective ....................................................................................................................................................... 4
3. Views ............................................................................................................................................................. 5
Use of a View .................................................................................................................................................... 6
General syntax for Views .................................................................................................................................. 6
Creating a View ............................................................................................................................................. 7
Get result from a View .................................................................................................................................. 7
Drop a View ................................................................................................................................................... 7
4. Advanced Stored Procedures ...................................................................................................................... 12
Modifying an Existing Stored Procedure ........................................................................................................ 12
Using try catch in SQL Server stored procedures ........................................................................................... 13Reducing amount of network data for SQL Server stored procedures .......................................................... 13
Deleting a SQL Server stored procedure......................................................................................................... 15
5. Exercise ........................................................................................................................................................... 16
6. References ...................................................................................................................................................... 17
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
3/17
FAST NU Lahore Database Systems CS 204
Page 3
1. Task DistributionTotal (170 minutes)
o Views (35 minutes)o Stored Procedures (Advanced Concepts) (35 minutes)o In lab Exercise (60 minutes)o Phase 2 Evaluations (30 minutes)
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
4/17
FAST NU Lahore Database Systems CS 204
Page 4
2. ObjectiveIn this lab, the concept of views will be discussed along with its implementation and types. We will also go
through introduce some advance usage of stored procedures. At the end of this lab, you will have knowledge
of the following.
o Views.o Advanced Concepts of stored procedures.
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
5/17
FAST NU Lahore Database Systems CS 204
Page 5
3. ViewsA database viewdisplays one or more database records on the same page. A view can display
some or all of the database fields. Views havefiltersto determine which records they show.
Views can be sortedto control the record order and groupedto display records in related sets.
Views have other options such as totals and subtotals.
Most users interact with the database using the database views. A key to creating a useful
database is a well-chosen set of views. Luckily, while views are powerful, they are also easy to
create.
A View is a "Virtual Table". It is not like a simple table, but is a virtual table which contains columns and data
from different tables (may be one or more tables). A View does not contain any data, it is a set of queries
that are applied to one or more tables that is stored within the database as an object. After creating a view
from some table(s), it used as a reference of those tables and when executed, it shows only those data whichare already mentioned in the query during the creation of the View.
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
6/17
FAST NU Lahore Database Systems CS 204
Page 6
In the above diagram, we have created a View (View_Table1_Table2) from Table1 and Table2. So the
View_Table1_Table2 will only show the information from those columns. Let's checkout the basic syntax for
creating a View:
CREATE VIEW [View Name]
AS
[SELECT Statement]
Use of a View
Views are used as security mechanisms in databases. Because it restricts the user from viewing certain
column and rows. Views display only those data which are mentioned in the query, so it shows only data
which is returned by the query that is defined at the time of creation of the View. The rest of the data is
totally abstract from the end user.
Along with security, another advantage of Views is data abstraction because the end user is not aware of all
the data in a table.
General syntax for Views
In this section, I will describe how to create Views, select data from Views, and deleting Views. I have created
a database named ViewDemo. It has a table called EmpInfoas shown below:
which contains the following data:
All the examples I have described are from this database.
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
7/17
FAST NU Lahore Database Systems CS 204
Page 7
Creating a View
Below is the general syntax for creating a View:
CREATE VIEW [View_Name]AS[SELECT Statement]
For example:
CREATEVIEWSampleViewAsSELECTEmpID,EmpName FROMEmpInfo
which will create a View with the name SampleView that will only contain EmpID, EMPName.
Get result from a View
This is similar to a Select statement:
select*fromSampleView
Now have a look at the output of SampleView:
Drop a View
DROPVIEWSampleView
Now if we want to select data from SampleView, we will get the following error:
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
8/17
FAST NU Lahore Database Systems CS 204
Page 8
We begin with creating 3 tables PRODUCTS, Customer & BOOKING. These are fictitious tables for our demo.
The PRODUCTS stores data for a retail shop with a flag column IsSalable based on whose value we treat the
products as Salable.
CREATETABLEPRODUCTS(ProductID INTPRIMARYKEYCLUSTERED,ProductDesc VARCHAR(50)NOTNULL,
ManufacturingDate DATETIME,ExpiryDate DATETIME,IsSalable BIT,--1 Salable/Active FOR 0 For NonSalable/Passive ProductPrice MONEYNOTNULL)
Next, we have a Customer table which stores UserID and Password details for customers.
CREATETABLECustomer(CustID INTIDENTITY(1002,2)PRIMARYKEYCLUSTERED,FName VARCHAR(50)NOTNULL,LNme VARCHAR(50)NOTNULL,
UserID VARCHAR(100)NOTNULL,Pswd NVARCHAR(100)NOTNULLDEFAULT'password123')
Lastly, I have created a BOOKING table which houses all the bookings from different customers.
CREATETABLEBOOKING(BookingID INTIDENTITY(10,2)PRIMARYKEYCLUSTERED,ProductID INTREFERENCESdbo.Products(ProductID),CustID INTREFERENCESdbo.Customer(CustID),DateOfBooking DATETIMENOTNULL,QTY INT
)
Next, insert a few records into these tables:
INSERTINTOPRODUCTS VALUES(1,'Biscuits','2011-09-01 00:00:00.000','2012-09-01 00:00:00.000',1,20)INSERTINTOPRODUCTS VALUES(2,'Butter','2010-09-01 00:00:00.000','2011-09-01 00:00:00.000',1,30)
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
9/17
FAST NU Lahore Database Systems CS 204
Page 9
INSERTINTOPRODUCTS VALUES(3,'Milk','2011-10-01 00:00:00.000','2011-11-01 00:00:00.000',1,46)
INSERTINTOCustomer(FName,LNme,UserID,Pswd)
VALUES('Sara','Verma','[email protected]','S123')INSERTINTOCustomer(FName,LNme,UserID,Pswd)VALUES('Rick','Singh','[email protected]','G311')INSERTINTOCustomer(FName,LNme,UserID,Pswd)VALUES('Micky','Khera','[email protected]','M222')
INSERTINTOBOOKING(ProductID,CustID,DateOfBooking,QTY)VALUES(1,1002,'2011-11-01 00:00:00.000',3)INSERTINTOBOOKING(ProductID,CustID,DateOfBooking,QTY)
VALUES(2,1004,GETDATE(),4)INSERTINTOBOOKING(ProductID,CustID,DateOfBooking,QTY)VALUES(3,1006,'2011-10-01 00:00:00.000',2)
Our table contents look like this. I know the tables are not completely normalized, for now please ignore
them, these are simple demo tables.
SELECT*FROMCustomer
Select*fromPRODUCTS
Select*fromBOOKING
A customer purchases/books a product and the same gets recorded into the BOOKING table now to generate
the bill on his name we can uses a VIEW which would help us do away with a physical table. Instead it would
enable us to generate the bill based on the information from these 3 tables itself. Lets see how its possible.
CREATEVIEWBill_VASSELECTC.FName
,C.LNme,P.ProductDesc,B.DateOfBooking,P.Price,B.QTY,(B.QTY*P.Price)ASTotalAmountPayable
FROMBOOKING BINNERJOINPRODUCTS PONB.ProductID=P.ProductIDINNERJOINCustomer CONB.CustID=C.CustID;
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
10/17
FAST NU Lahore Database Systems CS 204
Page 10
Next if,
Select*fromBill_V
Now we will create another view
CREATE VIEWv_EmployeeDetailAS
SELECT E.EmployeeID,E.Name,EA.AddressLine1,EA.CityFROM Employee E
INNERJOINEmployeeAddress EAONEA.EmployeeID =E.EmployeeID
SELECT *FROMv_EmployeeDetail
Views WITH CHECK OptionTo restrict the changes that users can make, you use the CREATE VIEW commands WITH CHECK OPTION
clause when defining the view
CREATE VIEWv_EmployeeDetailWithCheckOptionASSELECTE.*
FROMEmployee EWHEREE.EmployeeID
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
11/17
FAST NU Lahore Database Systems CS 204
Page 11
-- inserting into viewwould add automatically to the table--
INSERTINTOv_EmployeeDetailWithCheckOption(EmployeeID,NAME)
VALUES(12,'Added with View')
SELECT*FROMEmployeeSELECT*FROMv_EmployeeDetailWithCheckOption
---- Out OF Range
--inserting into tablewould be allowed but would not reflect into view as its against the view check--
INSERTINTOEmployee(EmployeeID,NAME)VALUES(16,'Added with Table')
SELECT*FROMEmployeeSELECT*FROMv_EmployeeDetailWithCheckOption
-- inserting into viewwould not be allowed--
INSERTINTOv_EmployeeDetailWithCheckOption(EmployeeID,NAME)VALUES(17,'Added with View')
SELECT*FROMEmployeeSELECT*FROMv_EmployeeDetailWithCheckOption
-- DELETE Employee WHERE employeeid= 16
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
12/17
FAST NU Lahore Database Systems CS 204
Page 12
4. Advanced Stored ProceduresModifying an Existing Stored Procedure
Overview
when you first create your stored procedures it may work as planned, but how to do you modify an existing
stored procedure. In this topic we look at the ALTER PROCEDURE command and it is used.
Explanation
Modifying or Altering a stored procedure is pretty simple. Once a stored procedure has been created it is
stored within one of the system tables in the database that is was created in. When you modify a stored
procedure the entry that was originally made in the system table is replaced by this new code. Also, SQL
Server will recompile the stored procedure the next time it is run, so your users are using the new logic. Thecommand to modify an existing stored procedure is ALTER PROCEDURE or ALTER PROC.
Let's say we have the following existing stored procedure: This allows us to do an exact match on the City.
Let's say we want to change this to do a LIKE instead of an equals.
To change the stored procedure and save the updated code you would use the ALTER PROCEDURE command
as follows.
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
13/17
FAST NU Lahore Database Systems CS 204
Page 13
Now the next time that the stored procedure is called by an end user it will use this new logic.
Using try catch in SQL Server stored procedures
Overview
A great new option that was added in SQL Server 2005 was the ability to use the Try..Catch paradigm that
exists in other development languages. Doing error handling in SQL Server has not always been the easiest
thing, so this option definitely makes it much easier to code for and handle errors.
Explanation
If you are not familiar with the Try...Catch paradigm it is basically two blocks of code with your stored
procedures that lets you execute some code, this is the Try section and if there are errors they are handled in
the Catch section.
Let's take a look at an example of how this can be done. As you can see we are using a basic SELECTstatement that is contained within the TRY section, but for some reason if this fails it will run the code in the
CATCH section and return the error information.
Reducing amount of network data for SQL Server stored procedures
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
14/17
FAST NU Lahore Database Systems CS 204
Page 14
Overview
Their are many tricks that can be used when you write T-SQL code. One of these is to reduce the amount of
network data for each statement that occurs within your stored procedures. Every time a SQL statement is
executed it returns the number of rows that were affected. By using "SET NOCOUNT ON" within your stored
procedure you can shut off these messages and reduce some of the traffic.
Explanation
As mentioned above there is not really any reason to return messages about what is occurring within SQL
Server when you run a stored procedure. If you are running things from a query window, this may be useful,
but most end users that run stored procedures through an application would never see these messages.
You can still use @@ROWCOUNT to get the number of rows impacted by a SQL statement, so turning SET
NOCOUNT ON will not change that behavior.
Not using SET NOCOUNT ON
Here is an example without using SET NOCOUNT ON
The messages that are returned would be similar to this:
This example uses the SET NOCOUNT ON as shown below. It is a good practice to put this at the beginning of
the stored procedure.
Using SET NOCOUNT ON
This example uses the SET NOCOUNT ON as shown below. It is a good practice to put this at the beginning of
the stored procedure.
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
15/17
FAST NU Lahore Database Systems CS 204
Page 15
The messages that are returned would be similar to this:
Using SET NOCOUNT ON and @@ROWCOUNT
This example uses SET NOCOUNT ON, but will still return the number of rows impacted by the previous
statement. This just shows that this still works.
The messages that are returned would be similar to this:
Deleting a SQL Server stored procedure
Overview
In addition to creating stored procedures there is also the need to delete stored procedures. This topic
shows you how you can delete stored procedures that are no longer needed.
Explanation
The syntax is very straightforward to drop a stored procedure, here are some examples.
Dropping Single Stored Procedure
To drop a single stored procedure you use the DROP PROCEDURE or DROP PROC.
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
16/17
FAST NU Lahore Database Systems CS 204
Page 16
Dropping Multiple Stored Procedures
To drop multiple stored procedures with one command you specify each procedure separated by a comma as
shown below.
5. ExerciseLoad the employee management schema (TableScripts.sql) before attempting this exercise.
1. Create a view of all employees against their RateChangeDate field in EmployeePayHistory.2. Create a view that displays all employeeDetails from Employee table against their respective
Maximum ratechangeDate in EmployeePayHistory table.
e-g
EmployeeID RateChangeDate
4 1998-01-05 00:00:00.000
4 2000-07-01 00:00:00.000
4 2002-01-15 00:00:00.000
So from this record set Employeeid would qualify for third row where RateChangeDate = 2002-01-15
00:00:00.000.
Accordingly you should select maximum ratechangeDate of any employee with >1 rateChangeDate.
Rest of the single row employee would be taken as it is.
Output should be All employee details from Employee and Maximum RateChageDate as
LatestRateChangeDate from EmployeePayHistory.
3. Create a view that displays total number of employees who have been associated with thedepartment (END Date not null) .You have to display departmentid and count of employee with an
-
5/27/2018 SQL: Views and Advanced Stored Prcedures
17/17
FAST NU Lahore Database Systems CS 204
Page 17
additional filter of Employee Count >1. There are 2 filters that need to be adjusted so make sure you
adjust them properly i-e EndDate, Count check
4. Create a view having all the details of an employee and his average salary of year 20085. Create a view that should restrict the data domain in the table VIEW_EmployeePayHistory with
EmployeeID >20 and DaysPerWeek < 7
You have to show the result before the insertion of any record and then the table and view state
after the insertion of valid record (within the domain check) and also out of range data.
6. Create a stored procedure that tries to delete product with any id from the products table. If a foreignkey constraint fails then this store procedure should print an error message( This will be checked for
both the cases i) When the product can be deleted ii) When the foreign key constraint fails )
6. References
1. http://www.mssqltips.com/sqlservertutorial/160/sql-server-stored-procedure/
http://www.mssqltips.com/sqlservertutorial/160/sql-server-stored-procedure/http://www.mssqltips.com/sqlservertutorial/160/sql-server-stored-procedure/http://www.mssqltips.com/sqlservertutorial/160/sql-server-stored-procedure/