Convert Column values into Column names - DotNet and DataBase

Follow us on Facebook

SQL Server Mountain View Mountain View Mountain View

Sunday, 28 April 2019

Convert Column values into Column names

















In this post let us see how to convert column values into the column names using MySQL.

DROP TABLE IF EXISTS Temp1;
CREATE TEMPORARY TABLE Temp1 (
    Col1 VARCHAR(100)
);

INSERT INTO Temp1(Col1) VALUES('Xyz A'),('BCD A'),('C'),('B');
 
SET @SqlString = (SELECT
    GROUP_CONCAT(DISTINCT Col1
        ORDER BY Col1 ASC
        SEPARATOR '` VARCHAR(100), `')FROM  Temp1);
SET @SqlString = CONCAT("`",@SqlString,"` VARCHAR(100)");

DROP TABLE IF EXISTS TempRowsToColumns;
SET @sql1 = CONCAT("CREATE TEMPORARY TABLE TempRowsToColumns (ID INT AUTO_INCREMENT PRIMARY KEY,",@SqlString,")");
 
PREPARE stmt FROM @sql1;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
SELECT * FROM TempRowsToColumns;

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.