使用sql 2005将多个值插入单个单元格

时间:2012-04-17 14:08:36

标签: sql sql-server sql-server-2005

我有典型的表格:

LSRNbr  BatchNbr
111     1212
111     1414  

查询应返回:

LSRNbr   BatchNbr
111      1212, 1414

我正在寻找解决方案,我找到了这两个:

解决方案1:

;WITH C AS 
(
SELECT LSRNbr, BatchNbr FROM tblDTS_LSRBatch
)

SELECT Distinct LSRNbr, 
STUFF((SELECT ';' + BatchNbr FROM tblDTS_LSRBatch WHERE LSRNbr = c.LSRNbr FOR XML PATH('')),1,1,'') 
FROM C

错误:

Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near ';'.
Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near 'XML'.

解决方案2:

SELECT 
[LSRNbr], REPLACE(RTRIM((SELECT [BatchNbr] + ' ' FROM tblDTS_LSRBatch WHERE (LSRNbr = Results.LSRNbr ) FOR XML PATH (''))),' ',', ') AS NameValues
FROM tblDTS_LSRBatch Results
GROUP BY LSRNbr

错误:

Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 'XML'.

但他们都没有为我工作,请看上面的错误。

这可能是什么问题?

我正在使用Microsoft SQL Server 2005

1 个答案:

答案 0 :(得分:1)

这些是语法错误。

您将从自己解决特定错误中了解更多信息:

查看syntax tree

查看good examples

what you're trying to do {。}}

如果您仍有问题,请随时提出更多问题