我需要查询来获取有关XML的数据计数

时间:2017-08-16 11:19:44

标签: sql-server

我有一个表CampaignXml,其中包含CampaignXml列以及其他列。在CampaignXml中,我保存了问题。我需要一个查询来获取所有top 1 CampaignXML列中的问题数量。

我使用Campaign表中的CampaignXml编写了一个存储过程,但我想查看表中的所有ALTER PROCEDURE [dbo].[GetPanelsitCount] AS DECLARE @CampaignXML NVARCHAR(MAX) DECLARE @idoc INT DECLARE @Marketid INT SELECT DISTINCT TOP 1 @CampaignXML = CampaignXML, @marketid = marketid FROM dbo.Campaign WHERE campaigntypeid = 8 AND CampaignXML IS NOT NULL AND statusid = 57 AND marketid = 24 EXEC sp_xml_preparedocument @idoc OUTPUT ,@CampaignXML (SELECT ID INTO #tblQuestionId FROM OPENXML(@idoc, 'XmlCampiagn/Pages/Page[1]/Questions/Question') WITH (ID INT '@ID')) -- select * from #tblQuestionId 并获取问题计数。

<XmlCampiagn Name='My Campaign' ID='4'>
    <GlobalSetting Name='Global Setting'>
        <MobileNumberVerification Enabled='False' Mandatory='False' Required='False'></MobileNumberVerification>
        <XGEOTargeting Enabled='False'></XGEOTargeting>
        <Captcha Enabled='False'></Captcha>
    </GlobalSetting>
    <Pages>
        <Page ID= '1' Name='Default' PageType='Default' Mode='0'>
            <PipingLogics></PipingLogics>
            <Questions>
                 <Question MaxLength='' Validation='' ID='6448' 
                           Mandatory='True' Required='False' IsNonEditable='False'/>
            </Questions>
            <Logics></Logics>
            <Masking‌​Logics></MaskingLogi‌​cs>
        </Page>
    </Pages>
</‌​XmlCampiagn>

示例XML:

{{1}}

1 个答案:

答案 0 :(得分:1)

您可以使用SQL Server中的原生XQuery 支持轻松完成此操作 - 无需使用sp_xml_preparedocument或类似的任何遗留内容....

试试这个:

SELECT 
    CampaignId, 
    CAST(CampaignXml AS XML).value('count(//Question)', 'int')
FROM
    dbo.Campaign
WHERE 
    CampaignTypeId = 8 
    AND CampaignXml IS NOT NULL  
    AND StatusId = 57    
    AND MarketId = 24

这将为您提供该广告系列的CampaignId和问题数(所有可能的多个<Page>子元素的所有问题)。如果您只需要 总计,请使用:

SELECT 
    SUM(CAST(CampaignXml AS XML).value('count(//Question)', 'int'))
FROM
    dbo.Campaign
WHERE 
    CampaignTypeId = 8 
    AND CampaignXml IS NOT NULL  
    AND StatusId = 57    
    AND MarketId = 24