这是我的问题:
给出插入游标的select语句的结果, 我怎样才能将这些值放入一行?
例如给定
a
b
c
我怎样才能实现a,b,c?
答案 0 :(得分: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
答案 1 :(得分:0)
简单地:
SUBSTRING((SELECT DISTINCT ',' + [ColumnName] FROM TableName FOR XML PATH('')),2,4000)