2016-09-23 59 views
-1
SubjectID  StudentName 
----------  ------------- 
1    Mary 
1    John 
1    Sam 


SubjectID  StudentName 
----------  ------------- 
1    Mary, John, Sam 

嗨,我使用SQL Server 2014,我想知道這是否是可以使用的東西()函數來插入結果成一列。我在網上看到的例子都在檢索。我試圖根據它的文檔做它似乎並不正確。的SQL Server 2014插入的東西功能

查詢

@"INSERT INTO ApplicationOtherInfo 
         (ApplicationId, AppOptionCode 
         ) values 
         (@applicationId, @appCode 
         )"; 

SELECT STUFF((SELECT ',' + AppOptionCode 
       FROM ApplicationOtherInfo 
       ORDER BY AppOptionCode 
       FOR XML PATH('')), 1, 1, '') 
+2

是的,它是:https://開頭MSDN。 microsoft.com/en-us/library/ms188043.aspx – rbr94

回答

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 
+0

你有沒有嘗試過我的方案? – gofr1