如何基于单个XML参数创建动态sql语句
我需要创建一个动态 SQL 语句,根据 XML 参数选择字段。
假设我有一个带有 1 个参数的存储过程 - [@FIELDS XML],其中包含字段名称。例如...
字段 1 = 名称
字段 2 = 地址等.....
实际上最多有 50 个字段,我只想报告 XML 参数中的字段。
我怎样才能做出像这样的简单声明工作..
select
xmlParam1,
xmlParam2,
...
xmlParamN
from TABLE
等...
注意:数据来自c#中的字符串数组。
谢谢!
i need to create a dynamic SQL statement that selects fields based on an XML parameter.
Say i have a stored proc with 1 param - [@FIELDS XML] that contains field names. eg...
Field 1 = Name
Field 2 = Address etc...
..in reality there would be up to 50 fields and i only want to report on the ones in the XML parameter.
how can i make a simple statement like this work..
select
xmlParam1,
xmlParam2,
...
xmlParamN
from TABLE
etc...
NB: the data is coming from a string array in c#.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需循环遍历数组以将适当的 SQL 查询创建为字符串,然后执行它,例如:
显然,
SET @SQL
部分将是循环遍历数组并构建字符串的位置。编辑
要循环遍历 xml,您必须首先从中选择一个记录集,例如
您必须然后遍历记录集,构建字符串。有很多方法可以做到这一点,例如使用临时表或游标。可以在此处找到一些示例。
Simply loop through the array to create the appropriate SQL query as a string, then EXEC it, for instance:
Obviously, the
SET @SQL
part would be where you loop through the array, building the string.EDIT
To loop through the xml, you must firstly SELECT a recordset from it, such as
You must then iterate through the recordset, building your string. There are many ways to do this, such as using temp tables or cursors. Somes examples can be found here.