[英]How to pass .NET Collection of objects (Parent-Child) hierarchy to a SQL Server stored procedure
I need to pass a .NET Collection to a stored procedure. 我需要将.NET集合传递给存储过程。 My collection contains 1000 records.
我的收藏包含1000条记录。 Each record contains 2-3 child objects of other types.
每个记录包含2-3个其他类型的子对象。
All I need to insert them at once by calling stored procedure from .NET. 我需要通过.NET调用存储过程一次插入它们。
I already have tried a TVP (table-valued parameter), but that simply doesn't fulfills my needs. 我已经尝试过TVP(表值参数),但这根本不能满足我的需求。
For each and every root level record, I need to call stored procedure by passing root record and it's corresponding child records. 对于每个根级别记录,我都需要通过传递根记录及其相应的子记录来调用存储过程。 This is making the whole process very slow.
这使整个过程非常缓慢。
That's why I am looking a way, so that I can pass whole hierarchical list at once, and inside stored procedure, by looping and iterating child records I can insert parent child records. 这就是为什么我要寻找一种方法,以便我可以一次循环通过整个层次结构列表,并在存储过程内部通过循环和迭代子记录来插入父子记录。
How can I achieve this? 我该如何实现?
I actually just did this 3 weeks ago. 我实际上在3周前就做了。
Here are a couple of links about the process with "real" examples: 这里有一些带有“真实”示例的有关过程的链接:
merge parent and child SQL Server tables 合并父子SQL Server表
T-SQL - Insert Data into Parent and Child Tables T-SQL-将数据插入父表和子表
You can use XML to pass records as well as their children to stored procedure. 您可以使用XML将记录及其子级传递给存储过程。 For example
例如
DECLARE @xml XML = '<root>
<parent value="213">
<child childValue="1111"></child>
<child childValue="1112"></child>
</parent>
<parent value="2313">
<child childValue="3333"></child>
<child childValue="3332"></child>
</parent>
</root>'
Then you can do many ways, one of them is to denormalize records and save to temp table for further processing 然后,您可以执行多种方法,其中一种方法是对记录进行非规范化并将其保存到临时表中以进行进一步处理
SELECT
T.c.value('parent::*/@value', 'INT') AS ParentValue,
T.c.value('@childValue', 'INT') AS ChildValue
FROM @xml.nodes('/root[1]/parent/child') T(c)
Result will look like 结果看起来像
ParentValue ChildValue
213 1111
213 1112
2313 3332
2313 3333
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.