Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is any way to pass object or list to sql server stored procedure? [duplicate]

Tags:

c#

.net

sql

asp.net

I want to pass object or list to sql server stored procedure. My purpose is to insert multiple records at a time via store procedure.

So, is there any way to do it?

like image 262
Kvadiyatar Avatar asked Sep 26 '13 10:09

Kvadiyatar


People also ask

Can we pass object in stored procedure?

In Part 1, I described how to pass a DataTable into a stored procedure using a structured type. So the question is, are there any other types you can pass as a structured parameter? The answer is yes. You can also pass a collection object to a structured type parameter.

Is stored procedure reusable?

Stored procedures have many benefits—they can be easily modified, are reusable and they possess the ability to automate a task that requires multiple SQL statements.


3 Answers

You can use sqlParameter. Like:

SqlParameter param1 = new Sqlparameter(SPVariablename , ValueofVariablewhichYouWantToPass)

Any as many parameter you want param2, param3 and in end

cmd.Parameter.add(param1)
Execute the command
like image 186
Wolfgang Avatar answered Oct 11 '22 06:10

Wolfgang


There Number of Ways like using XML and List. But if you want to do bulk insert, you can use

BULK INSERT

like image 25
Anand Avatar answered Oct 11 '22 05:10

Anand


I believe in SQLServer 2008 and later you can have a strongly typed DataTable parameter to your stored procedure which you can pass a .Net DataTable to.

BULK INSERT is a good suggestion for just inserting large numbers of rows and it is much quicker than single inserts.

For inserting hierarchical object data eg Parent 1 has 2 child records, Parent 2 has 3 child records, Parent 3 has 1 child record... I have in the past used XML to serialize the object structure in .Net before passing to SQLServer and shredding it out into tables. Of course if you are doing stuff like this a lot you would probably be better served to be using Entity Framework or NHibernate etc...

like image 32
El Ronnoco Avatar answered Oct 11 '22 04:10

El Ronnoco