如何简化嵌套的SQL-Server选择查询

时间:2013-12-04 20:21:41

标签: sql sql-server sqlxml simplify nested-queries

我正在针对包含以下表格的数据库简化一些查询:

  1. tShop
  2. tShopItems
  3. tInvoices
  4. tInvoiceRows
  5. 有一个嵌套查询生成一个xml输出,如下所示:

     <InvoiceInfo>
      <Invoice Id="100188">Invoice Title</Invoice>
      <InvoiceRows>
        <InvoiceRow Id="80190">Invoice Row 1 Title</InvoiceRow>
        <InvoiceRow>
          <ShopItem Id="20033">Invoice Row 2 Title</ShopItem>
        </InvoiceRow>
      </InvoiceRows>
      <Shop Id="3">Shop Title</Shop>
    </InvoiceInfo>
    

    查询是:

    SELECT
        (cast(i.InvoiceId as nvarchar)) as 'Invoice/@Id',
        i.InvoiceNote as 'Invoice/text()',
        (SELECT 
            (cast(ir.InvoiceRowId as nvarchar)) as 'InvoiceRow/@Id',
            InvoiceRowNote as 'InvoiceRow/text()',
            (SELECT 
                (cast(si.ShopItemId as nvarchar)) as 'ShopItem/@Id',
                si.ShopItemTitle as 'ShopItem/text()'
            FROM 
                [BizBank.Shops].dbo.tShopItems si
            WHERE
                si.ShopItemId=ir.InvoiceRowItemId
            for 
                xml path(''),root('InvoiceRow'), type
            )
        FROM 
            tInvoiceRows ir
        WHERE
            i.InvoiceId=ir.InvoiceRowInvoiceID
        for 
            xml path(''), root('InvoiceRows'), type
        ),
        (SELECT 
            (cast(s.ShopId as nvarchar)) as 'Shop/@Id',
            s.ShopTitle as 'Shop/text()'
        FROM 
            [BizBank.Shops].dbo.tShops s
        WHERE
            s.ShopID=i.InvoiceShopId
        for 
            xml path(''),type
        )
    FROM
        tInvoices i
    WHERE
        i.InvoiceID=100188
    for 
        XML PATH(''), ROOT('InvoiceInfo'), TYPE
    

    问题是: 有很多嵌套的select语句,如何简化这个查询?

0 个答案:

没有答案