大家都知道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)
运行结果如下:
将xml类型作为存储过程的参数,批量删除的存储过程如下:
CreateProcedure pro_Batch_Delete @xmlParam xml As Deletefrom t_TableName Where ID in (Select T.ID.value('.', 'int') As ID From @xmlParam.nodes('/Delete/ID') as T(ID))
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])
执行此脚本,可以得到我们想要的表:
批量插入记录的存储过程如下:
CreateProcedure pro_Batch_Insert @xmlParam xml As InsertInto 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]) )