3

Is there a way to store the results of a SELECT query in a stored proc using SQL Server?

In the example below I would like to store both "one", and "two" from the select query.

Example:

DECLARE @Values ???
SET @Values = (SELECT one, two FROM dummyTable)
2
  • 1
    You wish to grab multiple values from a single row or many rows? Commented Jan 3, 2012 at 20:27
  • Derived tables? 4guysfromrolla.com/webtech/112098-1.shtml Commented Jan 3, 2012 at 20:47

3 Answers 3

5

You can use a table variable for this:

DECLARE @Table TABLE (one varchar(100), two varchar(100)

INSERT INTO @TABLE
SELECT one, two from dummytable

Like other variables, this won't be accessible from outside the scope of the proc.

It's also not good for large numbers of rows since the optimizer always assumes a single row for execution plans.

Sign up to request clarification or add additional context in comments.

Comments

4
SELECT @Value1 = One, @Value2 = two FROM dummyTable;

You don't have any arrays in SQL Server.

1 Comment

This is a very useful technique
2

If your query only returns a single row:

DECLARE @v1 int -- or whatever
DECLARE @v2 int
SELECT @v1 = one, @v2 = two
  FROM dummyTable
  WHERE id = 1 

If your query returns multiple rows, you can use SELECT INTO to avoid having to declare a table variable:

SELECT one, two
  FROM dummyTable
  INTO #temp
SELECT * FROM #temp
DROP TABLE #temp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.