Home Forums SQL Server 2005 SQL Server Newbies How to Group and batch select/cursor results in stored procedure RE: How to Group and batch select/cursor results in stored procedure

  • It was a valiant attempt at sample data, but unfortunately it's not quite there. Here are a few of the errors:

    No insert statement for the table

    Word often uses 'smart quotes' which don't translate correctly back into sql and cause issues.

    You only used the # temp table for the initial check, not for the table you created.

    commas before the union alls

    invalid number of columns in the sample data compared to the table.

    Etc. etc. I tried to fix it for a while but there were simply too many mistake to correct. You could probably actually pick up quite a bit just by figuring out how to fix all these errors in your test data. The goal is for us to be able to copy/paste/run this in SSMS and have a small example of your table's data. Massage that script(use a dev or test server) until you get it all working and you'll get a better understanding of how it works. Also, not sure if those email addresses are real or not, but you want to be really careful of actual data when you post sample data on the internet.

    For your actual problem:

    First, Consider using the new ANSI style joins instead of the old style

    Second, I will probably get yelled at by someone for suggesting nested cursors here, so I'll throw out a disclaimer that this is almost never the best solution. Try to avoid cursors for the most part.

    At a glance, it looks like you're trying to pull in all the information into a cursor then loop through that cursor. The problem with this is that each message is on a different row and you're only accessing 1 row at a time. Going with a nested cursor approach for something like this, you'd want the outer cursor to pull in just the email address/name of each individual you're sending a message to, then the inner cursor would pull all the actual notes for each one, concatenate them into the body then exit. Your parent cursor would send the message then loop.

    Here's the gist of what I mean

    Take your current select statement and insert it into a temp table.

    SELECT...

    INTO #temp

    FROM...

    WHERE...

    order by...

    Use just the emailaddress as the declaration of the outer cursor

    DECLARE CURSOR... --Outer

    SELECT DISTINCT emailaddress

    FROM #Temp

    BEGIN

    Within that:

    DECLARE CURSOR--Inner

    SELECT...(all other fields)

    FROM #Temp

    WHERE emailaddress = @emailaddress

    BEGIN

    --Concatenate message fields

    END

    CLOSE / DEALLOCATE --Inner

    --Send email

    END

    CLOSE / DEALLOCATE --Outer

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]