Nice script. I looked at it and found two improvements that you can make. First you can replace:
if @first = 0
begin
set @first = 1
set @filenames = @filename
end
else
set @filenames = @filenames + ',' + @filename
with :
set @filenames = COALESCE(@filenames + ',' , '') + @filename
And you can remove the cursor use by following the sample like this:
In this sample, we use COALESCE to generate a flat list. You can specify a delimiter to seperate the items in the list.
CREATE TABLE [dbo].[student](
[id] [int] NOT NULL,
[name] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[ssn] [varchar](11) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_student] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT student VALUES(1, 'andrew', '201-98-9238')
INSERT student VALUES(2, 'lindsay', '656-89-9238')
INSERT student VALUES(3, 'david', '555-22-1111')
GO
DECLARE @list varchar(1024)
SELECT @list = COALESCE(@list + '|', '') + name
FROM student
PRINT @list
Here is the result set.
andrew|lindsay|david