You are on page 1of 3

-- CSC3326

2013

Database Systems

Summer

-- 1) Stored procedure to implement the anonymous Procedural SQL block from text
book (p.280)
CREATE PROCEDURE sp_prices @w_width INTEGER, @w_max INTEGER AS
BEGIN
DECLARE @w_p1 INTEGER,
@w_p2 INTEGER,
@w_num INTEGER
SET @w_p1 = 0
SET @w_p2 = 10
WHILE (@w_p2 < @w_max)
BEGIN
SET @w_num = (SELECT COUNT(*)
FROM Product
WHERE p_price BETWEEN @w_p1 AND @w_p2)
PRINT 'There are '+ cast(@w_num as VARCHAR) + ' Products with price between
' +
cast(@w_p1 as VARCHAR) + ' and ' + cast(@w_p2 as VARCHAR)
SET @w_p1 = @w_p2 + 1
SET @w_p2 = @w_p2 + @w_width
END
END
-- Example use:
EXEC sp_prices 50, 300

-- 2) Procedural SQL function to return the number of invoices by customer name


CREATE FUNCTION invoice_count(@c_lame NVARCHAR(30)) RETURNS INT AS
BEGIN
RETURN (SELECT COUNT(*)
FROM Invoice I JOIN Customer C ON I.cus_code = C.cus_code
WHERE cus_lname = @c_lame
)
END
-- Example uses:
SELECT dbo.invoice_count('Dunne')
SELECT cus_code, dbo.invoice_count(cus_lname)
FROM Customer

-- 3) Trigger created on Line table insertion, to update the invoice total amoun
t:
-- First, add column inv_amount of type MONEY, in the table Invoice:
ALTER TABLE Invoice ADD inv_amount MONEY NOT NULL DEFAULT 0
-- Now, create the following trigger
CREATE TRIGGER T_Line ON Line FOR INSERT AS
BEGIN
UPDATE Invoice
SET inv_amount = inv_amount + (SELECT SUM(line_units * line_price)
FROM INSERTED
WHERE inv_number = Invoice.inv_number)
WHERE inv_number IN (SELECT DISTINCT inv_number FROM INSERTED)
END
-- Now, insert some invoice lines, and check that the corresponding invoice amou
nt is updated accordingly
INSERT Line VALUES(1001, 3, '54778-2T', 2, (SELECT p_price FROM Product WHERE p_
code = '54778-2T'))

-- 4) Stored procedure that uses a cursor to display customers within an area co


de:
CREATE PROCEDURE sp_customers @c_area CHAR(3) AS
BEGIN
DECLARE @code VARCHAR(11),
@fname VARCHAR(20),
@lname VARCHAR(40),
@message VARCHAR(80)
DECLARE Cur_cust CURSOR FOR
SELECT cus_code, cus_fname, cus_lname
FROM Customer
WHERE cus_areacode = @c_area
ORDER BY cus_code
OPEN Cur_cust
PRINT'-------- Customers report --------'
FETCH NEXT FROM Cur_cust INTO @code, @fname, @lname
WHILE @@FETCH_STATUS = 0
-- fetch statement successful
BEGIN
PRINT ' '
SET @message = '----- Customer : ' + @code + ' ' + @fname + ' ' + @lname
PRINT @message

-- Get the next Customer


FETCH NEXT FROM Cur_cust INTO @code, @fname, @lname
END
CLOSE Cur_cust
DEALLOCATE Cur_cust
END
-- Example use:
EXEC sp_customers '615'

You might also like