Problems returning count in Stored Procedure
I have a stored procedure that loops through various tables to get the counts of listings in certain areas. The first part works fine. The second part always returns 0 for the count. I have the SP writing out the select count SQL statement, and when I run that in qry analyzer, it returns the correct count. What do I have to do/change to make the second part of my SP return te correct count?
Any help will be appreciated. The problem is in the block IF @type=A on the line where I set @count
I have marked this line below.
Thanks in advance,
P
Code below:
CREATE PROCEDURE dbo.sp_CompanyAreaCount
AS
DECLARE @area varchar(50)
DECLARE @count int
DECLARE @type char(1)
DECLARE @mlsAreas varchar(200)
DECLARE @tempAreas varchar(200)
DECLARE cl CURSOR FOR
SELECT AreaName, AreaType FROM CompanyArea
OPEN cl
FETCH NEXT FROM cl into @area, @type
WHILE @@FETCH_STATUS = 0
BEGIN
IF @type = 'C'
BEGIN
SET @count = (Select Count(*) as listingCount FROM listing WHERE City = @area)
UPDATE CompanyAreaTest SET Listings = @count WHERE AreaName = @area AND AreaType = 'C'
END
IF @type = 'A'
BEGIN
SET @mlsAreas = ''
DECLARE cm CURSOR FOR
SELECT IsNull(MLSArea, -1) FROM CompanyAreaDetail WHERE AreaName = @area
OPEN cm
FETCH NEXT FROM cm into @tempAreas
WHILE @@FETCH_STATUS = 0
BEGIN
set @mlsAreas = @mlsAreas + @tempAreas + ','
FETCH NEXT FROM cm INTO @tempAreas
END
set @mlsAreas = @mlsAreas + '-1'
Problem here --> SET @count = (Select Count(*) as listingCount FROM dbo.listing WHERE mapArea1 IN (@mlsAreas) AND mapArea1 <> '')
UPDATE CompanyAreaTest SET Listings = @count WHERE AreaName = @area AND AreaType = 'A'
print @area
print @mlsAreas
print @count
print "Select Count(*) as ListingCount FROM listing WHERE mapArea1 IN (" + @mlsAreas + ") AND MapArea1 <> ''"
CLOSE cm
DEALLOCATE cm
END
FETCH NEXT FROM cl INTO @area, @type
END
|