Sometimes, you want to store the result of a stored procedure into table or temp table instead of returning the output. Storing output of stored procedure into table enables more option for you, such as you can validate the output of stored procedure any time later or you can join that table with another table, and so on..
Lets demonstrate how to insert the stored procedure output into a table.
CREATE TABLE dbo.StudentData(ID INT IDENTITY(1,1), Name VARCHAR(100)) INSERT INTO dbo.StudentData(Name) VALUES('Rohit Khatri'), ('Sujoy Ghosh'), ('Manoj Singh'), ('Vimal Kumar') GO SELECT * FROM dbo.StudentData;
Now we will create a stored procedure which returns all the student records from StudentData table.
CREATE PROCEDURE dbo.FetchStudentData AS BEGIN SELECT * FROM dbo.StudentData; END GO EXEC dbo.FetchStudentData GO
Lets store the output of above stored procedure into table.
First we create another table named StudentData_Log that will be used to store stored procedure output.
CREATE TABLE dbo.StudentData_Log (ID INT, Name VARCHAR(100)) SELECT * FROM dbo.StudentData_Log;
You can see, table does not have any data right now.
Lets execute the stored procedure and store the output into table StudentData_Log as shown below.
INSERT INTO dbo.StudentData_Log EXEC dbo.FetchStudentData GO
Lets check the table StudentData_Log, and you can see the output of stored procedure is stored into table. Table have same number of records as returned by stored procedure.
SELECT * FROM dbo.StudentData_Log;
In similar way, you can store stored procedure output into temporary/ temp table as shown below.
CREATE TABLE #StudentData_Log (ID INT, Name VARCHAR(100)) SELECT * FROM #StudentData_Log;
Lets execute the stored procedure and insert output into above temp table.
INSERT INTO #StudentData_Log EXEC dbo.FetchStudentData GO
Lets check the temp table, and you can see the stored procedure output is inserted in table.
SELECT * FROM #StudentData_Log;