Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Perhaps you're making this more complicated than it needs to be. Partly because I couldn't wrap my little brain around the number of <code>PIVOT</code>/<code>UNPIVOT</code>/whatever combinations and a dynamic SQL "sea of red" would be necessary to pull this off. Since you know the table has exactly one row, pulling the value for each column can just be a subquery as part of a set of <code>UNION</code>ed queries.</p> <pre><code>DECLARE @sql NVARCHAR(MAX) = N'INSERT dbo.B([Key], Value) ' SELECT @sql += CHAR(13) + CHAR(10) + ' SELECT [Key] = ''' + REPLACE(name, '''', '''''') + ''', Value = (SELECT ' + QUOTENAME(name) + ' FROM dbo.A) UNION ALL' FROM sys.columns WHERE [object_id] = OBJECT_ID('dbo.A'); SET @sql = LEFT(@sql, LEN(@sql)-9) + ';'; PRINT @sql; -- EXEC sp_executesql @sql; </code></pre> <p>Result (I only created 4 columns, but this would work for any number):</p> <pre><code>INSERT dbo.B([Key], Value) SELECT [Key] = 'Column1', Value = (SELECT [Column1] FROM dbo.A) UNION ALL SELECT [Key] = 'Column2', Value = (SELECT [Column2] FROM dbo.A) UNION ALL SELECT [Key] = 'Column3', Value = (SELECT [Column3] FROM dbo.A) UNION ALL SELECT [Key] = 'Column4', Value = (SELECT [Column4] FROM dbo.A); </code></pre> <p>The most efficient thing in the world? Likely not. But again, for a one-row table, and hopefully a one-off task, I think it will work just fine. Just watch out for column names that contain apostrophes, if you allow those things in your shop...</p> <p><strong>EDIT</strong> sorry, couldn't leave it that way. Now it will handle apostrophes in column names and other sub-optimal naming choices.</p>
    singulars
    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