大家都知道SQL Server 2005新增了xml字段类型,我们可以利用它来实现批量操作数据库的需要,减少应用程序频繁、反复的建立数据库连接的情况发生,比如批量删除,我们可以在应用程序中构建如下xml:
<Delete><ID>1</ID><ID>2</ID><ID>3</ID></Delete>
在数据库中可以通过下面的脚本获得这些ID:
Select
T.ID.value('.', 'int') As ID
From
@xmlParam.nodes('/Delete/ID') as T(ID)
T.ID.value('.', 'int') As ID
From
@xmlParam.nodes('/Delete/ID') as T(ID)
运行结果如下:
将xml类型作为存储过程的参数,批量删除的存储过程如下:
Create Procedure pro_Batch_Delete
@xmlParam xml
As
Delete from
t_TableName
Where ID in
(Select
T.ID.value('.', 'int') As ID
From
@xmlParam.nodes('/Delete/ID') as T(ID))
@xmlParam xml
As
Delete from
t_TableName
Where ID in
(Select
T.ID.value('.', 'int') As ID
From
@xmlParam.nodes('/Delete/ID') as T(ID))
大家也知道,DataSet中的数据可以直接序列化成xml,通过dataSet.GetXml(),我们可以将这个xml作为存储过程参数,实现稍微复杂的功能,比如批量插入数据,在数据库中怎样将这个xml转换为表呢,我们先看DataSet序列化的xml结构:
<DataSet>
<Table><ID>1</ID><Count>1</Count></Table>
<Table><ID>2</ID><Count>2</Count></Table>
<Table><ID>3</ID><Count>3</Count></Table>
</DataSet>
<Table><ID>1</ID><Count>1</Count></Table>
<Table><ID>2</ID><Count>2</Count></Table>
<Table><ID>3</ID><Count>3</Count></Table>
</DataSet>
当然也可以包含多个表,这里我们以一个表举例,转换脚本如下:
Declare @Xml xml
Set @Xml = '
<DataSet>
<Table><ID>1</ID><Count>1</Count></Table>
<Table><ID>2</ID><Count>2</Count></Table>
<Table><ID>3</ID><Count>3</Count></Table>
</DataSet>'
Select
T2.ID.value('.', 'int') As ID, T3.[Count].value('.','int') As [Count]
From
(Select
T.Records.query('ID') As ID,
T.Records.query('Count') As [Count]
From
@Xml.nodes('/DataSet/Table') As T(Records)
) As T1
Cross Apply T1.ID.nodes('ID') As T2(ID)
Cross Apply T1.[Count].nodes('Count') As T3([Count])
Set @Xml = '
<DataSet>
<Table><ID>1</ID><Count>1</Count></Table>
<Table><ID>2</ID><Count>2</Count></Table>
<Table><ID>3</ID><Count>3</Count></Table>
</DataSet>'
Select
T2.ID.value('.', 'int') As ID, T3.[Count].value('.','int') As [Count]
From
(Select
T.Records.query('ID') As ID,
T.Records.query('Count') As [Count]
From
@Xml.nodes('/DataSet/Table') As T(Records)
) As T1
Cross Apply T1.ID.nodes('ID') As T2(ID)
Cross Apply T1.[Count].nodes('Count') As T3([Count])
执行此脚本,可以得到我们想要的表:
批量插入记录的存储过程如下:
Create Procedure pro_Batch_Insert
@xmlParam xml
As
Insert Into t_TableName (ID, [Count])
(
Select
T2.ID.value('.', 'int') As ID, T3.[Count].value('.','int') As [Count]
From
(Select
T.Records.query('ID') As ID,
T.Records.query('Count') As [Count]
From
@xmlParam.nodes('/DataSet/Table') As T(Records)
) As T1
Cross Apply T1.ID.nodes('ID') As T2(ID)
Cross Apply T1.[Count].nodes('Count') As T3([Count])
)
@xmlParam xml
As
Insert Into t_TableName (ID, [Count])
(
Select
T2.ID.value('.', 'int') As ID, T3.[Count].value('.','int') As [Count]
From
(Select
T.Records.query('ID') As ID,
T.Records.query('Count') As [Count]
From
@xmlParam.nodes('/DataSet/Table') As T(Records)
) As T1
Cross Apply T1.ID.nodes('ID') As T2(ID)
Cross Apply T1.[Count].nodes('Count') As T3([Count])
)
同样,可以实现批量update的功能,这里不具体列举了,实现核Insert是基本相同的。
这里只使用部分SQL2005关于xml几个谓词和函数,在MSDN中都有说明,还有其他更强大的功能等大家一起去发掘.