chobo
chobo

Reputation: 32311

store and use select statement result in stored proc?

Is it possible to store the results of a select query in a stored proc and then use those results from within the stored proc to further query the result set?

Example // my stored proc (simplified example)

ALTER PROCEDURE [dbo].[users]  
AS
BEGIN

    Declare @users nvarchar(1000)            

        set @users = select * from users


    // query @users result for counts, sums where clauses, etc...


END

Upvotes: 3

Views: 1982

Answers (3)

Aaron Bertrand
Aaron Bertrand

Reputation: 280431

You can use a table variable:

DECLARE @users TABLE (...columns...);
INSERT @users SELECT * FROM dbo.Users;

Though depending on the number of rows, a #temp table can often be safer because it will have statistics, you can create additional indexes, etc.

CREATE TABLE #users (...columns...);
INSERT #users SELECT * FROM dbo.Users;

Upvotes: 2

Joe Stefanelli
Joe Stefanelli

Reputation: 135848

You want users to be a table variable or temp table instead of an nvarchar type.

Table Variable Version

DECLARE @users TABLE (
    UserId int,
    ...
)

INSERT INTO @users
    (UserId, ...)
    SELECT *
        FROM users

SELECT *
    FROM AnotherTable t
        INNER JOIN @users u
            ON ...

Temp Table Version

CREATE TABLE #users (
    UserId int,
    ...
)

INSERT INTO #users
    (UserId, ...)
    SELECT *
        FROM users

SELECT *
    FROM AnotherTable t
        INNER JOIN #users u
            ON ...

You could also implicitly create the temp table.

SELECT *
    INTO #users
    FROM users

SELECT *
    FROM AnotherTable t
        INNER JOIN #users u
            ON ...

Upvotes: 6

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74410

You can use a temp table or a table variable to do just that. Here is a blog post comparing the options.

Upvotes: 1

Related Questions