查询从包含XML格式的数据的列中提取值

时间:2014-04-28 11:19:08

标签: sql sql-server-2008 query-analyzer

假设我有一个表 mydata ,其中有一列 xmldata ,其值为XML格式的文本,例如

<maindataheading>
    <firstleveldata>
        <pricedata pricetype="normal">123</pricedata>
    </firstleveldata>
</maindataheading>

如何从xmldata列中提取<pricedata pricetype="normal">123</pricedata>

2 个答案:

答案 0 :(得分:0)

下面是用于从XML检索varchar值的示例SQL:

DECLARE @MyXmlData XML

-- Read XML data into variable
 SELECT @MyXmlData = xmldata
   FROM MyData

-- Check if the XML node exists before attempting to retrieve it
IF @MyXmlData.exist('/maindataheading/firstleveldata/pricedata') = 1
BEGIN
    DECLARE @MyDataValue VARCHAR(255)

    -- Get specific XML data
     SELECT @MyDataValue = ParamValues.ID.Value('.', 'varchar(255)')
       FROM @MyXmlData.nodes('/maindataheading/firstleveldata/pricedata') AS ParamValues(ID)

    IF @MyDataValue IS NOT NULL
    BEGIN
        -- Do something with data
    END
END

答案 1 :(得分:0)

select xmldata.query('/maindataheading/firstleveldata/pricedata')
from mydata

结果:

<pricedata pricetype="normal">123</pricedata>