0

这是我的问题:

给定插入游标的选择语句的结果,我怎样才能将这些值放在一行中?

例如给出

 a
 b
 c

我怎样才能实现 a,b,c ?

4

2 回答 2

0

简单地:

SUBSTRING((SELECT DISTINCT ',' + [ColumnName] FROM TableName FOR XML PATH('')),2,4000)
于 2013-09-18T09:15:28.610 回答
0

将光标的结果插入临时表。以下是我的示例,但您必须用光标替换它。

SELECT 'a' AS [Col1]
INTO #Table1

INSERT INTO #Table1
SELECT 'b'
INSERT INTO #Table1
SELECT 'c'
INSERT INTO #Table1
SELECT 'd'

创建动态枢轴以显示结果。

DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF
            (
               (
                  SELECT DISTINCT ',' + QUOTENAME(c.[Col1]) 
                  FROM   #Table1 c
                  FOR XML PATH(''), TYPE
               ).value('.', 'NVARCHAR(MAX)') 
               ,1,1,''
            )

SET @query = 'SELECT ' + @cols + ' FROM
             (
                SELECT [Col1]
                FROM   #Table1
             ) x
            PIVOT
            (
                MAX([Col1])
                FOR [Col1] IN(' + @cols + ')
            ) p '


EXECUTE(@query)

删除临时表

DROP TABLE #Table1
于 2013-09-18T08:54:42.643 回答