透过SQL Server 2005获取未知行数

时间:2010-10-21 06:57:49

标签: sql tsql

我的桌子很动态。 E.g:

id      SUBJECT
1   his
2   math
3   sci
4   opt
5   ENG
6   SOC

行数不受限制。可能有一百个。我想要这样的输出:

ID 1     2     3      4     5      6  

   HIS  MATH    SCI   OPT   ENG   SOC

我可以使用数据透视查询,但我必须知道列数。如何在不事先知道列数的情况下执行此操作?

2 个答案:

答案 0 :(得分:1)

我得到了答案,但这很棘手

  1. 为您的所有记录创建一个表格
  2. 计算记录
  3. 创建一个包含大量列的表
  4. 为包含记录的表创建逗号分隔变量
  5. 然后将逗号分隔的变量拆分为多个列
  6. 这是代码

    DECLARE  @HEADDESC NVARCHAR(150)
    DROP TABLE #HEADS
    CREATE TABLE #HEADS
    (
        ID INT IDENTITY
       ,HEADS NVARCHAR(150)
       ,NU INT 
    )
    DECLARE @NO INT;
    SET @NO = 0
    DECLARE C1 CURSOR FOR (
        SELECT  HEADDESC 
        FROM GMC.FEEHEAD_MASTER 
        WHERE CODE = 'GF' AND HEADDESC <> '')
    OPEN C1
    FETCH NEXT FROM C1 INTO @HEADDESC
    
    WHILE @@FETCH_STATUS  = 0
    BEGIN
        PRINT @HEADDESC
        SET @NO = @NO+1 
        INSERT INTO #HEADS(HEADS,NU) 
        VALUES(@HEADDESC,@NO)
    
        FETCH NEXT FROM C1 INTO @HEADDESC
    END
    --SELECT * FROM #HEADS
    CLOSE C1
    DEALLOCATE C1
    DECLARE @COLNO INT
    
    SET @COLNO = (SELECT COUNT(*) FROM #HEADS)
    
    DECLARE @COLUMNS VARCHAR(8000)
    
    SELECT @COLUMNS = COALESCE(@COLUMNS +','+  CAST(HEADS AS VARCHAR) ,
           CAST(HEADS AS VARCHAR))
    FROM #HEADS
    --GROUP BY HEADS
    
    DECLARE @value NVARCHAR(100)
    
    SET @value = ',1,STUDENTIDNO,STUDENTNAME,'
    
    SET @COLUMNS = @VALUE+@COLUMNS
    SET @COLNO = @COLNO+4
    --SELECT @COLUMNS
    DROP TABLE  #HEADSCOMMA
    CREATE TABLE #HEADSCOMMA(HEADS NVARCHAR(3000))
    
    INSERT INTO  #HEADSCOMMA VALUES (@COLUMNS)
    
    DROP TABLE #TEMP
    CREATE TABLE #TEMP(COL1 NVARCHAR(1000))
    DECLARE @SQL NVARCHAR(MAX)
    DECLARE @COL NVARCHAR(1000)
    DECLARE @COL1 INT
    DECLARE @COLNAME NVARCHAR(1000)
    
    SET  @COL1 = 2
    SET @COL = 'COL'
    PRINT @COL1
    --SET @COLNAME = @COL +CAST(@COL1 AS NVARCHAR(10))
    
    WHILE @COL1 < =@COLNO
    BEGIN
        SET @COLNAME = @COL +CAST(@COL1 AS NVARCHAR(100))
        PRINT @COLNAME
        SET @SQL = 'ALTER TABLE #TEMP ADD '+@COLNAME+' NVARCHAR(100)'
        EXEC(@SQL)
        SET @COL1= @COL1+1
    END
    
    
    --SELECT * FROM #HEADSCOMMA -- COMMA SEPERATED VALUES
    DECLARE @S VARCHAR(8000), @DATA VARCHAR(8000)
    --DROP TABLE  #NORMALISEDTABLE
    --CREATE TABLE #NORMALISEDTABLE (HEADS NVARCHAR(200))
    SELECT @S=''
    
    WHILE EXISTS (SELECT * FROM #HEADSCOMMA WHERE HEADS>@S)
    BEGIN
        SELECT @S=HEADS FROM #HEADSCOMMA WHERE HEADS>@S
        PRINT @S
        SELECT @DATA=''''+REPLACE(@S,',',''',''')+''''
        PRINT @DATA
        INSERT INTO #TEMP
        EXEC('SELECT '+@DATA)
    END
    
    SELECT * FROM #temp 
    

    将提供记录

答案 1 :(得分:0)

动态SQL是一种选择。