views:

41

answers:

2

How can I pass a list of object in a SQL Procedure with SQL Server 2008 ?

I want to avoid this :

foreach (var item in itemList)
{
   myContext.ExecuteStoreCommand("EXEC MyAtomicProc ... item ...);
}

I want to do the foreach in a store procedure.

How can I pass a c# list of object and execute this procedure in EF :

myContext.ExecuteStoreCommand("EXEC MyGlobalProc ... itemList ...);
+1  A: 

You can not. You can:

  • Provide scalar values (variables)
  • Provide a TABLE of values

But you CAN NOT pass in objects. Objects do not exist at the SQL layer in a way that is compatible with the .NET runtime.

TomTom
Ok. Performance are very very very bad when I do the loop in c# comparing to the same kind of loop in T-SQL.
Patrice Pezillier
As TomTom said, convert the list of objects to a TABLE. Look for passing XML parameters and how to use them as a table in SQL Server.
Lieven
If you're talking about doing a cursor loop in t-sql, don't expect any type of performance advantage.
Jeff O
A: 

What I like to do is serialize the list of objects into a string, then pass that as a DB parameter.

Then in the stored proc you can use XML transform to create a temp table that you can join in onto. This lets you easily do bulk updates and inserts (using left join)

This converts a list of key value pairs to a temp table. You can extract it to a list of anything really.:

DECLARE @xmlHandle INT 
DECLARE @pixelParametersTable TABLE (
 [Key] VARCHAR(10) PRIMARY KEY, 
 [Value] VARCHAR(MAX)) 
EXEC sp_xml_preparedocument @xmlHandle output, @pixelParameters

INSERT INTO @pixelParametersTable 
SELECT [Key], [Value]
FROM  OPENXML (@xmlHandle, '/PixelRequestParameters/Parameter',1)
WITH (  
 [Key] VARCHAR(10) 'Key',
 [Value] VARCHAR(8000) 'Value'
) 
EXEC sp_xml_removedocument @xmlHandle
Slappy