So, you have a couple of problems ... firstly, this requires dynamic sql, because the table and columns are not known in advance, so you cannot just use simple univot.
It also means that you will need to get the column names from the system tables.
The second problem is that all of your data types are unknown, so you need to drop all columns to something that can support anything and any length ... varchar (max).
Thus, given these two obstacles, this solution:
declare @yourTable varchar(50) declare @yourKeyField varchar(50) declare @yourKey varchar(50) set @yourTable = 'MyTable' set @yourKeyField = 'ID' set @yourKey = '5' declare @query nvarchar(max) select @query = COALESCE(@query+' union all ','') + 'select ''' + c.name + ''' as [Column], Cast([' + c.name + '] AS VarChar(MAX)) as [Value] from ' + @yourTable + ' where ' + @yourKeyField + ' = ''' + @yourKey + '''' from syscolumns c inner join sysobjects o on c.id = o.id and o.xtype = 'u' where o.name = @yourTable order by c.colid exec sp_executesql @query
Finally, I cannot, with a clear conscience, recommend a solution that uses dynamic sql without warning about the dangers associated with these (both in terms of performance and injection capabilities). Read this wonderful article if you want to increase your knowledge of this subject.
http://www.sommarskog.se/dynamic_sql.html
source share