﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / Article Discussions / Article Discussions by Author / Discuss content posted by Puja Shah  / Generating a Distinct Delimited List Using XML / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Wed, 19 Jun 2013 15:14:28 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Hi all,Thank you very much. I liked your suggestions &amp; different but better solutions.Regards,Puja</description><pubDate>Fri, 02 Jul 2010 00:01:36 GMT</pubDate><dc:creator>Puja Shah</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[quote][b]chris.fauvel (6/30/2010)[/b][hr][quote][b]Bradley Deem (6/29/2010)[/b][hr]I recommend using a CLR for this.  Microsoft has a great example here [url]http://msdn.microsoft.com/en-us/library/ms131056.aspx[/url].  I'm curious what the performance differences are.  Admittedly, I have not compared the two because I've never had the CLR function not perform adequately.You can then use this as an aggregate, for example.[code="sql"]SELECT dbo.List(myColumn)FROM myTableGROUP BY SomeOtherColumn[/code][/quote]What version of SQLSERVER are you running with CLR? Any issues with the server crashing? Could the server crash if the CLR has an unhandled exception?I see the power of CLR, but the boss and I are scared for the database.ThanksChris[/quote]For this task you could build a SQL CLR assembly using the strictest permission set (SAFE), which indicates all managed code and no access to any external resources.  It's highly unlikely you could write an assembly that would corrupt the memory space with SAFE permissions, but even if you could it would be limited to just the managed memory space and wouldn't bring down the server.There are some things to know about using SQL CLR:* SQL Server caches SQL CLR assemblies after it loads them the first time, for efficiency.  In the case of memory pressure, SQL CLR assemblies are one of the first things to get unloaded.  If you are on a machine with a lot of memory pressure SQL Server will need to reload your assemblies every time, adding overhead and cutting into any efficiency gains from using SQL CLR.* When you're doing string concatenation operations like this you probably want to use an efficient .NET StringBuilder object to maximize efficiency.  Normal string concatenation is notoriously slow because strings are immutable (a copy of the string is made everytime it is modified).* SQL Server can't accurately cost a SQL CLR assembly in a query plan since it has no idea what you're doing in there.* In some cases SQL CLR can prevent parallelization in query plans.  When you pass in LOB (varchar(max), etc.) parameters to it, for instance.  That may not be an issue in this case, but is something to be aware of.* You need to explicitly handle NULLs on the .NET side when you use SQL CLR.  One of the biggest mistakes I've seen is SQL CLR code that pretends NULLs don't exist.  That usually results in hard-to-troubleshoot exceptions from the .NET side.If you keep these things in mind, you shouldn't have any problems with SQL CLR.  This particular exercise would actually make a very nice introduction to SQL CLR.Mike C</description><pubDate>Wed, 30 Jun 2010 09:50:39 GMT</pubDate><dc:creator>Mike C</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[quote][b]Jeff Moden (6/30/2010)[/b][hr]Nice to see someone else ramp it up for a change.  Nicely done Michael. :-DThe next thing we need to teach is that returning results to the screen is a performance testing error known as "The Great Equalizer". :hehe:[/quote]As usual you're 2 steps ahead of me Jeff :smile:The only thing I wanted to add is that a performance test should be run multiple times to get a good read, they need to be sure to clean buffers and drop cache, and the difference between 2 and 4 ms in performance tuning terms is literally a rounding error :)Mike C</description><pubDate>Wed, 30 Jun 2010 09:20:15 GMT</pubDate><dc:creator>Mike C</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[quote][b]Bradley Deem (6/30/2010)[/b][hr][quote][b]chris.fauvel (6/30/2010)[/b][hr][quote][b]Bradley Deem (6/29/2010)[/b][hr]I recommend using a CLR for this.  Microsoft has a great example here [url]http://msdn.microsoft.com/en-us/library/ms131056.aspx[/url].  I'm curious what the performance differences are.  Admittedly, I have not compared the two because I've never had the CLR function not perform adequately.You can then use this as an aggregate, for example.[code="sql"]SELECT dbo.List(myColumn)FROM myTableGROUP BY SomeOtherColumn[/code][/quote]What version of SQLSERVER are you running with CLR? Any issues with the server crashing? Could the server crash if the CLR has an unhandled exception?I see the power of CLR, but the boss and I are scared for the database.ThanksChris[/quote]CLR is just like any other feature.  Spend some time researching the in and outs so you will be fine.  In regards to your questions, this CLR function was implemented into 2005 and we recently upgraded to 2008 without any problems (in regards to the CLR).  If your CLR throws an unhandled exception it will be returned to SQL; it will not crash your server.  Of course, there are caveats, you could always build a CLR that could bring down a server, but I would find it hard to believe you'd knowingly put such volatile code in a CLR untested for production.On a side note, one of the changes to CLR in 2008 is removing the restriction of 8000 byte max.  This means you could return a list of elements of size varchar(max).[/quote]Unfortunately we are still at 2005, we have plans to go to 2008, but there is SOOOOO MUCH regression testing that it would preclude enhancements to the apps for several months. :-(  ugh</description><pubDate>Wed, 30 Jun 2010 08:19:20 GMT</pubDate><dc:creator>chris.fauvel</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[quote][b]chris.fauvel (6/30/2010)[/b][hr][quote][b]Bradley Deem (6/29/2010)[/b][hr]I recommend using a CLR for this.  Microsoft has a great example here [url]http://msdn.microsoft.com/en-us/library/ms131056.aspx[/url].  I'm curious what the performance differences are.  Admittedly, I have not compared the two because I've never had the CLR function not perform adequately.You can then use this as an aggregate, for example.[code="sql"]SELECT dbo.List(myColumn)FROM myTableGROUP BY SomeOtherColumn[/code][/quote]What version of SQLSERVER are you running with CLR? Any issues with the server crashing? Could the server crash if the CLR has an unhandled exception?I see the power of CLR, but the boss and I are scared for the database.ThanksChris[/quote]CLR is just like any other feature.  Spend some time researching the in and outs so you will be fine.  In regards to your questions, this CLR function was implemented into 2005 and we recently upgraded to 2008 without any problems (in regards to the CLR).  If your CLR throws an unhandled exception it will be returned to SQL; it will not crash your server.  Of course, there are caveats, you could always build a CLR that could bring down a server, but I would find it hard to believe you'd knowingly put such volatile code in a CLR untested for production.On a side note, one of the changes to CLR in 2008 is removing the restriction of 8000 byte max.  This means you could return a list of elements of size varchar(max).</description><pubDate>Wed, 30 Jun 2010 08:11:56 GMT</pubDate><dc:creator>Bradley Deem</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[quote][b]Mike C (6/29/2010)[/b][hr]How's this for data? :)[code]CREATE TABLE #Role(	RoleName VARCHAR(100));GOINSERT INTO #Role(	RoleName)VALUES ('Accounting'), ('Approver'), ('Developer'), ('International Sales Manager'), ('Marketing'), ('System Administrator'),('Technical Customer'), ('Technical Director'), ('Training');GOCREATE TABLE #UserRole (	UserID INT NOT NULL,	RoleName VARCHAR(100) NOT NULL,	ProjectID INT NOT NULL,	RoleAssignedDate DATETIME NOT NULL,	PRIMARY KEY	(		UserID,		RoleName,		ProjectID,		RoleAssignedDate	));GOCREATE TABLE #Numbers(	Num INT NOT NULL PRIMARY KEY);GOWITH DIGITSAS(	SELECT 0 AS Num	UNION ALL	SELECT Num + 1	FROM DIGITS	WHERE Num &amp;lt; 10)INSERT INTO #Numbers(	Num)SELECT NumFROM DIGITS;GOWITH NUMBERSAS(	SELECT HundredThousand.Num * 100000 + TenThousand.Num * 10000 + 		Thousand.Num * 1000 + Hundred.Num * 100 +		Ten.Num + One.Num AS Num	FROM #Numbers HundredThousand	CROSS JOIN #Numbers TenThousand	CROSS JOIN #Numbers Thousand	CROSS JOIN #Numbers Hundred	CROSS JOIN #Numbers Ten	CROSS JOIN #Numbers One),RANDOMDATAAS(	SELECT Num AS UserID,		RoleName,		ABS(CHECKSUM(NEWID()) % 8000) + 1000 AS ProjectID,		DATEADD(DAY, -ABS(CHECKSUM(NEWID()) % 1000), GETDATE()) AS RoleAssignedDate,		NEWID() AS SortOrder	FROM NUMBERS	CROSS JOIN #Role)INSERT INTO #UserRole(	UserID,	RoleName,	ProjectID,	RoleAssignedDate)SELECT TOP(1000000) UserID,	RoleName,	ProjectID,	RoleAssignedDateFROM RANDOMDATAORDER BY SortOrder;GO[/code][/quote]Nice to see someone else ramp it up for a change.  Nicely done Michael. :-DThe next thing we need to teach is that returning results to the screen is a performance testing error known as "The Great Equalizer". :hehe:</description><pubDate>Wed, 30 Jun 2010 06:53:51 GMT</pubDate><dc:creator>Jeff Moden</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[quote][b]Bradley Deem (6/29/2010)[/b][hr]I recommend using a CLR for this.  Microsoft has a great example here [url]http://msdn.microsoft.com/en-us/library/ms131056.aspx[/url].  I'm curious what the performance differences are.  Admittedly, I have not compared the two because I've never had the CLR function not perform adequately.You can then use this as an aggregate, for example.[code="sql"]SELECT dbo.List(myColumn)FROM myTableGROUP BY SomeOtherColumn[/code][/quote]What version of SQLSERVER are you running with CLR? Any issues with the server crashing? Could the server crash if the CLR has an unhandled exception?I see the power of CLR, but the boss and I are scared for the database.ThanksChris</description><pubDate>Wed, 30 Jun 2010 06:44:41 GMT</pubDate><dc:creator>chris.fauvel</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>I found Brian's 2nd solution easier to understand....I dig the STUFF...never used that before.</description><pubDate>Wed, 30 Jun 2010 06:36:18 GMT</pubDate><dc:creator>chris.fauvel</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>I didn't get a chance to run any tests against the data (it was a little late when I posted that), but one thing worth considering is whether or not a specific indexing strategy/index changes can improve the results.  I slapped a clustered PK on the sample data, but not necessarily the most efficient for any given query.ThanksMike C</description><pubDate>Wed, 30 Jun 2010 05:57:31 GMT</pubDate><dc:creator>Mike C</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>I did the test and combined Mike's test data with (most of) the suggestions:*** Peso ***********************************************************************[code="other"]SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 0 ms.UserID      Roles----------- -------------------------------------------------------------------------------------------------------------------------------------1           Technical Director,Technical Customer2           R&amp;D,Approver4           International Sales Manager,Marketing,System Administrator,Technical Customer...1111018     International Sales Manager,Technical Director1111019     Approver,Marketing1111020     Approver(210092 row(s) affected)Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210093, logical reads 641750, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 7719 ms,  elapsed time = 7917 ms.[/code]*** Puja Shah ******************************************************************[code="other"]SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 0 ms.UserID      Roles----------- -------------------------------------------------------------------------------------------------------------------------------------1           Technical Director, Technical Customer2           R&amp;D, Approver4           International Sales Manager, Marketing, System Administrator, Technical Customer...1111018     International Sales Manager, Technical Director1111019     Approver, Marketing1111020     Approver(210092 row(s) affected)Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210095, logical reads 641749, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.Table 'Worktable'. Scan count 1210296, logical reads 3993980, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 1509437 ms,  elapsed time = 772965 ms.[/code]*** Kailash Mishra *************************************************************[code="other"]SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 0 ms.UserID      ----------- -------------------------------------------------------------------------------------------------------------------------------------1           Technical Customer,Technical Director2           Approver,R&amp;D4           International Sales Manager,Marketing,System Administrator,Technical Customer...1111018     International Sales Manager,Technical Director1111019     Approver,Marketing1111020     Approver(210092 row(s) affected)Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210095, logical reads 641749, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.Table 'Worktable'. Scan count 1210312, logical reads 4167863, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 103482 ms,  elapsed time = 54131 ms.[/code]*** R.P.Rozema ****************************************************************[code="other"]SQL Server parse and compile time:    CPU time = 0 ms, elapsed time = 13 ms.SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 0 ms.UserID      Roles----------- -------------------------------------------------------------------------------------------------------------------------------------1           Technical Director, Technical Customer2           R&amp;D, Approver4           International Sales Manager, Marketing, System Administrator, Technical Customer...1111018     International Sales Manager, Technical Director1111019     Approver, Marketing1111020     Approver(210092 row(s) affected)Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210093, logical reads 641750, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 20672 ms,  elapsed time = 21298 ms.[/code]*** Brian Barkauskas 1st ****************************************************************[code="other"]SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 0 ms.UserID      RoleName----------- -------------------------------------------------------------------------------------------------------------------------------------8           Marketing, Technical Director, Training, Accounting, Approver9           Accounting, R&amp;D, Developer10          Accounting, R&amp;D, Technical Customer, System Administrator, Training...1111014     Approver, Technical Director, Training, System Administrator1111015     Developer, Training1111016     Marketing, R&amp;D(210092 row(s) affected)Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 974634, logical reads 2944527, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.Table 'Worktable'. Scan count 1210315, logical reads 4196120, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 96921 ms,  elapsed time = 51262 ms.[/code]*** Brian Barkauskas 2nd ****************************************************************[code="other"]SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 0 ms.UserID      RoleName----------- -------------------------------------------------------------------------------------------------------------------------------------1           Technical Director, Technical Customer2           R&amp;D, Approver4           International Sales Manager, Marketing, System Administrator, Technical Customer...1111018     International Sales Manager, Technical Director1111019     Approver, Marketing1111020     Approver(210092 row(s) affected)Table '#UserRole___________________________________________________________________________________________________________0000000007DC'. Scan count 210093, logical reads 641750, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 8000 ms,  elapsed time = 8233 ms.[/code]Soooooooo... Granted, Brian's 2nd is faster than my suggestion. However, that 2nd suggestion is nearly identical to Peso's suggestion, so you can hardly claim credit for that.Plus, as you can not see due to the forum code translating the &amp; amp ; in the output back into &amp;, I've added 'R&amp;D' as a role. Mine is the only suggestion that correctly returns 'R&amp;D' instead of 'R&amp; amp ;D' (without the spaces).To see what the difference is I also tried changing the case row_number() when 1 then '' else ',' end construct into the stuff( ..., 1, 2, '')-construction in my suggestion and found out that the stuff construction is indeed faster: about 0.013ms per row. Resulting in a gain of roughly 3 seconds for these 200K rows. So it is better to use stuff() on the result to replace the first ',' in the resulting string than to use case row_number to suppress the ',' on only the first role name.In conclusion: When you can guarantee the role name will never contain any of &amp;, &amp;lt; or &amp;gt;, use this:[code="sql"]-- PesoPRINT '*** Peso ***********************************************************************'SELECT          b.UserID,                STUFF(f.Roles, 1, 1, '') AS RolesFROM            (                        SELECT          UserID                        FROM            #UserRole                        GROUP BY        UserID                ) AS bCROSS APPLY     (                        SELECT          TOP(100) PERCENT                                        ',' + w.RoleName                        FROM            #UserRole AS w                        WHERE           w.UserID = b.UserID                        GROUP BY        w.RoleName                        ORDER BY        MIN(RoleAssignedDate)                        FOR XML         PATH('')                ) AS f(Roles)ORDER BY        b.UserID[/code]If however your role name can contain any of the characters &amp;, &amp;lt; or &amp;gt;, use this -at the cost of almost doubling the required cpu time from 8250 ms to 17203 ms for these 210092 rows- :[code="sql"]PRINT '*** Peso &amp; R.P.Rozema ****************************************************************'SELECT          b.UserID,                STUFF(f.Roles.value('.','nvarchar(max)'), 1, 1, '') AS RolesFROM            (                        SELECT          UserID                        FROM            #UserRole                        GROUP BY        UserID                ) AS bCROSS APPLY     (                        SELECT          ',' + w.RoleName as [text()]                        FROM            #UserRole AS w                        WHERE           w.UserID = b.UserID                        GROUP BY        w.RoleName                        ORDER BY        MIN(RoleAssignedDate)                        FOR XML         PATH(''), type                ) AS f(Roles)ORDER BY        b.UserID[/code]Or cheat and do the translation of the xml escaped characters yourself too, reducing the loss of performance a little to 13985 ms cpu time on the same data set:[code="sql"]PRINT '*** Peso &amp; R.P.Rozema ****************************************************************'SELECT          b.UserID,                replace(replace(replace(STUFF(f.Roles, 1, 1, ''), '&amp;', '&amp;'), '&amp;lt', '&amp;lt;'), '&amp;gt', '&amp;gt;') AS RolesFROM            (                        SELECT          UserID                        FROM            #UserRole                        GROUP BY        UserID                ) AS bCROSS APPLY     (                        SELECT          ',' + w.RoleName as [text()]                        FROM            #UserRole AS w                        WHERE           w.UserID = b.UserID                        GROUP BY        w.RoleName                        ORDER BY        MIN(RoleAssignedDate)                        FOR XML         PATH('')                ) AS f(Roles)ORDER BY        b.UserID[/code]</description><pubDate>Wed, 30 Jun 2010 04:39:33 GMT</pubDate><dc:creator>R.P.Rozema</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>I did something similar the other month to demonstrate the use of XML data, and how to remove the dreaded cursors from the code, granted it was written on an intitally small set and there was not requirement for Ordering the data in the output list.The main difference was that I prefixed the list with a Comma, this mean that I could simply do a substring(XMLString,2,4000), the code looked like this Select Distinct  EmployeeID ,Substring(Replace    (Replace((Select ','+SkillData        From #tmp        where EmployeeID=a.EmployeeID       FOR XML RAW),'&amp;lt;Row Data="',''),'"/&amp;gt;',''),2,4000) Datafrom #tmp aThe XML data before the Replace is run looked like&amp;lt;row Data=",UU"/&amp;gt;&amp;lt;row Data=",WW"/&amp;gt;&amp;lt;row Data=",XX"/&amp;gt;&amp;lt;row Data=",ZZ"/&amp;gt;After the replace you had a string that looked like this ",UU,WW,XX,ZZ"The downside is the distinct has on large data sets it could have an impact. Having said that I do like the look of some of the pure T-SQL scripts.</description><pubDate>Wed, 30 Jun 2010 02:20:20 GMT</pubDate><dc:creator>Jason-299789</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>How's this for data? :)[code]CREATE TABLE #Role(	RoleName VARCHAR(100));GOINSERT INTO #Role(	RoleName)VALUES ('Accounting'), ('Approver'), ('Developer'), ('International Sales Manager'), ('Marketing'), ('System Administrator'),('Technical Customer'), ('Technical Director'), ('Training');GOCREATE TABLE #UserRole (	UserID INT NOT NULL,	RoleName VARCHAR(100) NOT NULL,	ProjectID INT NOT NULL,	RoleAssignedDate DATETIME NOT NULL,	PRIMARY KEY	(		UserID,		RoleName,		ProjectID,		RoleAssignedDate	));GOCREATE TABLE #Numbers(	Num INT NOT NULL PRIMARY KEY);GOWITH DIGITSAS(	SELECT 0 AS Num	UNION ALL	SELECT Num + 1	FROM DIGITS	WHERE Num &amp;lt; 10)INSERT INTO #Numbers(	Num)SELECT NumFROM DIGITS;GOWITH NUMBERSAS(	SELECT HundredThousand.Num * 100000 + TenThousand.Num * 10000 + 		Thousand.Num * 1000 + Hundred.Num * 100 +		Ten.Num + One.Num AS Num	FROM #Numbers HundredThousand	CROSS JOIN #Numbers TenThousand	CROSS JOIN #Numbers Thousand	CROSS JOIN #Numbers Hundred	CROSS JOIN #Numbers Ten	CROSS JOIN #Numbers One),RANDOMDATAAS(	SELECT Num AS UserID,		RoleName,		ABS(CHECKSUM(NEWID()) % 8000) + 1000 AS ProjectID,		DATEADD(DAY, -ABS(CHECKSUM(NEWID()) % 1000), GETDATE()) AS RoleAssignedDate,		NEWID() AS SortOrder	FROM NUMBERS	CROSS JOIN #Role)INSERT INTO #UserRole(	UserID,	RoleName,	ProjectID,	RoleAssignedDate)SELECT TOP(1000000) UserID,	RoleName,	ProjectID,	RoleAssignedDateFROM RANDOMDATAORDER BY SortOrder;GO[/code]</description><pubDate>Tue, 29 Jun 2010 21:10:30 GMT</pubDate><dc:creator>Mike C</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[quote][b]Brian Barkauskas (6/29/2010)[/b][hr]OK, then use GROUP:[code="sql"]--An alternative without ROW_NUMBER()--How about this?select        u.UserID        , stuff((                select ', ' + u2.RoleName                from @UserRole u2                where u2.UserID = u.UserID                and u2.RoleAssignedDate = (                        select min(u3.RoleAssignedDate)                        from @UserRole u3                        where u3.UserID = u2.UserID                        and u3.RoleName = u2.RoleName                )                order by u2.RoleAssignedDate asc                for xml path('')        ), 1, 2, '') 'RoleName'from @UserRole ugroup by u.UserID[/code]*** R.P.Rozema *****************************************************************SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 1 ms.Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 4 ms.*** Brian Barkauskas ***********************************************************SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 1 ms.Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 2 ms.[/quote]You good folks simply aren't using enough data to claim victory in any of the cases.</description><pubDate>Tue, 29 Jun 2010 17:21:12 GMT</pubDate><dc:creator>Jeff Moden</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Actually for readability, this one's even better,It has only 32 "words" compared to your 70,182 non-space characters to your 363,and runs just as fast:[code="sql"]select	  u.UserID	, stuff((		select ', ' + u2.RoleName		from @UserRole u2		where u2.UserID = u.UserID		group by u2.RoleName		order by min(u2.RoleAssignedDate)		for xml path('')	),1,2,'') 'RoleName'from @UserRole ugroup by u.UserID[/code]</description><pubDate>Tue, 29 Jun 2010 15:10:39 GMT</pubDate><dc:creator>Brian Barkauskas</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>OK, then use GROUP:[code="sql"]--An alternative without ROW_NUMBER()--How about this?select        u.UserID        , stuff((                select ', ' + u2.RoleName                from @UserRole u2                where u2.UserID = u.UserID                and u2.RoleAssignedDate = (                        select min(u3.RoleAssignedDate)                        from @UserRole u3                        where u3.UserID = u2.UserID                        and u3.RoleName = u2.RoleName                )                order by u2.RoleAssignedDate asc                for xml path('')        ), 1, 2, '') 'RoleName'from @UserRole ugroup by u.UserID[/code]*** R.P.Rozema *****************************************************************SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 1 ms.Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 4 ms.*** Brian Barkauskas ***********************************************************SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 1 ms.Table '#4F1BAE10'. Scan count 8, logical reads 8, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times:   CPU time = 0 ms,  elapsed time = 2 ms.</description><pubDate>Tue, 29 Jun 2010 14:48:32 GMT</pubDate><dc:creator>Brian Barkauskas</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Hi Brian, why would you want to eliminate row_number() from the query? Simply copy and paste your code into the test script that SwePeso posted and see for yourself how your version compares to the alternatives already presented. Peso's suggestion has by far the least IO and cpu time; I've taken that and added a fix for a functional problem in all suggestions: the special-characters &amp;, &amp;lt; and &amp;gt; that for xml translates into &amp; amp ;, &amp; lt ; and &amp; gt ; respectively (I put some additional spaces in that aren't in the real codes because the forum software shows the complete codes as &amp;, &amp;lt; and &amp;gt; again). Your example re-introduces that problem and performs much worse because it re-introduces distinct instead of the group by in a sub query. So is there any specific reason why you think your version should be used instead of mine?edit: codes were not shown correctly by the forum software.</description><pubDate>Tue, 29 Jun 2010 14:03:56 GMT</pubDate><dc:creator>R.P.Rozema</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>This is a good article thanks!I was going to mention that using GROUP BY instead of DISTINCT/ROW_NUMBER might be a good way to solve this, but I see someone has already suggested that. IMO DISTINCT should hardly ever be used, as it usually isn't the best option, like in this case it prevents you from being able to order the results by what you want.</description><pubDate>Tue, 29 Jun 2010 10:32:40 GMT</pubDate><dc:creator>UMG Developer</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[code="sql"]--An alternative without ROW_NUMBER()--How about this?select distinct	u.UserID	, stuff((		select ', ' + u2.RoleName		from @UserRole u2		where u2.UserID = u.UserID		and u2.RoleAssignedDate = (			select min(u3.RoleAssignedDate)			from @UserRole u3			where u3.UserID = u2.UserID			and u3.RoleName = u2.RoleName		)		order by u2.RoleAssignedDate asc		for xml path('')	), 1, 2, '') 'RoleName'from @UserRole u[/code]</description><pubDate>Tue, 29 Jun 2010 08:21:29 GMT</pubDate><dc:creator>Brian Barkauskas</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>I recommend using a CLR for this.  Microsoft has a great example here [url]http://msdn.microsoft.com/en-us/library/ms131056.aspx[/url].  I'm curious what the performance differences are.  Admittedly, I have not compared the two because I've never had the CLR function not perform adequately.You can then use this as an aggregate, for example.[code="sql"]SELECT dbo.List(myColumn)FROM myTableGROUP BY SomeOtherColumn[/code]</description><pubDate>Tue, 29 Jun 2010 08:04:24 GMT</pubDate><dc:creator>Bradley Deem</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Another variation on the previous suggestions. See what happens to all the other solutions when any of the roles is changed into for example 'R&amp;D'. Plus, I don't like the replace()-approach to get rid of the last ','. I rather don't generate it if it's not needed instead of taking it off in an additional processing step:[code="sql"]SELECT 	u1.UserID,	(		select case row_number() over (order by (select 1)) when 1 then '' else ', ' end 			+ t.RoleName AS [text()]		from (			select row_number() over (order by min(u2.RoleAssignedDate)) as nr, u2.RoleName			from @UserRole u2			where u2.UserID = u1.UserID			group by u2.RoleName		) t		order by t.nr		for xml path(''), type	).value('.', 'nvarchar(max)') as Rolesfrom (			select 				UserID			from @UserRole			group by				UserID		) u1order by u1.UserID[/code]</description><pubDate>Tue, 29 Jun 2010 07:13:40 GMT</pubDate><dc:creator>R.P.Rozema</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Let's do some testing...[CODE]SET NOCOUNT ON-- Prepare sample dataDECLARE	@UserRole TABLE	(		UserID INT NOT NULL,		RoleName VARCHAR(100) NOT NULL,		ProjectID INT NOT NULL,		RoleAssignedDate DATETIME NOT NULL	) -- Populate sample dataINSERT	@UserRole	(		UserID,		RoleName,		ProjectID,		RoleAssignedDate	)VALUES	(1112, 'Technical Director',          2041, '1967-02-20 04:21:13.490'),	(1357, 'Training',                    1614, '1961-09-14 16:18:59.990'),	(1836, 'Technical Director',          1628, '1987-07-30 11:22:45.060'),	( 715, 'Accounting',                  1487, '1995-01-08 11:46:17.670'),	( 162, 'Approver',                    1548, '2001-07-02 11:34:14.260'),	(1975, 'Technical Director',          1614, '1955-11-10 03:55:05.560'),	(1112, 'System Administrator',         831, '1956-04-25 08:26:54.040'),	( 162, 'Technical Director',           986, '1989-12-17 15:51:04.330'),	( 715, 'Accounting',                   461, '1954-11-27 00:45:52.830'),	(1357, 'Developer',                   2064, '2006-12-15 23:43:55.470'),	(1867, 'Technical Director',          1416, '2003-04-11 16:50:01.070'),	(1975, 'Developer',                   1548, '1967-05-11 17:01:26.840'),	(1975, 'Accounting',                  1089, '1988-06-20 00:52:16.070'),	( 162, 'Marketing',                   1443, '1995-06-10 14:29:23.290'),	(1112, 'Accounting',                  2109, '1999-12-05 09:07:46.620'),	( 162, 'Technical Director',          1089, '1975-09-25 12:13:12.590'),	( 162, 'International Sales Manager', 1628, '1984-05-30 09:25:18.330'),	(1836, 'Technical Customer',           420, '1993-05-28 00:49:31.090'),	(1357, 'Technical Director',          2036, '1979-04-25 23:38:48.120'),	(1836, 'Developer',                   1628, '2006-07-26 20:36:53.420')-- Start timingSET STATISTICS IO ONSET STATISTICS TIME ON-- PesoPRINT '*** Peso ***********************************************************************'SELECT		b.UserID,		STUFF(f.Roles, 1, 1, '') AS RolesFROM		(			SELECT		UserID			FROM		@UserRole			GROUP BY	UserID		) AS bCROSS APPLY	(			SELECT		TOP(100) PERCENT					',' + w.RoleName			FROM		@UserRole AS w			WHERE		w.UserID = b.UserID			GROUP BY	w.RoleName			ORDER BY	MIN(RoleAssignedDate)			FOR XML		PATH('')		) AS f(Roles)ORDER BY	b.UserID-- Puja ShahPRINT '*** Puja Shah ******************************************************************'SELECT		b.UserID,		LEFT(b.Roles, LEN(b.Roles) - CHARINDEX(',', REVERSE(b.Roles))) AS RolesFROM		(			SELECT DISTINCT	a.UserID,					CAST(a.Roles.query('distinct-values(/Root/Roles)') AS VARCHAR(MAX)) AS Roles			FROM		(						SELECT	u1.UserID,							CAST(								(									SELECT DISTINCT	u2.RoleName + ',' AS Roles,											ROW_NUMBER() OVER(PARTITION BY u2.UserID ORDER BY u2.RoleAssignedDate) AS RID									FROM		@UserRole AS u2									WHERE		u2.UserID = u1.UserID									ORDER BY	RID									FOR XML		PATH(''),											ROOT('Root')								) AS XML							) AS Roles						FROM	@UserRole AS u1					) AS a		) AS bORDER BY	b.UserID-- Kailash Mishra		&amp;lt;- Fails orderingPRINT '*** Kailash Mishra *************************************************************'SELECT DISTINCT	a.UserID,		SUBSTRING(b.RoleName, 1, LEN(b.RoleName) -1)FROM		@UserRole AS aCROSS APPLY	(			SELECT DISTINCT	b.RoleName + ','			FROM		@UserRole AS b			WHERE		b.UserID = a.UserID			FOR XML		PATH('')		) AS b(RoleName) ORDER BY	a.UserID-- Mike CPRINT '*** Mike C *********************************************************************';WITH cteAS (	SELECT		ROW_NUMBER() OVER (PARTITION BY u2.UserID ORDER BY MIN(u2.RoleAssignedDate)) AS RowNum,			u2.UserID, 			u2.RoleName        FROM		@UserRole AS u2        GROUP BY	u2.UserID,			u2.RoleName)SELECT DISTINCT	u1.UserID,		SUBSTRING(				(					SELECT		',' + c.RoleName AS '*'					FROM		cte AS c					WHERE		u1.UserID = c.UserID					ORDER BY	c.RowNum					FOR XML		PATH('')				), 2, 8000			) AS RolesFROM		@UserRole AS u1ORDER BY	u1.UserID-- Nick HansonPRINT '*** Nick Hanson ****************************************************************'SELECT DISTINCT	u1.UserID,		REPLACE (				(					SELECT		u2.RoleName + ',' AS 'data()'					FROM		@UserRole AS u2					WHERE		u2.UserID = u1.UserID					GROUP BY	u2.RoleName					ORDER BY	MIN(u2.RoleAssignedDate)					FOR XML		PATH('')				) + '$', ',$', ''			) AS RolesFROM		@UserRole AS u1ORDER BY	u1.UserID-- Stop timingSET STATISTICS TIME OFFSET STATISTICS IO OFF[/CODE]</description><pubDate>Tue, 29 Jun 2010 03:39:11 GMT</pubDate><dc:creator>SwePeso</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>I like this article, it was a problem I had to solve previously.I particularly like the way you solved the problem of the final ',' at the end of the string. Very neat.I have to say I was totally lost by the end of your explanation and found the code too difficult to follow.The following is an adaptation of your 2nd stage code, but using Group By RoleName which then allows Order By MIN(RoleAssignedDate) and thereby giving the order required.[code="sql"] SELECT DISTINCT u1.UserID,REPLACE	(			(SELECT u2.RoleName + ',' AS 'data()'			FROM @UserRole u2			WHERE u2.UserID = u1.UserID			GROUP BY RoleName			ORDER BY MIN(RoleAssignedDate)			FOR XML PATH('')			) + '$', ',$', ''		) AS RolesFROM @UserRole u1[/code]Cheers,Nick</description><pubDate>Tue, 29 Jun 2010 02:43:33 GMT</pubDate><dc:creator>nick.hanson</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Thanks Mike for new approach. :-)</description><pubDate>Tue, 29 Jun 2010 00:00:17 GMT</pubDate><dc:creator>Puja Shah</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Thanks Kailash Mishra.The query that you gave will give result in an alphabetical order instead of the order in which the roles were assigned. The article is about retrieving delimited values in the order they were stored.Thanks &amp; regards,Puja</description><pubDate>Mon, 28 Jun 2010 23:55:14 GMT</pubDate><dc:creator>Puja Shah</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>[code]WITH CTEAS(	SELECT ROW_NUMBER() OVER 		(			PARTITION BY u2.UserID 			ORDER BY MIN(u2.RoleAssignedDate)		) AS RowNum,		u2.UserID, 		u2.RoleName	FROM @UserRole u2	GROUP BY u2.UserID,		u2.RoleName)SELECT DISTINCT u1.UserID,	SUBSTRING	(		(			SELECT ', ' + c.RoleName AS '*'			FROM CTE c			WHERE u1.UserID = c.UserID			ORDER BY c.RowNum			FOR XML PATH('')		), 3, 8000	) AS RolesFROM @UserRole u1;[/code]Should give the same result without the XQuery.</description><pubDate>Mon, 28 Jun 2010 23:20:57 GMT</pubDate><dc:creator>Mike C</dc:creator></item><item><title>RE: Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Appreciate your article. This is with lot of explanation, but we can achieve the output more efficient way with the sorting of rolename also:select distinct a.userid, substring(b.rolename, 1, len(b.rolename )-1) from @UserRole across apply (select distinct RoleName + ', ' from @UserRole where a.userid = useridfor xml path('')) b (rolename)</description><pubDate>Mon, 28 Jun 2010 23:18:57 GMT</pubDate><dc:creator>Kailash Mishra</dc:creator></item><item><title>Generating a Distinct Delimited List Using XML</title><link>http://www.sqlservercentral.com/Forums/Topic944361-2724-1.aspx</link><description>Comments posted to this topic are about the item [B]&lt;A HREF="/articles/FOR+XML+PATH/70203/"&gt;Generating a Distinct Delimited List Using XML&lt;/A&gt;[/B]</description><pubDate>Mon, 28 Jun 2010 21:35:59 GMT</pubDate><dc:creator>Puja Shah</dc:creator></item></channel></rss>