Part 01 In this part you will learn how to create and use triggers: 1. Create a
ID: 3732570 • Letter: P
Question
Part 01 In this part you will learn how to create and use triggers: 1. Create a table called Customer_Archives that has the same columns as customers table and it also has a column that is called "Deletion_Date" 2. Create a Trigger on table Customers so that every time a record is deleted from table customers this same record is inserted in table Customer_Archives with the current date as Deletion_Date 3. Now insert a new customer into table Customers and then delete it. Is the record inserted correctly into table Customers Archive? Part 02 In this part we will learn how to use functions: 1. Create a functions that has the Customer_id as input and returns a number that represents the total cost of orders for this customer. Notice that you will need to multiply the Order Qty from table order_details and the Unit Price from table items to get the total cost of each order. 2. Now use the function: Write a select statement that selects all the customers and the total cost of the orders they have ever made.Explanation / Answer
ANSWER:
Part 01:
Lets say Customers table has columns
CustomerID, CustomerName, Address, CreationDate
1. CREATE TABLE Customer_Archives(
CustomerID INT NOT NULL,
CustomerName VARCHAR(1000) NOT NULL,
Address VARCHAR(MAX),
CreationDate DateTime,
DeletionDate DateTime
)
2.CREATE TRIGGER customerTrigger
ON dbo.Customers
FOR DELETE
AS
INSERT INTO Customer_Archives(CustomerID, CustomerName, Address, CreationDate,DeletionDate)
SELECT CustomerID, CustomerName, Address, CreationDate,Getdate() FROM deleted
GO
3.INSERT INTO Customers(CustomerID, CustomerName, Address, CreationDate)
VALUES (1,'Jane Doe','Park Street, London', GETDATE())
Deletion of records
DELETE FROM Customers WHERE CustomerID = 1
Part02:
1.CREATE FUNCTION dbo.udfGetTotalCosts(@CustomerID int)
RETURNS decimal(10,2) AS
BEGIN
DECLARE @ret decimal(10,2);
SELECT @ret = SUM(od.Order_Qty*up.Price)
FROM order_details od
INNER JOIN Unit_Price up
ON od.UnitID = up.UnitID
WHERE od.CutomerID = @CustomerID
IF (@ret IS NULL)
SET @ret = 0;
RETURN @ret;
END;
GO
2. SELECT CustomerID, CustomerName, dbo.udfGetTotalCosts(CustomerID)
FROM dbo.Customers