如何使用动态sql查询方法“EXECUTE sp_executesql”读取xml节点值

时间:2017-07-02 19:53:00

标签: sql sql-server xml

在此声明XML

DECLARE @input XML 
set @input= '<AcordXML><location id="1"><id>1</id><name>first</name><noofemp>37</noofemp> </location></AcordXML>'

设置动态查询

Declare @Equery varchar(max)
set @Equery='SELECT C.value(''name[1]'',''varchar(MAX)''), C.value(''noofemp[1]'', ''varchar(MAX)'') FROM @input.nodes(''//location'') AS T(C)'
    print @Equery
    EXECUTE sp_executesql @Equery, N'@input varchar(max)',@input=@input

2 个答案:

答案 0 :(得分:0)

将proc @input参数声明为XML,与您实际传递的类型相同

DECLARE @input XML 
SET @input = '<AcordXML > <location id="1"><id>1</id> <name>first</name><noofemp>37</noofemp> </location></AcordXML>'

DECLARE @Equery nvarchar(max)
SET @Equery = 'SELECT C.value(''name[1]'',''varchar(MAX)''), C.value(''noofemp[1]'', ''varchar(MAX)'') FROM @input.nodes(''//location'') AS T(C)'

EXECUTE sp_executesql @Equery, N'@input XML',@input=@input

答案 1 :(得分:0)

棘手的事情是仅传递参数,首先您可以看到XML参数@Persons的DECLARE数据类型为XML,然后您必须声明sql查询本身的语句-确保将其包装用单引号引起来,棘手的部分是在执行时,请确保按如下所示添加参数: 1- @stmt是要执行的字符串查询 2-在查询中定义参数。 3-从初始化参数中将此参数的值分配为@XMLPersons = @PersonsXml

就这样,您就可以开始了

DECLARE @PersonsXml XML = '<persons > <person ><firstName > Jon </firstName ><lastName > Johnson </lastName > </person >
<person > <firstName >Kathy</firstName > <lastName > Carter </lastName > </person >
<person > <firstName > Bob </firstName > <lastName > Burns </lastName > </person > </persons >'

declare @stmt nvarchar(max)
set @stmt = N'Select person.value(''(firstName/text())[1]'',''nvarchar(100)'') as Mobile_Number  From @XMLPersons.nodes(''/persons/person'') as Persons(person)'

Execute sp_executesql @stmt, N'@XMLPersons xml' , @XMLPersons = @PersonsXml