| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

Lecture - Advanced Stored Procedures

Page history last edited by Dr. Ron Eaglin 10 years, 5 months ago
 

Video Template Title

 

Summary of Video

 

This video demonstrates using dynamic SQL and database cursors to perform relatively complex SQL queries.

 

Prerequisites

 

The lecture uses the Lookup table example  Lecture - Lookup Tables Part 1

 

The Data Dictionary used in this lecture is available at http://www.census.gov/acs/www/Downloads/data_documentation/pums/DataDict/PUMS_Data_Dictionary_2009-2011.pdf 

 

The Data used in this lecture is uploaded here FL_Housing_Data_2006.zip

 

Video Link

 

http://online1.daytonastate.edu/player2.php?id=d4a897919a124958e699170b2b1dc8f2 

 

 

http://www.youtube.com/watch?v=B9zKi8H_IUs 

 

Support Materials

 

ALTER PROCEDURE sp_ACRReport (
 @ColCategory NVARCHAR(50)
)
AS
BEGIN 
-- This report creates a count of entries of a specific field
-- specified by @RowCategory, broken down by @ColCategory
 
-- We are going to use a CURSOR for Rows   
DECLARE Col_Cursor CURSOR FOR   
    SELECT [Name], [Description]
    FROM dbo.Codes 
    WHERE [CategoryName] = @ColCategory
-- Next we will create a place to put the cursor results
DECLARE @CatDescription NVARCHAR(200)
DECLARE @Query NVARCHAR(500)
DECLARE @ColCodeName NVARCHAR(50)
DECLARE @ColCodeDescription NVARCHAR(200)
SET @CatDescription = (SELECT [Description] FROM Categories WHERE Name = @ColCategory)
-- Cursors are Opened and Closed    
-- For each row we enumerate, we want the 
OPEN Col_Cursor
FETCH NEXT FROM Col_Cursor INTO @ColCodeName, @ColCodeDescription
WHILE (@@FETCH_STATUS <> -1)
BEGIN
  PRINT ''
  PRINT '-- ' + LEFT(@CatDescription, 50) + ' = ' + @ColCodeDescription + '  --'
  SET @Query ='SELECT LEFT([Codes].[Description], 50), COUNT(*) As ''Number Units'' 
    FROM RawData, Codes, Categories 
    WHERE RawData.ACR = Codes.Name
    AND   Codes.CategoryName = ''ACR''
    AND   RawData.' + @ColCategory + ' = ''' + @ColCodeName + ''' 
    GROUP BY [Codes].[Description]'  
  EXECUTE(@Query)
 
  FETCH NEXT FROM Col_Cursor INTO @ColCodeName, @ColCodeDescription
END
CLOSE Col_Cursor
DEALLOCATE Col_Cursor  
END 

 

Example of a filtered query using this database

SELECT [Codes].[Description], COUNT(*) As 'Number Units' FROM RawData, Codes, Categories 
    WHERE RawData.ACR = Codes.Name
    AND   Codes.CategoryName = 'ACR'
    AND   RawData.FS = '1' 
    GROUP BY [Codes].[Description] 

 

 

All Materials Copyright 2012 Dr. Ron Eaglin

Comments (0)

You don't have permission to comment on this page.