Sql-Server-2008

將表行值合併到另一個表的標題

  • September 3, 2019

表格1

id   |  Field           | Values        
----------------------------------------
1    | 'Field01'        |Name           
2    | 'Field02'        |Age  
3    | 'Field03'        |Gender  
4    | 'Field04'        |Qualification

表 2

id   |  Field01  | Field02 |Field03 |Field04
----------------------------------------
1    | Ajay      |18       |Male    |Bsc

2    | Arun      |19       |Male    |BA  
3    | Aruna     |18       |Female  |Bsc

輸出格式為:

id   |  Name     | Age     |Gender  |Qualification
----------------------------------------
1    | Ajay      |18       |Male    |Bsc

2    | Arun      |19       |Male    |BA  
3    | Aruna     |18       |Female  |Bsc

檢查這個我在 Stack Overflow 上回答了類似問題的地方。

您可以使用動態 sql 執行此操作:

DECLARE @fieldName varchar(32), @title varchar(32)
DECLARE @sql_cmd varchar(512)
SET @sql_cmd='SELECT id, '

DECLARE sql_cursor CURSOR FOR
SELECT Field, Values FROM table1 ORDER BY id

OPEN sql_cursor

FETCH NEXT FROM sql_cursor INTO @fieldName, @Title

WHILE (@@FETCH_STATUS = 0)
BEGIN
   SET @sql_cmd = @sql_cmd + @fieldName + ' AS ' + @Title + ', '

   FETCH NEXT FROM sql_cursor
   INTO @fieldName, @Title
END;

CLOSE sql_cursor
DEALLOCATE sql_cursor

SET @sql_cmd = SUBSTRING(@sql_cmd,0,LEN(@sql_cmd)-2) + ' FROM table2'
EXEC(@sql_cmd)

引用自:https://dba.stackexchange.com/questions/76175