简体   繁体   中英

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

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 ...

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM