forked from HOGENT-Databases/DB2-Workshops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemp-tables-1.sql
30 lines (26 loc) · 1.05 KB
/
temp-tables-1.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
ALTER PROCEDURE DeleteOrdersFromSupplier3
@supplierid INT,
@nrdeletedorders INT OUT,
@nrdeleteddetails INT OUT
AS
SET NOCOUNT ON;
IF NOT EXISTS (SELECT NULL FROM Supplier WHERE SupplierID = @supplierid)
BEGIN
DECLARE @message NVARCHAR(200) = FORMATMESSAGE('Supplier with id: %d, does not exist',@supplierid);
THROW 50000,@message,1; -- always use ; in front of throw.
-- FormatMessage cannot directly be used in a THROW statement.
END;
-- Create a temp. table
CREATE TABLE #Orders (OrderID INT) -- Note the '#'
-- Insert all orders in scope in the temp. table
INSERT INTO #Orders
SELECT DISTINCT OrderID
FROM OrdersDetail
JOIN Product on Product.ProductID = OrdersDetail.ProductID
WHERE SupplierID = @supplierid;
-- Delete all orderdetails based on the temp. table
DELETE FROM OrdersDetail WHERE OrderID IN (SELECT OrderID FROM #Orders);
SET @nrdeleteddetails = @@ROWCOUNT;
-- Delete all orders based on the temp. table
DELETE FROM Orders WHERE OrderID IN (SELECT OrderID FROM #Orders);
SET @nrdeletedorders = @@rowcount;