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.
First, we create a sample table named StudentData and insert some dummy records into 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;
Also Read..
Howย to get the definitions of stored procedures, user defined functions and triggers in SQLย ?
What is SQL Server user defined table type and table valued parameters?
How to access the files name list from window directory folder to SQL Server table using T-SQL Query?
Difference between Truncate and Delete statements in SQL Server?
41,416 total views, 10 views today