Insert and update in a cursor in SQL Server

后端 未结 1 931
孤独总比滥情好
孤独总比滥情好 2020-12-22 05:11

I have a Table shown below

DateRange
10/1
11/1
12/1

I am looping through this table using cursor and trying to populate a temp table

相关标签:
1条回答
  • 2020-12-22 05:46

    Use PIVOT as

    SELECT Code,
           [22] Data1,
           [33] Data2,
           [43] Data3
    FROM
        (
          SELECT *
          FROM T
        ) TBL
        PIVOT
        (
          MAX(Data) FOR Data IN([22],[33],[43])
        ) PVT
    

    Demo

    For dynamic pivot

    CREATE TABLE T
    (
      Code VARCHAR(45),
      Data INT
    );
    
    INSERT INTO T VALUES
    ('SL Payroll',    22),
    ('SL Payroll',    33),
    ('SL Payroll',    43);
    
    DECLARE @IN VARCHAR(MAX) = '',
            @Cols VARCHAR(MAX) = '';
    
    SELECT @IN = @IN + ',' + QUOTENAME(Data),
           @Cols = @Cols + ',' + QUOTENAME(Data) + ' AS Data'+
                   CAST(ROW_NUMBER()OVER(ORDER BY (SELECT NULL)) AS VARCHAR)
    FROM T;
    
    SELECT @IN = STUFF(@IN, 1, 1, ''), @Cols = STUFF(@Cols, 1, 1, '');
    
    DECLARE @SQL NVARCHAR(MAX) = N'SELECT Code, ' +
                                   @Cols+
                                   ' FROM (SELECT * FROM T) TBL PIVOT (MAX(Data) FOR Data IN('+
                                   @IN+
                                   ')) PVT';
         EXECUTE sp_executesql @SQL;
    

    Demo

    0 讨论(0)
提交回复
热议问题