创建多个带有不同参数的存储过程(stored procedure)来完成同一个任务总是一个很大的负担。利用xml字符串向你的存储过程发送参数就能够简化这个任务;这也让com组件的设计更简单。
实现这个目的的方法是将你的参数作为一个xml字符串来传递,并剖析xml来取回你所需要的数据,然后继续实现你所需要集成的功能。你不仅可以通过xml来获取一些参数,你还可以对xml所创建的dom文档运行查询,以此来封装多个存储过程。我会提供一些例子,告诉你如果实现这个目的,并简要地描述每个例子。
在本例里,为了更新一个customer表格里的姓名字段,我会传递几个参数。为了获得customerid(身份列)和新的姓名字段,xml会被剖析。我传递给过程的xml字串就像下面的这样:
<root><customer><customerid>3</customerid><name>acme
inc.</name></customer></root>
要被创建的存储字段就像下面的这样:
create procedure update_customer (@xmldatavarchar(8000)) as
declare @customeridint
declare @customernamevarchar(50)
declare @xmldata_idint
exec sp_xml_preparedocument @xmldata_id output, @xmldata, ''
select @customerid = customerid, @customername = [name] from
openxml(@xmldata_id, '//customer', 2) with (customeridint, [name]
varchar(50))
exec sp_xml_removedocument @xmldata_id
update customer set customer.[name] = isnull(@customername, customer.[name])
where customer.tblid = @customerid
这个过程首先就声明我们将要用到的变量会保存相关信息。在此之后,dom文档被打开,一个“句柄(handle)”会被返回到sp_xml_preparedocument调用的第一参数里。
这个调用的第二个参数是用于新dom文档的xml源文件。这个“句柄”是在进行openxml调用的时候用来从dom里查询信息的。openxml调用的第二个参数是父节点的一个xpath映射,这些父节点包含有要被执行的数据。
第三个参数(2)指明,以元素为中心的映射会被使用。with子句为被剖析的数据提供了数据列集(rowset)格式,sp_xml_removedocument调用会删掉dom文档的源文件。
在下面这个例子里,我会传递一系列用户id,用以删除多个数据列。下面就是xml字符串的内容:
<root><customer><customerid>1</customerid></customer><customer><customerid>
2</customerid></customer><customer><customerid>3</customerid></customer>
</root>
相应的存储过程看起来就像下面这样:
. . .
exec sp_xml_preparedocument @xml_id output, @xmldata, ''
delete from customer where customer.tblid in (select customerid from
openxml(@xmldata_id, '//customer', 2) with (customeridint))
. . .
有了这个存储过程就不再需要创建一个冗长的sql查询字符串,用以在ado里传递或者多次调用一个存储过程了。这也会消除多次调用对网络流量所造成的影响。
正如你能够看到的,微软的sql 2000让整个过程稍稍简单了一点。要记住,这一方法的不足之处在于:在sql 2000进行xml任务的时候,将xml作为一个参数发送会被限制到8,000字符。和以往一样,不要忽视了精心策划的好处。
访问msdn库能够获得更多关于openxml、sp_xml_preparedocument以及sp_xml_removedocument的信息。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器