1

请检查以下查询。

        declare @xmlRoot as xml
        set @xmlRoot= '<Root>
        <table1 col1="2012-03-02T16:42:55.777">
            <table2Array>
              <Table2 col2="abc">
              </Table2>  
              <Table2 col2="def"> 
              </Table2> 
            </table2Array>
          </table1>
         <table1 col1="2012-03-02T17:42:55.777">
            <table2Array>
              <Table2 col2="abc1">
              </Table2>  
              <Table2 col2="def1"> 
              </Table2> 
            </table2Array>
          </table1>
        </Root>'

        declare @a as varchar(1) 
           set @a= '1' 

         SELECT
        col1 =  item.value('./@col2', 'varchar(10)') 
        FROM @xmlRoot.nodes('Root/table1[1]/table2Array/Table2'  ) AS T(item);

--以上查询返回预期输出

SELECT
col1 =  item.value('./@col2', 'varchar(10)') 
FROM @xmlRoot.nodes('Root/table1[*[local-name()=sql:variable("@a")]]/table2Array/Table2'  ) 
  AS T(item);

-- 上面的查询没有返回预期的输出

我在这里做错了什么?

由于我在父节点中没有键值来识别子节点。我必须通过索引解析。

4

1 回答 1

1

这对我有用:

DECLARE @a INT; -- data type is probably important!
SET @a = 1;

SELECT col1 =  item.value('./@col2', 'varchar(10)') 
FROM @xmlRoot.nodes('Root/table1[sql:variable("@a")]/table2Array/Table2') AS T(item);
于 2012-05-23T16:35:42.150 回答