Professional Documents
Culture Documents
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
-- 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'))