Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views10 pages

Practice 02 Stored Procedures

The document describes a practice on the use of stored procedures in SQL Server. Four stored procedures will be created to perform queries and updates of data in a database. The first procedure will search for an employee by code, the second will search for employees by first or last name, the third will show the highest sales by product in a given year, and the fourth will show the best customer by product and year.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views10 pages

Practice 02 Stored Procedures

The document describes a practice on the use of stored procedures in SQL Server. Four stored procedures will be created to perform queries and updates of data in a database. The first procedure will search for an employee by code, the second will search for employees by first or last name, the third will show the highest sales by product in a given year, and the fourth will show the best customer by product and year.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

José María Arguedas National University Teacher: Eng.

Edwin Ramos Velásquez


Professional Career in Systems Engineering Subject: Database II

PRACTICE 02

USE OF STORED PROCEDURES IN SQL SERVER

OBJECTIVES
The student will be able to use stored procedures to perform:

• Queries in SQL Server


• Data updates

METHODOLOGY
• The student will register an administrator user for the newly created database (For example
UserDB). Assigning the respective rights.
• The student will enter the SQL Server Query Analyzer administrator by identifying themselves.
previously (for example asUserDB, with their respective password).
• The student will create stored procedures in SQL Server 2000 according to the same format as
syntax that specifies SQL Server.
• The student will execute the SQL Server queries from the same SQL Query Analyzer (open
from the SQL Server Corporate Administrator.

PREVIOUS KNOWLEDGE
The reader has prior knowledge of the syntax for creating stored procedures.

PRELIMINARY CONSIDERATIONS

In this practice, we assume the following considerations

- There is a server PC whose name is: ServerPC


- There is a SQL Server 2000 database server whose name is: ServerBD (which is hosted
on the server PC) and that has been properly registered locally.
- In this server, the database named DataBaseTienda has been created.
- For the database DataBaseStore, an administrator-type user (with rights to
typical access of a database administrator) called UserDB with an access password
UserPassword.1
- Create a directory named WorkDirectory (It will store all the generated files in)
this practice)
Note: The data to be used for the database connection will be:

VALUES OF
ATTRIBUTE CUSTOM VALUES2
SAMPLE
DATABASE NAME StoreDatabase
SERVER NAME DatabaseServer
HOST NAME ServerPC
USER NAME UserDB3
PASSWORD UserPassword4

1
The username and password will be registered only in this practice.
2
You must fill in this column with the values that correspond to you.
3
This user must be registered in the current practice.
4
This key corresponds to the newly registered user
National University José María Arguedas Teacher: Eng. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Database II

SECTION 01: CREATION OF THE STORED PROCEDURE


usp_SearchEmployeeByCode (empCode: Integer)
1. Press the New Query button, and in the editing window, write the following:

CREATE PROCEDURE dbo.usp_SearchEmployeeByCode_SQL


@CodEmpINT/* Input parameters */
AS
IF EXISTS(SELECT cod_empleado FROM empleado WHERE cod_empleado=@CodEmp)
BEGIN
SELECT LastName, FirstName, Position, HiringDate
Years_of_service = YEAR(GETDATE()) - YEAR(Hire_date)
FROM employee WHERE employee_code = @CodEmp
END
ELSE
BEGIN
The employee code you are looking for does not exist...:
CAST(@CodEmpas varchar(6))
RETURN-1 /*Return status code */
END
RETURN0
2. Save the file as BuscarEmpleadoPorCod_ASQL.sql
3. Execute the query (press the Execute query button)
The stored procedure usp_BuscarEmpleadoPorCod_ASQL will have been successfully created.

4. Press the New Query button, and in the editing window, write the following:

CREATE PROCEDURE dbo.usp_FindEmployeeByCode


@CodEmpINT/* Input parameters */
AS
SELECT LastName, FirstName, Position, HiringDate
Years_of_service = YEAR(GETDATE()) - YEAR(Hire_date)
FROM employee WHERE employee_code = @CodEmp
RETURN0
5. Save the file as BuscarEmpleadoPorCod.sql
6. Press the Analyze Query button. Correct any errors if there are any.
7. Run the query (press the Run query button)
The stored procedure usp_BuscarEmpleadoPorCod has been successfully created.

a) Execution of the stored procedure usp_BuscarEmpleadoPorCod_ASQL


8. Open a new window to run the procedure with instructions for example:
We tested how the remote procedure works:
We will look for the employee whose code is number 8.
Execute usp_FindEmployeeByCode_ASQL8
The result of this stored procedure is similar to:
First Names Hiring_date
--------- ------- ---------------------------- ----------------- ------------
Callahan Laura 12

We will look for the employee with code number 6.


Execute usp_FindEmployeeByCode_ASQL6

The result of this stored procedure is similar to:


Surnames Names Cargo Hiring Date Years of service
--------- ------- -------------------- --------------------------------
Suyama Michael Sales Representative September 13, 1992 13
José María Arguedas National University Teacher: Eng. Edwin Ramos Velásquez
Professional Career in System Engineering Subject: Databases II
b) Execution of the stored procedure usp_BuscarEmpleadoPorCod
9. Execute the query SearchEmployeeByCod.sql and compare the results with the previous query.
What is the difference in the results of both stored procedures?
Why would we use the PRINT statement in one stored procedure while not in another?
used?

SECTION 02: CREATING THE STORED PROCEDURE


usp_ usp_SearchEmployeeByLastNameFirstName (Filter: String[70])
10. Press the New Query button, and in the editing window, write the following:
CREATE PROCEDURE dbo.usp_SearchEmployeeByLastNameFirstName
@FilterVARCHAR(70)
AS
cod_employee
Private Phone
FROM employee
WHERE lastnames LIKE '%' + @Filter + '%' OR
names LIKE '%' + @Filter + '%'
RETURN0
11. Press the Analyze query button. Correct any errors, if there are any.
12. Save the file as BuscarEmpleadoPorApeNom.sql
13. Execute the query (press the Execute query button)
The stored procedure usp_BuscarEmpleadoPorApeNom has been successfully created.
14. Open a new window to run the procedure with instructions for example:
We tested how the remote procedure works:
We will look for employees whose first or last name starts with the letters 'pe'.
EXECusp_SearchEmployeeByLastNameFirstName pe
The result of this stored procedure is similar to:

Code ApeNom tfno_Particular Date of Birth


------ --------------------------------- -----------------------
-
4 Peacock, Margaret 1937-09-19 00:00:00.000
Laurent Pereira 1965-12-09 00:00:00.000

We will look for employees whose first or last name starts with the letters 'LA'.
EXEC usp_SearchEmployeeByLastNameFirstName LA
The result of this stored procedure is similar to:

Code ApeNom tfno_Particular Date of Birth


------ --------------------------------- -----------------------
-
8 Callahan, Laura 2065551189
Laurent Pereira December 9, 1965 00:00:00.000

SECTION 03: CREATION OF THE STORED PROCEDURE


usp_StatOrderByProduct (Year: String[4])
15. Press the New Query button, and in the editing window, write the following:
CREATE PROCEDURE dbo.usp_EstadPedXProducto
@AnioCHAR(4)
AS
SELECT TOP 10 d.product_code, Total=SUM(Quantity), a.Product_name
FROM order_detail d
INNER JOIN order p ON d.id_order = p.id_order
INNER JOIN product a ON d.cod_producto = a.cod_producto
WHERE YEAR(order_date) = CAST(@Year AS INTEGER)
GROUP BY d.cod_producto, a.nombre_producto
ORDER BY DESC
RETURN0
National University José María Arguedas Teacher: Eng. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Database II
16. Press the Analyze query button. Correct any errors, if there are any.
17. Save the file as EstadPedXProducto.sql
18. Execute the query (press the Execute query button)
With this, the stored procedure usp_EstadPedXProducto will have been successfully created.
19. Open a new window to run the procedure with instructions, for example:
We test how the remote procedure works:
We will look for the top 10 sold items based on their total quantities in the year 2002.
EXECusp_EstadPedXProducto 2002

The result of this stored procedure is similar to:


Product_Code Product_Name
----------- ------ -----------------------------
3305 15 Guardian Mini Lock
4105 14 InFlux Lycra Glove
301151 14 SlickRock
2202 13 Triumph Pro Helmet
401002 13 Mini Nicros
1101 12 Active Outdoors Crochet Glove
1111 11 Active Outdoors Lycra Glove
303182 11 Nicros
2204 10 Triumph Pro Helmet
2209 10 Triumph Vertigo Helmet

SECTION 04: CREATION OF THE STORED PROCEDURE


usp_EstadMejorClientePorProducto (Anio: String[4])
20. Press the New Query button, and in the editing window, write the following:
CREATE PROCEDURE dbo.usp_BestClientByProduct
@Anio INT = 0
As
SET NOCOUNT ON
Select the customers of the month according to the Quantity of Product Ordered
SELECT d.cod_producto, p.cod_cliente, Total = SUM(d.cantidad)
c.Customer_name
INTO#TotalQuantityOrdered
FROM Order_detail d
INNER JOIN Order p ON d.id_order = p.order_id
INNER JOIN Client c ON p.cod_cliente = c.cod_Client
WHERE YEAR(p.order_date) = @Year
GROUP BY p.cod_cliente, d.cod_producto, c.Nombre_cliente
ORDER BY p.cod_cliente, d.cod_producto, 3 DESC
Select only the products of the Year
SELECT d.cod_producto INTO #Productos
FROM Order_detail d
INNER JOIN Order p ON d.id_order = p.id_order
WHERE YEAR(p.order_date) = @Year
GROUP BY d.cod_producto
ORDER BY d.cod_producto

CREATE TABLE #TheBest


( Product_CodeINT NULL, Client_CodeINT NULL,
DECIMAL(5,2) NULL
Customer_nameCHAR(50)NULL
--
DECLARE @CodProd INT
National University José María Arguedas Instructor: Eng. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Database II
Cursor management
DECLARE Cursor_Prod CURSOR SCROLL
FOR SELECT Cod_producto FROM #Productos
OPENCursor_Prod
FETCH FIRST FROM Cursor_Prod INTO @CodProd
WHILE@@FETCH_STATUS = 0
BEGIN
INSERT#TheBest (Product_code, Customer_code,
Total_pedido
(SELECT Top3 Product_Code, Client_Code, Total
Client Name
FROM#TotalOrderQty
WHERE Product_Code = @CodProd
)
FETCH NEXT FromCursor_Prod INTO @CodProd
END
CLOSECursor_Prod
DEALLOCATECursor_Prod
--
SET NOCOUNT OFF
SELECT * FROM #TheBest ORDER BY Product_code, Total_order DESC

RETURN0

21. Press the Analyze query button. Correct any errors, if there are any.

22. Save the file comousp_EstadMejorClientePorProducto.sql

23. Execute the query (press the Execute query button)


With this yes there will becreated with success the procedure stored
usp_BecomeBestCustomerByProduct

24. Open a new window to execute the procedure with instructions for example:
We tested how the remote procedure works:
We will look for the top 10 sold items based on their total quantities in the year 2002.
EXEC usp_BestCustomerByProduct2002

The result of this stored procedure is similar to:

Product_Code Total Order Customer_Name


----------- ------------- ------------ -----------------
1 1101 30 3.00 Spokes for Folks
2 1101 25 2.00 Extreme Cycling
3 1101 1 1.00 City Cyclists
4 1102 29 2.00 Blazing Bikes
…..
…..
239 402002 18 3.00 Bikes and Trikes
240 402002 33 3.00 Fulcrum Cycles
241 402002 15 1.00 The Bike Cellar
National University José María Arguedas Teacher: Eng. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Database II
SECTION 05: CREATION OF THE STORED PROCEDURE usp_ReadProduct
25. Press the New Query button, and in the editing window, write the following:

CREATE PROCEDURE dbo.usp_ReadProduct


AS
SET NOCOUNT ON
DECLARE Product_cursor CURSOR
SELECT * FROM product

OPENProduct_cursor /*Open the cursor*/


FETCHProduct_cursor /*moves the cursor to the next record*/

WHILE @@FETCH_STATUS = 0
BEGIN
FETCH product_cursor /*moves the cursor to the next record*/
END

CLOSEProduct_cursor --- Closes the cursor


DEALLOCATE Product_cursor --- Releases the resources used in the cursor

26. Press the Analyze Query button. Correct any errors, if there are any.
27. Save the file as ReadProduct.sql
28. Execute the query (press the Execute query button)
29. Test it by executing the instruction:

EXEC usp_ReadProduct

SECTION 06: CREATION OF THE VIEW List_Personas


30. Press the New Query button, and in the editing window, write the following:
CREATE VIEW dbo.vw_List_People
AS
SELECT cod_Persona = 'P' + CAST(Cod_Proveedor AS VARCHAR(5)),
Name
FROMProvider
UNION ALL

SELECT cod_Person = 'C' + CAST (Cod_Client AS VARCHAR(5))


Client_Name
FROMClient
UNION ALL

SELECT cod_Person = 'E' + CAST(Employee_Code AS VARCHAR(5)),


LastName + ', ' + FirstName
FROMEmployee

31. Press the Analyze query button. Correct the errors, if there are any.
32. Save the file as VistaLista_Personas.sql
33. Execute the query (press the Execute query button)
34.Try it by running:
SELECT * FROM vw_List_People

NOTE: Note that a view is treated the same way as a table when selecting it.
data to show it.
National University José María Arguedas Teacher: Eng. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Database II
SECTION 07: CREATION OF VIEW vw_10Best_Clients
35. Press the New Query button, and in the editing window, write the following:

CREATE VIEW dbo.vw_10Best_Customers


AS
SELECT TOP 10 C.Cod_Cliente, Name = C.Nombre_Cliente,
=SUM(P.Sub_Total)
FROM Client C
INNER JOIN Payment_Receipt ON Client.code_Client = P.code_Client
GROUP BY C.Cod_Cliente, C.Nombre_Cliente
ORDER BY PurchaseAmount DESC, C.Client_Code

36. Press the Analyze query button. Correct any errors, if there are any.
37. Save the file as vw_10Best_Clients.sql
38. Execute the query (press the Execute query button)
39. Try it by running:
SELECT * FROM vw_10Best_Customers

The result of this query is similar to the one shown.


Customer_Code Name Amount Purchased
----------- ----------- --------------
49 Rocky Roadsters 89764.7800
26 Blazing Saddles 65017.6300
38 Tyred Out 63961.2900
22 Crank Components 61962.1600
39 Wheels Inc. 60736.1500
97 Bicycle Bourges North 60732.6500
72 Cycle City Rome 56420.4400
74 Driving force wheels 56203.3400
54 Cyclopath 53274.3600
64 SAB Mountain 52034.5900

SECTION 08: CURSOR MANIPULATION


2. Use of cursors
a) In the following example, we will show the ability to navigate through the rows of the
results generated by a cursor:
• Execute the following instructions one by one and check the result of each one:

DECLARE client_cursor SCROLL CURSOR


FOR SELECT client_code, client_name, country
FROM client

OPENclient_cursor

• Next, execute each of the following batches and observe the result of each one.
-- first row of the cursor - Execution 1
FETCH NEXT FROM client_cursor
SELECT "Cursor state" = @@FETCH_STATUS
GO
-- last row of the cursor -- Execution 2
FETCH LAST FROM client_cursor
SELECT 'Cursor Status' = @@FETCH_STATUS
GO
-- the same previous row -- Execution 3
FETCH RELATIVE0FROMcliente_cursor
SELECT 'Cursor status' = @@FETCH_STATUS
National University José María Arguedas Teacher: Ing. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Database II
GO
-- first row of the cursor - Execution 4
FETCH FIRST FROM client_cursor
SELECT 'Cursor status' = @@FETCH_STATUS
GO
next row (second row) - Execution 5
FETCH NEXT FROM client_cursor
SELECT "Cursor status" = @@FETCH_STATUS
GO
The sixth row of the cursor – Execution 6
FETCH ABSOLUTE6FROMclient_cursor
SELECT 'Cursor status' = @@FETCH_STATUS
GO
-- Delete the sixth row of the cursor from the table - Execution 7
DELETE FROM client WHERE CURRENT OF client_cursor
GO
-- there are no data for the sixth row – Execution 8
FETCH RELATIVE0FROMclient_cursor
SELECT 'Cursor status' = @@FETCH_STATUS
GO
Read the previous row - Execution 9
FETCH PRIOR FROM client_cursor
SELECT 'Cursor status' = @@FETCH_STATUS
GO
-- the row does not exist in the cursor - Execution 10
-- (Note: There are not 7200 rows in the customers table)
FETCH ABSOLUTE 7200 FROM client_cursor
SELECT 'Cursor Status' = @@FETCH_STATUS
GO
-- close and delete the cursor the cursor – Execution 11
CLOSE customer_cursor
DEALLOCATE client_cursor
GO

b) Creation and use of a cursor from a Stored Procedure


Review the implementation of the procedure creation routine.usp_ReadProduct
Execute the procedure with the instruction: EXEC usp_ReadProduct
TASKS
Write a stored procedure:
That returns the total number of quantities sold
Product_Code – Product_Name – Quantity_Sold – Product_Type_Name
2. To return a list of the first 30 records of payment receipts registered in the year
XXXX (example 2004)
Receipt_Number – Total – issue_date
3. Show all the names of the customers who made any type of order
Format: Client_Name – Order_Number – issue_date – Total
4. Show all the names of the customers who made any type of purchase.
Customer_Name - Receipt_Number - issue_date - Total
5. Show all the names of the employees who registered any type of order.
Format: Names and Surname – Receipt Number – Issue Date – Total
6. Show all the names of the employees who recorded any type of purchase
Names and Surname - Receipt Number - issue date - Total
7.Show a list of all undelivered orders
National University José María Arguedas Teacher: Eng. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Database II
QUESTIONS FOR YOUR ANALYSIS (Review)
How would you execute the following stored procedures?5?
• CREATE PROCEDURE usp_BestClients @maxClients INT
Rpta:EXECusp_BestClients 10

• CREATE PROCEDURE usp_BuscaCliente @codCliente INT


Answer: ?

• CREATE PROCEDURE usp_BuscaNombreCliente @iNombre VARCHAR(25)


Rpta:EXECusp_BuscaNombreCliente 'Juan'

• CREATE PROCEDURE usp_SearchEmployee @iLastName VARCHAR(25)


Answer: ?

How would the following stored procedure differ from the procedure?
dbo.usp_SearchEmployeeByCode dbo.usp_SearchEmployeeByCod_ASQL
CREATE PROCEDURE dbo.usp_SearchEmployeeByCode_Optional
@CodEmpINT
AS
DECLARE @CurrentApp varchar(35)
SET @CurrentApp = APP_NAME()

IF(@CurrentApp = 'MS SQL Query Analyzer') OR


(@CurrentApp = 'SQL Query Analyzer')
BEGIN
IF Exists(SELECT cod_empleado FROM empleado WHERE cod_empleado=@CodEmp)
SELECT LastName, FirstName, Position, HiringDate
Years_of_service = Year(Getdate()) - Year(Employment_date)
FROM employee WHERE employee_code = @CodEmp
ELSE
Begin
The employee code you are looking for does not exist...
+ Cast(@CodEmp as varchar(6))
RETURN-1 /*Return status code */
End
END
ELSE
SELECT LastName, FirstName, Position, HireDate
Years of service = Year(Getdate()) - Year(Contract_start_date)
FROM employee
WHERE employee_code = @CodEmp
Return0

SECTION 09 (More questions): Execution of SQL queries in the databaseDataBaseStore

a) Answer the following questions


What are the 'extragrand' size products?
The names of the customers who purchased 'extra large' size products
Which clients live in the "CA" region?
Which employees served customers living in the region 'CA'?
Which employees have last names that start with the letter 'D'?
What products were sold in 2002?
What products were sold to customers living in the region 'CA'?
b) Ask yourself five questions and find the answers using Transact-SQL DML.

5
None of the stored procedures have been created in this practice. However, when answering these questions,
Assume that they were indeed created.
National University José María Arguedas Teacher: Eng. Edwin Ramos Velásquez
Professional Career in Systems Engineering Subject: Databases II

Examples of DML queries in a database - example


Be the following relational database,

It is fulfilled that the following SQL - DML queries can be made:


---------------------------------------------------------------------------------------------
Example 1: Selecting data from a single table
SELECT Employee_Code, Last_Name, First_Name -- 1. Selection of the fields to be displayed
FROM Employee -- 2. Selection of the first table
---------------------------------------------------------------------------------------------
-- Example 2: Selecting data from two tables
SELECT E.Employee_Code, E.Last_Name, E.First_Name, P.Order_Amount -- 1. Select fields to view
FROM Employee AS E 2. Selection of the first table
JOINOrderASPON(E.Employee_Code = P.employee_code) --3. Next Table
---------------------------------------------------------------------------------------------
-- Example 3: Data selection from three or more tables
SELECT E.Employee_Code, E.Last_Name, E.First_Name
P.Order_ID 1. Selection of the fields to be displayed
FROM Employee AS E 2. Selection of the first table
JOINOrder AS PON(E.cod_Empleado = P.cod_empleado) --3. Next Table
JOIN Order_Detail AS DON(P.Order_ID = D.Order_ID)
---------------------------------------------------------------------------------------------
-- Example 4: Selection of two related tables
-- for three or N fields
SELECT C.Invoice_Type, C.Series_Number, C.Invoice_Number,
C.Issue_Date
FROM Payment_ReceiptASC
INNER JOIN Payment_Receipt_Detail ASD
ON(C.Tipo_Comprobante = D.Tipo_Comprobante AND C.Nro_Serie = D.Nro_Serie
ANDC.Invoice_Number = D.Invoice_Number)
---------------------------------------------------------------------------------------------
-- Example 5: Use of Subqueries for selection
Product_Code
FROMProductASP
WHERE Exists
(SELECT C.Tipo_Comprobante, C.Nro_Serie, C.Nro_Comprobante,
C.Issue_Date
FROM Payment_Receipt AS C
INNER JOIN Payment_Voucher_Detail AS DON (C.Voucher_Type = D.Voucher_Type AND
C.Nro_Serie = D.Nro_Serie AND C.Nro_Comprobante = D.Nro_Comprobante
WHERE YEAR(C.Issue_Date)=2002 AND P.Product_Code=D.Product_Code
)

You might also like