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
2009-05-01 06:25:41
+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
2009-05-01 06:26:03
Thanks for ur help
Wondering
2009-05-01 06:39:47
I assume you meant "@MyTableVariable now contains", not @TableVariable.
Nick
2009-05-01 07:12:29
Also, Table Valued Parameters are available in SQL Server 2005 as well.
Nick
2009-05-01 07:13:26
@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
2009-05-01 07:21:31