forked from HOGENT-Databases/DB2-Workshops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic-sql-1.sql
28 lines (23 loc) · 834 Bytes
/
dynamic-sql-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
CREATE PROCEDURE SP_ProductClass_By_Country_Amount
AS
DECLARE CountryCursor CURSOR FOR
(
SELECT DISTINCT Country
FROM Product
JOIN Supplier on Product.SupplierID = Supplier.SupplierID
)
DECLARE @sqlString VARCHAR(4000) = ''
DECLARE @country varchar(100);
SET @sqlString = 'SELECT Product.ProductClassID,'
OPEN CountryCursor
FETCH NEXT FROM CountryCursor into @country
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlString += 'SUM(CASE WHEN Supplier.Country=''' + @country + ''' THEN 1 ELSE 0 end) AS ' + ''''+@country+''','
FETCH NEXT FROM CountryCursor into @country
END
DEALLOCATE CountryCursor
SET @sqlString += 'COUNT(Product.ProductId) TOTAL FROM PRODUCT JOIN Supplier on Product.SupplierID = Supplier.SupplierID '
SET @sqlString += 'GROUP BY Product.ProductClassID';
PRINT @sqlString
EXECUTE (@sqlString);