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 clau开发者_StackOverflowses, 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.
精彩评论