Try that;
SELECT STUFF ((
SELECT cast('/' as Varchar(max)) + Location
From Locations
Group by Location
Order by MAX(Time) FOR XML PATH('')) , 1 , 1 , '' ) as result
Question
So I have been fighting with this for a while now and I thought this had to be a simple task. My goal is to return a single string of all the unique rows returned separated with a forward slash and ordered by the time they were entered. Here is example data
Table: Locations
Location Time
======== =======
OR1 2013-02-06 16:55:47.000
OR1 2013-02-06 16:56:34.000
ICU1 2013-02-06 16:59:50.000
OR1 2013-02-06 17:02:50.000
ICU1 2013-02-06 17:09:50.000
So given the above table of data I want to return a string that says this "OR1/ICU1". I can return the distinct values as a string using FOR XML PATH but as soon as I throw in the ORDER BY it all falls apart with errors.
Ideas?
Solution
Try that;
SELECT STUFF ((
SELECT cast('/' as Varchar(max)) + Location
From Locations
Group by Location
Order by MAX(Time) FOR XML PATH('')) , 1 , 1 , '' ) as result
OTHER TIPS
Use a temporary table in your query, and a while loop, but I would not recommend doing so against large production data whose performance may be negatively impacted.
For example.
/*Create our temp table */
DECLARE @MyTemp TABLE (Location VARCHAR(10), Processed BIT DEFAULT 0)
/*Load the temp table will all the distinct locations */
INSERT INTO @MyTemp SELECT DISTCINT Location FROM Locations
/* need these variable to hold data */
DECLARE @FinalString VARCHAR(1000) = ''
DECLARE @Location VARCHAR(10) = ''
/*as long as there is any row with an unprocessed location in the table
we want to continue this process */
WHILE EXISTS(SELECT 1 FROM @MyTemp WHERE Processed = 0)
BEGIN
/* Grab our next unprocessed location */
SELECT TOP 1 @Location = Location FROM @MyTemp WHERE Processed = 0 ORDER BY Location
/* Add it to the final string */
SET @FinalString = @FinalString + '/' + @Location
/* mark the location as processed */
UPDATE @MyTemp SET Processed = 1 WHERE Location = @Location
END
/* get the final result (note this will have a leading '/') */
SELECT @FinalString