tags:

views:

282

answers:

2

Hi All, I want to know, How can I store multiple rows in a variable.i.e. My query will return multiple rows and i want to store it in a variable. Thanks in adv.

A: 

You can use a table valued parameter or you can use the old stand-by temp tables.

JP Alioto
+3  A: 

In SQL Server 2008, there's a feature called Table Valued Parameters which allow you to store rows into a variable that can be passed across stored procedures.

If however, your intent is to manipulate the data inside the same store procedure, then common table variables would be fine. Here's an Example:

DECLARE @MyTableVariable TABLE
(
  Id int,
  FirstName varchar(10),
  LastName varchar(10)
);

INSERT @MyTableVariable(Id, FirstName, LastName)
SELECT Id, FirstName, LastName FROM SomeOtherTable WHERE SomeCriteria

@MyTableVariable now contains all the rows matching the criteria, you can still continue to add more rows, do further manipulations and even return its contents.

Jose Basilio
Thanks for ur help
Wondering
I assume you meant "@MyTableVariable now contains", not @TableVariable.
Nick
Also, Table Valued Parameters are available in SQL Server 2005 as well.
Nick
@Nick - Table Valued Parameters do no exist in SQL Server 2005. Read this: http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!222.entry
Jose Basilio