在查詢和while循環中使用一個臨時表,但我不建議這樣做,否則可能會對性能可能受到負面影響的大型生產數據這樣做。
例如。
/*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
這裏是sqlfiddle此方法 http://sqlfiddle.com/#!3/e528e/2 – HKImpact
哈!我從來不知道命令STUFF。我以爲你只是在做點什麼。這工作很好,但。謝謝。 – mdutra
不客氣mdutra。 – soysal