I came across some very cool t-sql to generate a comma delimited list of column values from selected rows in one t-sql query:
SELECT @MyList = ISNULL(@MyList,'') + Title + ', ' FROM Titles
But I can’t figure out how it works. Somehow it must be doing a recursive call but I don’t know how.
Can anyone explain it to me or send me a link that explains it?
To see it work, use the following script:
CREATE TABLE Titles(
Title varchar(50)
)
insert Titles values ( 'Doctor')
insert Titles values ( 'Nurse')
insert Titles values ( 'Administrator')
insert Titles values ( 'CMA')
select * from Titles
DECLARE @MyList VARCHAR(1000)
SET @MyList = ''
SELECT @MyList = ISNULL(@MyList,'') + Title + ', ' FROM Titles
SELECT @MyList
The assignment:
is evaluated for every row of the Titles table. It concatenates each row’s
Titlecolumn value to @MyList.The test
ISNULL(@MyList,'')is only needed, so that@MyListstarts with an empty string if it isNULL. In your example theISNULLis unnecessary, because @MyList is explicitly set to an empty string.