Pivot the results of a stored procedure?

2019-06-12 14:30发布

问题:

I have a stored procedure that always returns one row. I want to convert each column_name and its corresponding value to a row. Example -

ID | Name | Address
-----------------------
1  | Jim  | Home

should become -

ID      |  1
---------------------
Name    | Jim
Address | Home

How do I do this ?

回答1:

You'll need to insert the values from the stored procedure into a (temporary) table, and then unpivot from there. Psuedocode below:

CREATE TABLE #t (ID int, Name varchar(100), Address varchar(100))

INSERT INTO #t
EXEC stored_proc

SELECT ID = 'Name', [1] = Name
FROM #t
UNION ALL
SELECT ID = 'Address', [1] = Address
FROM #t

DROP TABLE #t