我试图找出如何使用动态xquery从XML加载我的表变量?我从查询中获取节点的结果集并定义这些节点的值类型。它似乎是它正在爆炸的节点的值定义。
以下是可行的脚本示例,但不是动态的。
脚本:
DECLARE @XML XML = '<root>
<data>
<list id="organization" label="Organization">
<options>
<item value="1" label="Organization1" selected="false" />
<item value="2" label="Organization2" selected="false" />
<item value="3" label="Organization3" selected="false" />
<item value="4" label="Organization4" selected="true" />
<item value="5" label="Organization5" selected="true" />
</options>
</list>
</data>
</root>';
DECLARE @Orgs TABLE (ID INT);
Insert Into @Orgs(ID) Select OrgNameIdNodes.ID.value('@value','int') from @xml.nodes('//*[@id="organization"]//item[@selected="true"]') as OrgNameIdNodes(ID);
Select *
from @orgs
我希望能够传递值和@ xml.nodes部分的参数,所以我会这样:
Insert Into @Orgs(ID) Select OrgNameIdNodes.ID.value(@Value) from @xml.nodes(@Nodes) as OrgNameIdNodes(ID);
这可能吗?
答案 0 :(得分:2)
如何将sp_executesql与动态sql一起使用。类似的东西:
DECLARE @XML XML = '<root>
<data>
<list id="organization" label="Organization">
<options>
<item value="1" label="Organization1" selected="false" />
<item value="2" label="Organization2" selected="false" />
<item value="3" label="Organization3" selected="false" />
<item value="4" label="Organization4" selected="true" />
<item value="5" label="Organization5" selected="true" />
</options>
</list>
</data>
</root>';
declare @orgs table(ID int);
declare @nodes nvarchar(4000),
@value nvarchar(4000),
@query nvarchar(4000)
select @value = '''@value'',''int'''
select @nodes = '//*[@id="organization"]//item[@selected="true"]'
select @query = 'Select OrgNameIdNodes.ID.value( ' + @value + ') ' +
'from @xml.nodes(''' + @nodes + ''') as OrgNameIdNodes(ID)'
insert into @Orgs(ID) EXEC sp_executesql @query, N'@xml xml', @xml = @xml
Select *
from @orgs