循环遍历表的每一列

时间:2015-08-12 11:58:50

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

我有两个表,即ExcelData和PlanProfile。我想要的是当我循环遍历ExcelData表的每一行时,逻辑将在另一个表PlanProfile的Attribute字段中插入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 

1 个答案:

答案 0 :(得分:4)

测试数据

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必须具有相同的数据类型。

相关问题