Well, it seems to me that I need to skip to comment How do you combine multiple rows into a single column on SQL Server? and provide a more preferable answer.
I'm sorry, but using scalar-valued functions like this will lead to performance damage. Just open SQL Profiler and see what happens when you use the scalar function that calls the table.
In addition, the “update variable” method for concatenation is not recommended, as this functionality may not be preserved in future versions.
The preferred way to perform string concatenation is to use the FOR XML PATH.
select stuff((select ', ' + t.tag from tags t where t.photoid = p.photoid order by tag for xml path('')),1,2,'') as taglist ,* from photos order by photoid;
For examples of how the FOR XML PATH works, consider the following, imagining that you have a table with two fields called id and name
SELECT id, name FROM table order by name FOR XML PATH('item'),root('itemlist') ;
gives:
<itemlist><item><id>2</id><name>Aardvark</a></item><item><id>1</id><name>Zebra</name></item></itemlist>
But if you leave ROOT, you will get something a little different:
SELECT id, name FROM table order by name FOR XML PATH('item') ; <item><id>2</id><name>Aardvark</a></item><item><id>1</id><name>Zebra</name></item>
And if you put an empty PATH line, you get even closer to the usual string concatenation:
SELECT id, name FROM table order by name FOR XML PATH('') ; <id>2</id><name>Aardvark</a><id>1</id><name>Zebra</name>
Now comes a very complicated bit ... If you name a column starting with the @ sign, it will become an attribute, and if the column does not have a name (or you name it [*]), then it also leaves this tag:
SELECT ',' + name FROM table order by name FOR XML PATH('') ; ,Aardvark,Zebra
Now, finally, to break the leading comma, the STUFF command is turned on. STUFF (s, x, n, s2) extends n characters s, starting at position x. Instead, he puts s2. So:
SELECT STUFF ('abcde', 2,3, '123456');
gives:
a123456e
Now look at my request above for your taglist.
select stuff((select ', ' + t.tag from tags t where t.photoid = p.photoid order by tag for xml path('')),1,2,'') as taglist ,* from photos order by photoid;
For each photo, I have a subquery that captures the tags and combines them (in order) with commma and a space. I then surround this subquery in the stuff command to remove the leading comma and space.
I apologize for any typos - I actually did not create the tables on my machine to check this.
Rob