Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return temporary table from stored procedure

CREATE PROCEDURE [test].[proc]
@ConfiguredContentId int,
@NumberOfGames int
AS
BEGIN
 SET NOCOUNT ON
 RETURN 
 @WunNumbers TABLE (WinNumb int)

    INSERT INTO @WunNumbers (WinNumb)
 SELECT TOP (@NumberOfGames) WinningNumber
 FROM [Game].[Game] g
 JOIN [Game].[RouletteResult] AS rr ON g.[Id] = rr.[gameId]
 WHERE g.[ConfiguredContentId] = @ConfiguredContentId
 ORDER BY g.[Stoptime] DESC

 SELECT WinNumb, COUNT (WinNumb) AS "Count"
 FROM @WunNumbers wn
 GROUP BY wn.[WinNumb]
END
GO

This stored procedure returns values from first select statement, but I would like to have values from second select statement to be returned. Table @WunNumbers is a temporary table.

Any ideas???

like image 803
dani Avatar asked Sep 18 '09 10:09

dani


People also ask

How do I return a temp table from a function in SQL Server?

No, you cannot "return" a temp table - you can create that temp table before calling your function, and have your function write data into that temp table. But this has a tendency to get rather messy .... you need to make sure to have the temp table created before calling the function.....

Can we return table variable from stored procedure?

The RETURN exits the stored procedure, and nothing that follows it will be executed, including the SELECT statement on the following line. Otherwise, if you want the data for the entire table, as your question shows, add a SELECT after the INSERT . But don't put RETURN in front of it!

How can we store stored procedure result in temp table in SQL Server?

When the stored procedure returns a lot of columns and you do not want to manually "create" a temporary table to hold the result, I've found the easiest way is to go into the stored procedure and add an "into" clause on the last select statement and add 1=0 to the where clause.

How do you insert the output of a stored procedure into a table?

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.


1 Answers

Take a look at this code,

CREATE PROCEDURE Test

AS
    DECLARE @tab table (no int, name varchar(30))

    insert @tab  select eno,ename from emp  

    select * from @tab
RETURN
like image 126
KV Prajapati Avatar answered Oct 13 '22 16:10

KV Prajapati