【问题标题】:loop through each column of a table循环遍历表格的每一列
【发布时间】:2015-08-12 11:58:49
【问题描述】:

我有两张表,即 ExcelData 和 PlanProfile 。我想要的是,当我遍历 ExcelData 表的每一行时,逻辑将在另一个表 PlanProfile 的属性字段中插入 column_names,但我不想遍历每一列,对于某些列应该可以正常插入第二张桌子。

ExcelData table:

Id  PId  PType  CId  CNotes  CLegal
1    101  test  201  notes  testlegal
2    102  test  202  notes  testlegal
3    103  test  203  notes  testLegal

我在第二张表 PlanProfile 中想要什么;

Id PId PType Attributes Value
1  101 test   CId         201
2  101 test   CNotes      notes
3  101 test   CLegal      testlegal
4  102 test   CId         202
5  102 test   CNotes      notes
6  102 test   CLegal      testlegal
----- same goes for 103 

【问题讨论】:

    标签: sql sql-server database sql-server-2008 sql-server-2012


    【解决方案1】:

    测试数据

    declare @ExcelData TABLE (Id INT, PId INT, PType VARCHAR(20)
    , CId VARCHAR(20), CNotes VARCHAR(20), CLegal VARCHAR(20))
    INSERT INTO @ExcelData VALUES
    (1  ,  101  ,'test',  '201'  ,'notes','testlegal'),
    (2  ,  102  ,'test',  '202'  ,'notes','testlegal'),
    (3  ,  103  ,'test',  '203'  ,'notes','testLegal')
    

    查询

    SELECT ROW_NUMBER() OVER (ORDER BY ID ASC) New_ID
           ,*
    FROM @ExcelData t
     UNPIVOT (Value FOR Attributes IN (CId, CLegal,CNotes))up
    

    结果

    ╔════════╦════╦═════╦═══════╦═══════════╦════════════╗
    ║ New_ID ║ Id ║ PId ║ PType ║   Value   ║ Attributes ║
    ╠════════╬════╬═════╬═══════╬═══════════╬════════════╣
    ║      1 ║  1 ║ 101 ║ test  ║ 201       ║ CId        ║
    ║      2 ║  1 ║ 101 ║ test  ║ testlegal ║ CLegal     ║
    ║      3 ║  1 ║ 101 ║ test  ║ notes     ║ CNotes     ║
    ║      4 ║  2 ║ 102 ║ test  ║ 202       ║ CId        ║
    ║      5 ║  2 ║ 102 ║ test  ║ testlegal ║ CLegal     ║
    ║      6 ║  2 ║ 102 ║ test  ║ notes     ║ CNotes     ║
    ║      7 ║  3 ║ 103 ║ test  ║ 203       ║ CId        ║
    ║      8 ║  3 ║ 103 ║ test  ║ testLegal ║ CLegal     ║
    ║      9 ║  3 ║ 103 ║ test  ║ notes     ║ CNotes     ║
    ╚════════╩════╩═════╩═══════╩═══════════╩════════════╝
    

    注意

    UNPIVOT 中使用的列必须具有相同的数据类型,如果它们不使用子查询将它们转换/转换为相同的数据类型,其余的应该相同。在此示例中,列 CId, CLegal,CNotes 必须具有相同的数据类型。

    【讨论】:

    • 在 UNPIVOT 子句中使用 CAST 使所有列具有相同的数据类型,如果它们不是...
    • @M Ali 感谢您的时间和帮助。但我在执行时遇到错误“列“CLegal”的类型与 UNPIVOT 列表中指定的其他列的类型冲突。”即使我在两个表中都有相同数据类型的列。
    • 在应用 unpivot 之前使用子查询并将列转换为与其他列相同的数据类型,请参阅SQL FIDDLE
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 2015-04-14
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多