在客户端进行大批量的数据更改时,如果全部在客户端处理导入逻辑,就需要频繁的读写数据库,这样就不可避免的出现性能瓶颈,我们需要一种方法能将数据一次性提交给SQLServer来处理,这样就可以避免这个问题。
这里给出一个方案和具体示例:
- 在客户端将对象集合序列化为XML
- 在数据库端处理客户端发送来的XML数据,并进行校验
C# 对象序列化方法:
MEABlock myBlock = new MEABlock();
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new XmlSerializer(typeof(MEABlock));
// To write to a file, create a StreamWriter object.
StreamWriter myWriter = new StreamWriter(myFileName.xml);
mySerializer.Serialize(myWriter, MEABlock);
以下是SQL Server 上使用XPath解析XML的示例
DECLARE @ItemMessage XML
DECLARE @ItemTable TABLE(ItemNumber INT PRIMARY KEY,ItemDescription NVARCHAR(300))
SET @ItemMessage=N'<ItemList xmlns="http://cd.love.com/SOA">
<Item>
<ItemNumber>1</ItemNumber>
<ItemDescription>XBox 360,超值</ItemDescription>
</Item>
<Item>
<ItemNumber>2</ItemNumber>
<ItemDescription>Windows Phone7,快来尝鲜吧</ItemDescription>
</Item>
</ItemList>'
;WITH XMLNAMESPACES(DEFAULT 'http://cd.love.com/SOA')
INSERT INTO @ItemTable
(
ItemNumber,
ItemDescription
)
SELECT T.c.value('(ItemNumber/text())[1]','INT'),
T.c.value('(ItemDescription/text())[1]','NVARCHAR(300)')
FROM @ItemMessage.nodes('/ItemList/Item') AS T(c)
SELECT ItemNumber,
ItemDescription
FROM @ItemTable