2013-03-04 76 views
0

我試圖將xpath作爲參數傳遞給查詢。xml查詢變量

declare @test as nvarchar(1000) = '(ns1:Book/Authors)[1]' 
    ;with XMLNAMESPACES ('MyNameSpace:V1' as ns1) 
    select 
    b.XmlData.value(
    '@test' 
    , 'nvarchar(100)') as QueriedData 
    from Books b 
    where b.BookID = '1' 

上述說明給出了以下錯誤。

XQuery [Books.XmlData.value()]: Top-level attribute nodes are not supported 

試過它作爲@test而不是'@test'。並得到了以下錯誤:

The argument 1 of the XML data type method "value" must be a string literal. 

試了一下使用 'SQL:變量(@test)' 和得到這個錯誤:

XQuery [Books.XmlData.value()]: A string literal was expected 

試圖爲「SQL:變量( 「@測試」) 「,它體現在@Test爲QueriedData,這是錯誤的價值

請告訴我,我在這裏缺少

+0

您不能使用變量而不是xQuery表達式。你有一個選擇是動態構建和執行查詢,如[本答案](http://stackoverflow.com/a/14812275/569436)。 – 2013-03-04 13:38:16

回答

1

不能使用變量作爲XQuery表達式,但表達式可以參考到變量。

set @ix = 2 
with XMLNAMESPACES ('MyNameSpace:V1' as ns1) 
select 
b.XmlData.value(
    '((ns1:Book/ns1:Authors)[sql:variable("@ix")])[1]' 
    , 'nvarchar(100)') as QueriedData 
    from Books b 
    where b.BookID = '1' 

這包括元素名稱。例如,把節點名稱參數:

declare @elementName nvarchar(20) set @elementName = 'Authors' 


    with XMLNAMESPACES ('MyNameSpace:V1' as ns1) 
    select 
    b.XmlData.value(
     '((//ns1:*)[ local-name()=sql:variable("@elementName") ])[1]' 
     , 'nvarchar(100)') as QueriedData 

這意味着「查找命名空間NS的元素,其中有@elementName的本地名字,然後返回第一個。」