I am having an issue I honestly have no idea how to fix.
I have a query that is doing a loop basically, with a execute command. And my results are being returned with blanks, where the statement would have a blank set of data basically.
I.E. I get multiple result sets returned as expected, and a whole lot returned with no data in them.
Please give me a hand, I really am completely lost and its driving me mad here.
DECLARE @CustomerRegion NVARCHAR(30)
DECLARE @Groups NVARCHAR(30)
DECLARE @BRANCH NVARCHAR(7)
DECLARE @getid CURSOR
SET @BRANCH = N'Patleys'
SET @getid = CURSOR FOR
SELECT
[Main_Reporting].[dbo].[Sales].[Customer Region],
[Main_Reporting].[dbo].[Sales].[Groups]
FROM
[Main_Reporting].[dbo].[Sales]
OPEN @getid
FETCH NEXT FROM @getid INTO @CustomerRegion, @Groups
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ('SELECT [Branch]
,[cust-number]
,[Customer Region]
,[Groups]
FROM [Main_Reporting].[dbo].[Sales]
WHERE -- Missed
[Customer Region] != ''1''
AND [Customer Region] = ''' + @CustomerRegion + '''
AND [Groups] = ''' + @Groups + '''
GROUP BY
[Branch], [cust-number]
, [Customer Region], [Groups]
ORDER BY
MAX([invoice-date]) DESC')
FETCH NEXT FROM @getid INTO @CustomerRegion, @Groups
END
CLOSE @getid
DEALLOCATE @getid
--Edited--
Sorry I am doing the Loop because its going to Generate a file output with the possible combinations of Group and Customer Region.
So I will have in this instance 10 different files, each with the data that is Distinct for Group and Customer Region.
Rather than generating several scripts each loop would run, and then output to a file and move onto the next. This way i thought would be better in that if I added anything new, E.I. we have a new group join in, we would have another report generate with its unique data in it.
Hope this helps, sorry for the vague explination earlier.
You need to include your where criteria in your cursor. " [Customer Region] != ''1''" is in the select inside the cursor. When you happen upon a record where the customer region is 1, you get blanks.