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中只能用函数解决
create
table
tb(id
int
, value
varchar
(10))
insert
into
tb
values
(1,
‘aa‘
)
insert
into
tb
values
(1,
‘bb‘
)
insert
into
tb
values
(2,
‘aaa‘
)
insert
into
tb
values
(2,
‘bbb‘
)
insert
into
tb
values
(2,
‘ccc‘
)
go
--1. 创建处理函数
CREATE
FUNCTION
dbo.f_strUnite(@id
int
)
RETURNS
varchar
(8000)
AS
BEGIN
DECLARE
@str
varchar
(8000)
SET
@str =
‘‘
SELECT
@str = @str +
‘,‘
+ value
FROM
tb
WHERE
[email protected]
RETURN
STUFF(@str, 1, 1,
‘‘
)
END
GO
-- 调用函数
SELECt
id, value = dbo.f_strUnite(id)
FROM
tb
GROUP
BY
id
go
id value
----------- -----------
1 aa,bb
2 aaa,bbb,ccc
Combine the same field of multiple records into a single string