0% found this document useful (0 votes)
30 views51 pages

Asm2 1622

This document provides the front sheet for Assignment 2 on database design and development. It includes information such as the student's name and ID, class details, date of submission, and a declaration of authenticity. It also contains grading criteria that will be used to evaluate the assignment.

Uploaded by

Dao Van Hieu
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)
30 views51 pages

Asm2 1622

This document provides the front sheet for Assignment 2 on database design and development. It includes information such as the student's name and ID, class details, date of submission, and a declaration of authenticity. It also contains grading criteria that will be used to evaluate the assignment.

Uploaded by

Dao Van Hieu
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/ 51

ASSIGNMENT 2 FRONT SHEET

Qualification TEC Level 5 HND Diploma in Computing

Unit number and title Unit 04: Database Design & Development

Submission date Date Received 1st submission

Re-submission Date Date Received 2nd submission

Student Name Dao Van Hieu Student ID GCH211135

Class GCH1105 Assessor name Tran Thi Thoa

Student declaration

I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism. I understand that
making a false declaration is a form of malpractice.

Student’s signature Hieu

Grading grid

P2 P3 P4 P5 M2 M3 M4 M5 D2 D3
❒ Summative Feedback: ❒ Resubmission Feedback:

Grade: Assessor Signature: Date:


Signature & Date:
Contents
Chapter 1 - Develop the database system ................................................................................................................................................... 5
1.1 Final Mock-up of the application.............................................................................................................................................. 6
1.2 Queries to create database with results .................................................................................................................................. 16
Chapter 2 – Produce queries ..................................................................................................................................................................... 24
2.1 Queries to INSERT data with illustrations of final result ............................................................................................................... 24
2.2 Queries to UPDATE data with illustrations of final result ............................................................................................................. 29
2.3 Queries to DELETE data with illustrations of final result .............................................................................................................. 32
2.4 Queries to SELECT data with illustrations of final result .............................................................................................................. 33
2.5 Advanced queries: Stored procedures, scalor functions ................................................................................................................. 37
2.6 Evaluate the effectiveness of the database solution ........................................................................................................................ 43
Chapter 3 – Test the system ...................................................................................................................................................................... 43
3.1 Test cases ........................................................................................................................................................................................ 43
3.2 User documentation, Flowchart to show how the system works .................................................................................................... 46
3.2.1 User documentation ................................................................................................................................................................. 46
3.2.2 Flowchart ................................................................................................................................................................................. 47

Figure 1: My Database ................................................................................................................................................................................ 5


Figure 2: Mock-up Login ............................................................................................................................................................................ 6
Figure 3: Employee Information in the Director's Interface ....................................................................................................................... 7
Figure 4: Add Employee in the Director's Interface ................................................................................................................................... 8
Figure 5: List Product in the Manager's Interface ....................................................................................................................................... 9
Figure 6: Customer Information in the Manager's Interface ..................................................................................................................... 10
Figure 7: Add Product in the Manager's Interface .................................................................................................................................... 11
Figure 8: Mock-up Client's Interface ........................................................................................................................................................ 12
Figure 9: Change Infomation In the Client's Interface ............................................................................................................................. 13
Figure 10: Mock-up Feedback In the Client's Interface ........................................................................................................................... 14
Figure 11: Cart In the Client's Interface .................................................................................................................................................... 15
Figure 15: Result of creating Director ...................................................................................................................................................... 16
Figure 16: Result of creating Manager ..................................................................................................................................................... 17
Figure 17: Result of creating login ........................................................................................................................................................... 18
Figure 18: Result of creating Product ....................................................................................................................................................... 19
Figure 19: Result of creating Client .......................................................................................................................................................... 20
Figure 20: Result of creating Order .......................................................................................................................................................... 21
Figure 21: Result of creating Feedback .................................................................................................................................................... 22
Figure 22: Result of creating Order_Item ................................................................................................................................................. 23
Figure 32: Flowchart of system ................................................................................................................................................................ 47
Figure 33: Add function ............................................................................................................................................................................ 48
Figure 34: Update Function ...................................................................................................................................................................... 49
Figure 35: Delete Function ....................................................................................................................................................................... 51
Chapter 1 - Develop the database system

Figure 1: My Database
1.1 Final Mock-up of the application
The login form is a place where members of FPT Shop company can log in to manage their accounts, and it is also where clients can
log in to purchase items

Figure 2: Mock-up Login


The Director form is a platform where directors can update and modify their information. Additionally, they can manage personnel,
products, customers, and their orders, as a director.

Figure 3: Employee Information in the Director's Interface


Figure 4: Add Employee in the Director's Interface
The Manager form is a platform where directors can update and modify their information. Additionally, they can manage products,
customers, and their orders, as a manager.

Figure 5: List Product in the Manager's Interface


Figure 6: Customer Information in the Manager's Interface
Figure 7: Add Product in the Manager's Interface
The Client form is a place where clients can manage and update their personal information, add feedback, as well as view detailed
information on their previous orders.

Figure 8: Mock-up Client's Interface


Figure 9: Change Infomation In the Client's Interface
Figure 10: Mock-up Feedback In the Client's Interface
Figure 11: Cart In the Client's Interface
1.2 Queries to create database with results

- The first and most important step is to create the database table.

- Create a table for directors.

Figure 12: Result of creating Director


- Create a table for managers.

Figure 13: Result of creating Manager


- Create a table for login.

Figure 14: Result of creating login


- Create a table for orders.

Figure 15: Result of creating Product


- Create a table for clients.

Figure 16: Result of creating Client


- Create a table for products.

Figure 17: Result of creating Order


- Create a table for feedback.

Figure 18: Result of creating Feedback


- Create a table for order items.

Figure 19: Result of creating Order_Item


Chapter 2 – Produce queries

2.1 Queries to INSERT data with illustrations of final result


- Insert values into the Director table.

- Insert values into the Manager table.


- Insert values into the Login table.

- Insert values into the Product table.


- Insert values into the Client table.
- Insert values into the Order table.
- Insert values into the Feedback table.
- Insert values into the Order_Item table

2.2 Queries to UPDATE data with illustrations of final result

Based on user requirements, the update commands must adhere to their demands, including updating product information, updating
customer information, and updating manager information.

- Updating product information includes updating product name, product details, product price, and inventory
For example 1, for product with ID = 1, I will update the product details, product price, and inventory quantity.
However, the product name will remain unchanged

This statement is used to update the product table in a database. The specific product that will be updated is identified by its
product_id, which is set to 1 in this case. The statement updates three fields of the product record: description, price, and
quantityInStock.

The SET clause lists the fields that will be updated and their new values. In this case, the description field is being updated to 'One of
the phones with the most powerful chipset', the price field is being updated to '999.99', and the quantityInStock field is being updated
to '55'.

The WHERE clause specifies which product record to update. In this case, only the record with a product_id of 1 will be updated. If
you omit the WHERE clause, all records in the product table will be updated with the new values, which could have unintended
consequences.

For example 2, for product with ID = 2, I will update the product price and inventory quantity in case the product has
been released for a long time and the demand for it has cooled down, and the number of products in stock has
decreased or increased

This UPDATE statement is also updating the product table in a database, specifically updating the price and quantityInStock fields for
a product with a product_id of 2.
The SET clause lists the fields that will be updated and their new values. In this case, the price field is being updated to '898.99' and
the quantityInStock field is being updated to '35'.

The WHERE clause specifies which product record to update based on the condition provided. In this case, only the record with a
product_id of 2 will be updated with the new values.

- Updating customer information includes updating first name, last name, phone number, and email

For example, for customer with ID = 1, they may have entered incorrect information when registering, so they want to
correct their name, phone number, and email

This UPDATE statement is updating the client table in a database, specifically updating the firstName, lastName, phone, and email
fields for a client with a client_id of 1. The SET clause lists the fields that will be updated and their new values. In this case, the
firstName field is being updated to 'Robert', the lastName field is being updated to 'Dao', the phone field is being updated to
'0373019563', and the email field is being updated to '[email protected]'.

- Updating manager information includes updating first name, last name, phone number, and email

For example, for manager with ID = 3, they recently lost their phone along with their phone number, so they have obtained a new
phone number and want to update their phone number
This UPDATE statement is updating the manager table in a database, specifically updating the phone field for a manager with a
manager_id of 2. The SET clause lists the fields that will be updated and their new values. In this case, only the phone field is being
updated to '0367599875'.

2.3 Queries to DELETE data with illustrations of final result

As per the user's request, the delete function will be applied to a product when it is no longer sold in the shop. Additionally, in the case
where a manager's contract ends or they are no longer working at the company, their account will also be deleted to prevent the loss of
shop information such as customer or product information.

- Example 1, Delete the manager with ID = 6 because they have resigned from the company

The DELETE statement is used to remove records from a table in a database.

The FROM keyword specifies the name of the table from which records should be deleted, which in this case is the manager table.

The WHERE clause is used to specify which records should be deleted. In this statement, the condition is that the manager_id field
must be equal to 6.

When this SQL statement is executed, the database will locate all records in the manager table where manager_id equals 6.

If there are any records that match this condition, they will be permanently deleted from the manager table.

It's important to note that this action cannot be undone, so it's important to double-check that you're deleting the correct records before
executing the statement.
- Example, Delete the product with ID = 8 as this product is no longer sold in the shop.

The DELETE statement is used to remove records from a table in a database.

The FROM keyword specifies the name of the table from which records should be deleted, which in this case is the product table.

The WHERE clause is used to specify which records should be deleted. In this statement, the condition is that the product_id field
must be equal to 8.

When this SQL statement is executed, the database will locate all records in the product table where product_id equals 8.

If there are any records that match this condition, they will be permanently deleted from the product table.

It's important to note that this action cannot be undone, so it's important to double-check that you're deleting the correct records before
executing the statement.

2.4 Queries to SELECT data with illustrations of final result

Based on the user's requirements, I will adhere to them to apply the appropriate adjustment.

1. Find the customers who have purchased a product

SELECT DISTINCT c.* selects all columns from the client table, and DISTINCT ensures that each client record is returned only once
even if they have multiple orders containing the specified product.
The INNER JOIN keyword is used to join the client table with the order table based on the client_id field.

Another INNER JOIN is used to join the order_item table with the previous join based on the order_id field.

The WHERE clause is used to filter the results to only show customers who have purchased a specific product, which is specified
using the product_id field in the order_item table.

Replace <product_id> with the ID of the product user want to search for, and this SQL statement will return a list of all customers
who have purchased that product.

2. Profit of the shop

The SELECT clause uses the SUM function to calculate the total profit, which is the sum of the product of the quantity and price of
each product sold. The alias profit is used to label this calculated value.

oi.quantity is the quantity of a specific product that has been ordered, and p.price is the price of that product.

oi.quantity * p.price is the total revenue from selling that specific product.

By using SUM(oi.quantity * p.price) for all products sold, you get the total revenue from all product sales.

The FROM clause specifies the tables that you want to query. In this case, you are querying the product table and joining it with the
order_item table.

The INNER JOIN keyword is used to join the product and order_item tables based on the product_id field.

The ON clause specifies the condition for joining the tables, which is that the product_id field in the product table must match the
product_id field in the order_item table.
3. Find the orders managed by a Manager

The SELECT clause specifies the fields that you want to retrieve from the order table. You can replace * with the specific fields that
you are interested in.

The FROM clause specifies the tables that you want to query. In this case, you are querying the order table and joining it with the
manager table.

The INNER JOIN keyword is used to join the order and manager tables based on the manager_id field.

The ON clause specifies the condition for joining the tables, which is that the manager_id field in the order table must match the
manager_id field in the manager table.

4. Find the customers who have made 3 or more orders

The SELECT clause specifies the columns that you want to retrieve, which are client_id, firstName, and lastName from the client
table.

The FROM clause specifies the tables that you want to query, which are the client and order tables.

The INNER JOIN keyword is used to join the client and order tables based on the client_id field.
The GROUP BY clause is used to group the results by client_id, firstName, and lastName of the client table.

The HAVING clause filters the results to only include clients who have made 3 or more orders. The COUNT(o.order_id) function is
used to count the number of orders made by each client, and the >= operator is used to filter the results to only include clients who
have made 3 or more orders.

5. Return the average time difference from the order date to the shipping date for each type of product order status

This line specifies the columns that should be returned in the results: order_id and the average time difference, which is calculated
using the AVG() function and the DATEDIFF() function.

DATEDIFF() is used to calculate the difference in days between the order date (o.orderDate) and the shipped date (o.shippedDate).

day should actually be o.shippedDate to get the correct results. The result of the DATEDIFF() function is then passed to the AVG()
function, which calculates the average time difference across all orders.

These lines specify the tables that are being used in the query and how they are joined.

orders is the main table that contains order information, while order_item and product are joined to get the product information
associated with each order item.

The INNER JOIN clause is used to join the tables based on the common order_id and product_id columns.

This line specifies how the results should be grouped.

In this case, the results are grouped by order_id, which means that the average time difference is calculated for each unique order_id.

This ensures that the query returns one row per order, with the average time difference for each order.
2.5 Advanced queries: Stored procedures, scalor functions
a. Scalor functions

- A scalar function to retrieve a list of products that have been ordered by a specific customer. Ensure that this scalar function
only returns results for users with access rights as manager.

-
Explanation:

CREATE FUNCTION GetOrderedProductsByCustomer (@customerId INT) - Declare a Scalar Function with the name
GetOrderedProductsByCustomer, which takes one argument customerId.

RETURNS VARCHAR(MAX) - Specifies the return data type of the function as VARCHAR with a maximum size of MAX.

AS BEGIN - Start of a Function block.

DECLARE @result VARCHAR(MAX) - Declare a variable @result of data type VARCHAR with maximum size of MAX.

IF (SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE is_user_ process = 1 AND original_login_name = 'manager') = 0 -
Checks if the authenticated user has manager access by checking the number running instance (sessions) in SQL Server, if it is 0, user
is not allowed to execute Function.

BEGIN - Start of the IF command block.

SET @result = 'Unauthenticated user as manager.' - Assign the error message string to the @result variable.

RETURN @result - Returns the value of the @result variable and ends the execution of the Function.

SELECT @result = COALESCE(@result + ', ', '') + p.product_name FROM order o JOIN order_item oi ON o.order_id = oi.order_id
JOIN product p ON oi.product_id = p.product_id JOIN GIA customer c ON o .client_id = c.client_id WHERE c.client_id =
@customerId - Execute a SQL query to get a list of products ordered by a customer with the specified customer id.

RETURN @result - Returns the ordered list of products as a string and ends the execution of the Function.

END - Ended block command of Function.

GO - Function termination marker and separator between different SQL statements in the script.

- Use Function GetOrderedProductsByCustomer


GetOrderedProductsByCustomer with2. The function returns a comma-separated list of product names that have
been ordered by the customer with ID equal to 2.
b. Stored procedure

- Create a stored procedure to delete a product. Ensure that this stored procedure only executes when an authenticated user is a
manager.

Explanation:

CREATE PROCEDURE DeleteProduct @productId INT - This is a command to create a new stored procedure named
"DeleteProduct" with an input parameter named "productId" of data type INT.

AS BEGIN - Begins the block of commands for the stored procedure.


SET NOCOUNT ON; - Sets the NOCOUNT option to ON to prevent SQL Server from returning the number of rows affected by
DML statements. This helps improve the performance of the stored procedure.

IF (SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE is_user_process = 1 AND original_login_name = 'manager') = 0 -


Checks if the user has been authenticated. If the user has not been authenticated, the stored procedure will end and return an error
message. This statement checks the number of login sessions in the system and determines if the user has been authenticated. In this
case, only users with a login name of "manager" are allowed to execute the stored procedure.

BEGIN - Begins the command block for the IF statement.

RAISERROR('User not authenticated as a manager.', 16, 1) - Returns an error message if the user is not authenticated.

RETURN; - Ends the stored procedure.

END - Ends the command block for the IF statement.

DELETE FROM product WHERE product_id = @productId - Deletes a product from the "product" table based on the passed-in
"productId".

END - Ends the command block for the stored procedure.

GO - The GO keyword is used to separate batches of statements.

- Use Procedure DeleteProduct

This command executes the stored procedure called Delete Product with the product id value of 8.

c. Trigger

- Create a trigger to check the quantity of products in stock before adding a new order and raise an error message if the quantity
of products in stock is not sufficient to fulfill the order.
This code creates a trigger on the order_item table and is fired every time a record is added to the table. This trigger checks the number
of products in stock before adding a new order. If the number of products in stock is less than the ordered quantity, the trigger will issue
an error message and rollback the transaction to ensure that the data has not been changed. If there is no problem, the number of products
left in stock will be updated.

Line 1: Create a CheckInventory trigger on the order_item table, use AFTER INSERT to fire the trigger after a new record is added.

Lines 3-13: The trigger uses a temporary variable @productId to store the ID of the product in the newly added order_item record, and
a temporary @quantityInStock to store the number of products left in stock. The temporary variable @sales is used to store the number
of products ordered in the newly added record.

Line 4: Get the number of products ordered in the newly added record.

Lines 5-8: Get the product ID and the number of products left in stock from the product table.

Lines 9-13: Check the number of products left in stock. If the quantity in stock is less than the ordered quantity, the trigger will issue an
error message and rollback the transaction.

Lines 15-18: If there are no problems, the number of products left in stock will be updated by subtracting the number of products ordered.
Updates are performed on the product table using the UPDATE statement.

- Use Trigger
I will insert a new order with a quantity of products that exceeds the quantity of products in stock. For example, I will insert an order
with an ID of 11 and a product ID of 8 with an order quantity of 20, even though there are only 11 products left in stock.

The program will report an error because simply the products in the inventory are not sufficient in quantity to fulfill the customer's
order.
2.6 Evaluate the effectiveness of the database solution
In my database, all necessary entities and fields are available for users to utilize, such as managing employees, products, customers,
and their orders, allowing executives to run the company efficiently. Managers can also manage products, customers, and their orders.
Additionally, customers can purchase products, update their information, and provide feedback on their orders. However, these are all
basic functionalities, and my database has yet to implement any advanced performance optimizations. Despite being incomplete, I will
strive to improve it to the best of my knowledge and abilities.

Chapter 3 – Test the system

3.1 Test cases

To ensure that all commands adhere to user requirements, we have decided to plan to re-test all results of the functions and commands
above that we have set up, and ensure that the program operates as smoothly as possible and has no errors to be delivered to the end
user. Below is the order of our test cases and the reasons why we selected these cases for testing:

-Deleting an employee is one of the important functions of the FPT company system, which aims to ensure system safety to prevent
specific employee data from leaking out when this employee, in this case a manager, no longer works for the company.

-Deleting a product is a function for users to delete a product when the company no longer sells it, either because it is not suitable for
their field or for some other reason.

-Our program aims to store customer information to add potential customers, so there is no function to delete customers.

-Inserting an employee, in this case a manager, is a function used when someone successfully applies to the company and will be
added to the system by the director.

-Inserting a product is an important function of the system to ensure that the company has new products, and that these products will
be added to the system by the manager.

-Inserting feedback is a customer function when they have purchased a product and want to provide feedback on their reaction when
receiving the order.
-Updating customer information is a fairly important function used when customers want to update their phone number or email, or
when they register their name incorrectly.

-Getting a list of products that have been ordered by a specific customer, returning the result to the manager, checking the operation of
the void function. This is easy for the company manager to know which customers are potential customers.

-Getting a list of products that have been ordered by a specific customer, returning the result to the customer, checking the operation
of the void function. I want to check the system's security and privacy through whether the customer can view the company's
information or not.

-Deleting a product is executed when the requester is a manager. I want to check the security through the requester of the command.

-Deleting a product is executed when the requester is a client. I want to check the security through the requester of the command.

-Checking the quantity of products in stock when adding a new order, if the order quantity of the product is greater than the quantity
of the product in stock, an error message will be displayed.

NO. TEST CASE INPUT DATA EXPECTED RESULT ACTUALY RESULTS STATUS
DESCRIPTION
1 Deleting an ID = 6 1 row affected 1 row affected Pass
employee, in this
case a manager
2 Deleting a product Product_ID = 8 1 row affected 1 row affected Pass
3 Inserting an Manager_id="6", first A new manager record is A new Order record is Pass
employee, in this name = Robert, last name added to the database with added to the database with
case a manager = Dao, phone = the above input data the above input data
0373019563, email =
[email protected],
director_id = 1
4 Inserting a product Product_ID=1, Name=" A new Product record is A new Product record is Pass
iPhone 14 Pro ", added to the database with added to the database with
Description=" Latest high- the above input data the above input data
end smartphone from
Apple A", Price= 1099.99,
QuantityInStock = 100
5 Inserting feedback Feedback_id = 2, The procedure returns an The procedure returns an Pass
comment=" Could be error message saying that error message saying that
better ", Client_ID=1, the Client_ID is invalid the Client_ID is invalid
Order_ID=2
6 Updating customer Order_ID=10, first name = Update successfully from Update successfully from Pass
information Diana, last name = email = email =
Nguyen, phone = [email protected] to [email protected] to
11111122231, email = phone = 0399872898, email phone = 0399872898,
[email protected] = email =
update to first name = [email protected] [email protected]
Diana, last name =
Nguyen, phone =
0399872898, email =
[email protected]
7 Getting a list of client_id = 8 Iphone 14 pro, Dell XPS 13 Iphone 14 pro, Dell XPS Pass
products that have 13
been ordered by a
specific customer,
returning the result to
the manager
8 Getting a list of client_id = 7 User not authenticated as User not authenticated as Pass
a manager. a manager.
products that have
been ordered by a
specific customer,
returning the result to
the customer
9 Deleting a product is Product_id = 8 Deleting product with id = 8 Deleting product with id = Pass
executed when the successfull 8 successfull
requester is a
manager
10 Deleting a product is Product_id = 7 User not authenticated as User not authenticated as Pass
a manager. a manager.
executed when the
requester is a client
11 Checking the Feedback_id = 2, The procedure returns an The procedure returns an Pass
quantity of products comment=" Could be error message saying that error message saying that
in stock when adding better ", Client_ID=1, the Client_ID is invalid the Client_ID is invalid
a new order Order_ID=2

3.2 User documentation, Flowchart to show how the system works

3.2.1 User documentation


Documentation for users:

For customers: To log in to the system, users must have an account for customers, including email and password. Additionally, if
customers do not have an account to log in to the system, they must provide information such as name, phone number, address, email
address to register for an account. After the system receives accurate information, users will be redirected to the product purchase
page. When there are products in the shopping cart and customers want to buy them, the system will redirect customers to the payment
page, where consumers can check the accuracy of the product and view data such as price and quantity. After completing the payment,
consumers will receive an invoice and can give feedback on the quality of the product after receiving it in their hands.

For managers: Managers must have a login account including email and password provided by the director to access the system. After
logging in, managers will be redirected to the manager page. Managers can retrieve information about Products, Invoices, Stores,
Orders and Customers through the management page. Managers can add, update, and delete records in the system regarding products.

For the Director: To have access to the system, the Director must also have an account with an email and password. After the Director
logs into the system, the system will redirect to the Director page. The Director is the highest authority and has access to all
information systems, allowing them to monitor all managers. Direct access provides system functions, including the ability to add,
modify, and delete data.
3.2.2 Flowchart
a. Flowchart of system

Figure 20: Flowchart of system

- First we log into the system


- If you are a customer, the program will direct you to Buy products, comment and edit customer information
- If you are a manager, you can manage the shop:
 Here you can add, edit, delete, products, invoices
 See information in the comments section
- If you are a director, you can assign your employees to:
 Here you have the right to add, edit, delete, products, invoices but usually the director will only assign tasks to
his employees
b. Add function

Figure 21: Add function

Insert:

-Select object to insert

-Input data
-Check

-If yes, insert success data

-If no, go back input

c. Update Function

Figure 22: Update Function


Update:

-Select object to insert

-Input data

–Check

-If yes, update success data

-If no, go back input

c. Delete function
Figure 23: Delete Function

Delete:

-Select object to insert

-Choose data “product”

-Check -If yes, Delete success data

-If no, go back input

You might also like