Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think you're halfway there. Just use <code>UNPIVOT</code> and <code>dynamic SQL</code> as Martin recommended:</p> <pre><code>CREATE TABLE TableA ( Code VARCHAR(10), Name VARCHAR(10), Details VARCHAR(10) ) INSERT TableA VALUES ('Foo', 'Bar', 'Baz') GO DECLARE @sql nvarchar(max) SET @sql = (SELECT STUFF((SELECT ',' + column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name='TableA' ORDER BY ordinal_position FOR XML PATH('')), 1, 1, '')) SET @sql = N'SELECT [Key], Val FROM (SELECT ' + @sql + ' FROM TableA) x ' + 'UNPIVOT ( Val FOR [Key] IN (' + @sql + ')) AS unpiv' EXEC (@sql) </code></pre> <p><strong>Results</strong>: </p> <pre><code>Key Val ------------ ------------ Code Foo Name Bar Details Baz </code></pre> <p>There is a caveat, of course. All your columns will need to be the same data type for the above code to work. If they are not, you will get this error: </p> <pre><code>Msg 8167, Level 16, State 1, Line 1 The type of column "Col" conflicts with the type of other columns specified in the UNPIVOT list. </code></pre> <p>In order to get around this, you'll need to create two column string statements. One to get the columns and one to cast them all as the data type for your Val column. </p> <p><strong>For multiple column types</strong>: </p> <pre><code>CREATE TABLE TableA ( Code INT, Name VARCHAR(10), Details VARCHAR(10) ) INSERT TableA VALUES (1, 'Foo', 'Baf') GO DECLARE @sql nvarchar(max), @cols nvarchar(max), @conv nvarchar(max) SET @cols = (SELECT STUFF((SELECT ',' + column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name='TableA' ORDER BY ordinal_position FOR XML PATH('')), 1, 1, '')) SET @conv = (SELECT STUFF((SELECT ', CONVERT(VARCHAR(50), ' + column_name + ') AS ' + column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name='TableA' ORDER BY ordinal_position FOR XML PATH('')), 1, 1, '')) SET @sql = N'SELECT [Key], Val FROM (SELECT ' + @conv + ' FROM TableA) x ' + 'UNPIVOT ( Val FOR [Key] IN (' + @cols + ')) AS unpiv' EXEC (@sql) </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload