SubjectID StudentName
---------- -------------
1 Mary
1 John
1 Sam
SubjectID StudentName
---------- -------------
1 Mary, John, Sam
嗨,我正在使用SQL Server 2014.我想知道是否可以使用STUFF()函数将插入结果放入一列。我在网上看到的例子都是检索。我尝试根据文档来做它似乎不正确。
查询
@"INSERT INTO ApplicationOtherInfo
(ApplicationId, AppOptionCode
) values
(@applicationId, @appCode
)";
SELECT STUFF((SELECT ',' + AppOptionCode
FROM ApplicationOtherInfo
ORDER BY AppOptionCode
FOR XML PATH('')), 1, 1, '')
答案 0 :(得分:0)
是的,你可以:
DECLARE @Students TABLE (
SubjectID int,
StudentName nvarchar(max)
)
INSERT INTO @Students VALUES
(1, 'Mary'),
(1, 'John'),
(1, 'Sam')
INSERT INTO SomeTable
SELECT DISTINCT
s.SubjectID,
STUFF((SELECT ', ' + StudentName
FROM @Students
WHERE s.SubjectID = SubjectID
FOR XML PATH('')), 1, 2, '')
as StudentName
FROM @Students s
如果您从SomeTable
中选择,您将获得:
SubjectID StudentName
1 Mary, John, Sam