SQL Snippet: Return Comma Delimited String

Microsoft SQL ServerIf you’ve been following this blog, you’ll know that I write a fair bit of SQL. I’m going to post some small snippets of SQL which I had to work out how to accomplish a small task as part of a larger script.

This first example, shows how to return a comma delimited string of vlues from a select instead of the usual multiline recordset:

/*
Created by Ian Grieve of azurecurve|Ramblings of a Dynamics GP Consultant (https://www.azurecurve.co.uk)
This code is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 UK: England & Wales (CC BY-NC-SA 2.0 UK).
*/
DECLARE @DOCDATE DATETIME = '2017-04-12'
SELECT (STUFF((
        SELECT
			', ' + RTRIM(CNTRLNUM)
        FROM
			PM00400
        WHERE
			DOCDATE = @DOCDATE
        ORDER BY
			CNTRLNUM
        FOR XML PATH('')
        ), 1, 2, '')
    ) AS ReturnString

The example above, is created against the Microsoft Dynamics GP sample database and returns a comma delimited list of vouchers for a particular date.

What should we write about next?

If there is a topic which fits the typical ones of this site, which you would like to see me write about, please use the form, below, to submit your idea.

Your Name

Your Email

Suggested Topic

Suggestion Details

Looking for support or consultancy with Microsoft Dynamics GP?

I no longer work with Microsoft Dynamics GP, but the last company I worked for was ISC Software in the UK; if you’re looking for support or consultancy services with Microsoft Dynamics GP you can contact them here.

Leave a Reply

Your email address will not be published. Required fields are marked *