Azure数据仓库中的多行到单行

时间:2016-11-25 18:09:29

标签: sql-server azure azure-sqldw

由于Azure DW不支持FOR XMLSELECT变量赋值,除了使用CURSOR之外,还有其他方法可以将多行转换为单行吗?

1 个答案:

答案 0 :(得分:3)

我没有找到任何直接方法,但下面的代码对我有效。

DECLARE @intColumnCount  INT, 
        @intProcessCount INT, 
        @varColList      VARCHAR(max) 

SET @varColList = '' 

IF Object_id('tempdb.dbo.#tempColumnNames') IS NOT NULL 
  BEGIN 
      DROP TABLE #tempcolumnnames; 
  END 

CREATE TABLE #tempcolumnnames 
  ( 
     intid          INT, 
     varcolumnnames VARCHAR(256) 
  ) 

INSERT INTO #tempcolumnnames 
SELECT Row_number() 
         OVER ( 
           ORDER BY NAME), 
       NAME 
FROM   sys.tables 

SET @intProcessCount = 1 
SET @intColumnCount = (SELECT Count(*) 
                       FROM   #tempcolumnnames) 

WHILE ( @intProcessCount <= @intColumnCount ) 
  BEGIN 
      SET @varColList = @varColList + ', ' 
                        + (SELECT varcolumnnames 
                           FROM   #tempcolumnnames 
                           WHERE  intid = @intProcessCount) 
      SET @intProcessCount +=1 
  END 

SELECT Stuff(@varColList, 1, 2, '') 

希望这有助于某人。