You can get the results from an SP into a table by using the INSERT INTO..EXEC
syntax. I don't advise it, however, as it relies on all datasets being returned from the SP to have the same definition:
USE Sandbox;
GO
CREATE PROC TestProc1 AS
SELECT *
FROM (VALUES(1,'T-Shirt'),
(2,'Jeans'),
(3,'Spotlight')) V(ProductID,ProductName);
SELECT *
FROM (VALUES(1,'Clothing'),
(2,'Lighting')) V(DeptID, DepartmentName);
GO
CREATE TABLE #TempTable (ID int, [Name] varchar(15));
INSERT INTO #TempTable
EXEC TestProc1;
SELECT *
FROM #TempTable;
GO
DROP TABLE #TempTable
DROP PROC TestProc1;
As soon as you throw in a dataset that has a different definition (for example, different number of columns, or perhaps a value that can't be implicitly cast (i.e. 'abc' to an int
) it'll fail. For example:
USE Sandbox;
GO
CREATE PROC TestProc1 AS
SELECT *
FROM (VALUES(1,'T-Shirt',1),
(2,'Jeans',1),
(3,'Spotlight',2)) V(ProductID,ProductName,DeptID);
SELECT *
FROM (VALUES(1,'Clothing'),
(2,'Lighting')) V(DeptID, DepartmentName);
GO
CREATE TABLE #TempTable (ID int, [Name] varchar(15));
--fails
INSERT INTO #TempTable
EXEC TestProc1;
SELECT *
FROM #TempTable;
GO
DROP TABLE #TempTable;
GO
CREATE TABLE #TempTable (ID int, [Name] varchar(15),OtherID int);
--fails
INSERT INTO #TempTable
EXEC TestProc1;
SELECT *
FROM #TempTable;
GO
DROP TABLE #TempTable
DROP PROC TestProc1;
You should really be using multiple SP's and handling the data that way.