1

Here the code from my function:

-- Get Country Names
DECLARE getCountriesName CURSOR FOR
    SELECT c.Name
    FROM VocabCountry c
        RIGHT OUTER JOIN ProjectCountryRelations cr
            ON cr.CountryId = c.Id
    WHERE 
        c.Id = @project_id;

-- Finally Create list to return 
OPEN getCountriesName;
FETCH NEXT FROM getCountriesName INTO @Name;
WHILE @@FETCH_STATUS = 0
BEGIN  

    SET @listOfItems = @listOfItems + @Name + ', '
    FETCH NEXT FROM getCountriesName INTO @Name;

END;
CLOSE getCountriesName;
DEALLOCATE getCountriesName;

I am expecting a list of comma separated values, for example, like so:

Canada, United States of America,

I verified that the SELECT returns the countries expected.

Thanks for any help!

Eric

3
  • What output does the above code produce? I think you forgot the '@' in front of your cursor. Commented Jul 11, 2012 at 14:31
  • 1
    Do you initialize @listOfItems to anything before the loop? Commented Jul 11, 2012 at 14:35
  • 3
    "I am expecting ..." - okay, fine. But with us not having your tables and data, it's worth telling us what you're currently getting. I'm guessing NULL (as would @MikaelEriksson, I think) Commented Jul 11, 2012 at 14:38

2 Answers 2

2

If you're on SQL Server 2008 or newer, you could easily do this with a single SELECT and some FOR XML PATH magic :-)

SELECT 
    STUFF(
       (SELECT ',' + c.Name
        FROM VocabCountry c
        RIGHT OUTER JOIN ProjectCountryRelations cr
        ON cr.CountryId = c.Id
        FOR XML PATH('')
       ), 1, 1, '')

That should return a comma-separated list of those country names for you. No ugly and awful cursor needed!

Sign up to request clarification or add additional context in comments.

Comments

2

Using the FOR XML PATH will concat the values with commas.

Using the STUFF Function will remove the first comma you don't want.

So use this:

SELECT 
    STUFF(
       (SELECT ',' + c.Name
        FROM VocabCountry c
        RIGHT OUTER JOIN ProjectCountryRelations cr
        ON cr.CountryId = c.Id
        WHERE cr.Id = @project_id
        FOR XML PATH('')
       ), 1, 1, '');

See this fiddle: http://sqlfiddle.com/#!3/fd648/21

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.