Stuff (SELECT ', ' + fieldname from tablename FOR XML Path (")), 1, 1, ')
The function of this whole sentence is to concatenate the contents of a multiline FieldName field, separated by commas.
such as tables
FieldName
-----------
Aaa
Bbb
Ccc
After concatenation is the string: AAA,BBB,CCC
The FOR XML path is a way to generate XML that is supported by a later version of SQL Server 2005 . Refer to Books Online for details on how to use them.
The role of the stuff function is to remove the comma delimiter from the front of the string.
---------------------------------------------------------------
在sql server 2000中只能用函数解决createtabletb(id int, value varchar(10)) insertintotb values(1, ‘aa‘) insertintotb values(1, ‘bb‘) insertinto tb values(2, ‘aaa‘) insertintotb values(2, ‘bbb‘) insertintotb values(2, ‘ccc‘) go --1. 创建处理函数 CREATEFUNCTIONdbo.f_strUnite(@id int) RETURNSvarchar(8000) ASBEGIN DECLARE@str varchar(8000) SET@str = ‘‘ SELECT@str = @str + ‘,‘+ value FROMtb WHERE [email protected] RETURNSTUFF(@str, 1, 1, ‘‘) ENDGO -- 调用函数 SELECtid, value = dbo.f_strUnite(id) FROMtb GROUPBY id go id value ----------- ----------- 1 aa,bb 2 aaa,bbb,ccc
Combine the same field of multiple records into a single string