运行 已转换为 XML 的文本字段上的 XQuery

Running XQuery on a text field that's been CAST to XML

我正在尝试对已转换为 XML 的文本数据使用 XQuery,但没有成功。所以这失败了:

    DECLARE @myDoc TEXT  
    SET @myDoc = '<Root>  
    <ProductDescription ProductID="1" ProductName="Road Bike">  
    <Features>  
      <Warranty>1 year parts and labor</Warranty>  
      <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>  
    </Features>  
    </ProductDescription>  
    </Root>'  

SELECT CAST(@myDoc AS XML)('(/Root/ProductDescription/@ProductID)[1]', 'int' )  

但这成功了:

DECLARE @myDoc xml  
DECLARE @ProdID int  
SET @myDoc = '<Root>  
<ProductDescription ProductID="1" ProductName="Road Bike">  
<Features>  
  <Warranty>1 year parts and labor</Warranty>  
  <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>  
</Features>  
</ProductDescription>  
</Root>'  

SELECT  @myDoc.value('(/Root/ProductDescription/@ProductID)[1]', 'int' )  

我明白了 David Brown 在说什么,这有效:

DECLARE @myDoc NVARCHAR(MAX)  
DECLARE @ProdID int  
SET @myDoc = '<Root>  
<ProductDescription ProductID="1" ProductName="Road Bike">  
<Features>  
  <Warranty>1 year parts and labor</Warranty>  
  <Maintenance>3 year parts and labor extended maintenance is available</Maintenance>  
</Features>  
</ProductDescription>  
</Root>'  

SELECT CAST(@myDoc AS XML).value('(/Root/ProductDescription/@ProductID)[1]', 'int' )