This question already has answers here:
Unpivot with column name (3 answers)
Closed 4 days ago.
I want to retrieve the name and value of each column in a SQL table for a particular record, and store them as a separate entry in a different table using a stored procedure. I have tried using an INSERT EXEC statement within a loop, but I get an error saying that it cannot be nested within a stored procedure. How can I achieve this dynamic column name/value pairing in MS SQL Server?
For example, given the following table:
| Id | Name | Place |
| ------------ | ------------ | ------------ |
| 1 | 'Jane' | 'USA' |
| 2 | 'Tyrion' | 'UK' |
I want to retrieve the data for a specific Id (e.g. 1) and store the column name and value as separate entries in a different table like this:
Column Name | Column Value |
---|---|
Id | 1 |
Name | 'Jane' |
Place | 'USA' |
Please suggest a solution or workaround.
1条答案
按热度按时间k4ymrczo1#
Here is an option that will dynamically UNPIVOT virtually any table, view or query WITHOUT enumerating columns or using Dynamic SQL
Example
Results
UPDATE ... XML Version