English 中文(简体)
XML 查询中的变量使用
原标题:Variable usage in XML query
  • 时间:2012-05-23 16:23:18
  •  标签:
  • sql-server

请检查下面的查询 。

        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);

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

我在这里做错什么了?

由于我在父节点上没有关键值来识别子节点, 我不得不通过索引分析 。

最佳回答

这对我管用:

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);
问题回答

暂无回答




相关问题
Export tables from SQL Server to be imported to Oracle 10g

I m trying to export some tables from SQL Server 2005 and then create those tables and populate them in Oracle. I have about 10 tables, varying from 4 columns up to 25. I m not using any constraints/...

SQL server: Can NT accounts be mapped to SQL server accounts

In our database we have an SQL server account that has the correct roles to access some of the databases. We are now switching to windows authentication and I was wondering if we can create a NT user ...

SQL Server 2000, ADO 2.8, VB6

How to determine if a Transaction is active i.e. before issuing Begin Transaction I want to ensure that no previous transaction are open.. the platform is VB6, MS-SQL Server 2000 and ADO 2.8

热门标签