简体   繁体   中英

How to improve SQL query performance with a lot of inner selects?

How can I change this SQL query to improve performance?

I need to select name, address, phone, etc from Client, Supplier or Contact depending on EntityID ( EntidadeID )

  • EntidadeID = 1 gets data from Clients table
  • EntidadeID = 2 gets data from Supplier table
  • EntidadeID = 3 gets data from Contacts table

SQL code:

CREATE VIEW [dbo].[View_AtivTecnicasAtivTecnicasMatSer]
AS
    SELECT        
        a.Numero, a.UserFullName, a.Data, a.Hora, a.CodigoTerceiro, 
        a.Contacto, a.Tarefa, a.UserTarefaNome, a.AFaturar, a.Resolvido, 
        a.AgendadaData, a.AgendadaHora, a.AlertaData, a.AlertaHora, 
        a.Execucao, a.NotasInternas, a.ResolvidoData, a.ResolvidoHora, 
        a.ResolvidoUserFullName, a.NumeroAtendInicial, a.EmailCliente, 
        a.EmailUserTarefa, a.PDFTarefaAnexo, a.DataNotifInformativa, 
        a.DataNotifResolucao, a.TipoDoc, a.UserTarefaAlertado, 
        a.Origem, a.Anulado, a.TotalSIVA, a.TotalCIVA, a.Moeda, a.Cambio, 
        a.TaxaDesconto, a.TipoPreco, dbo.WR_Temas.Descricao, 
        CASE 
           WHEN EntidadeID = 1 THEN
                             (SELECT        Descricao
                               FROM            dbo.WR_ClientesEstab
                               WHERE        ID = a.ClienteEstabID) 
        END AS Estab, 
        CASE 
           WHEN a.EntidadeID = 1 THEN
                             (SELECT        Morada
                               FROM            dbo.WR_ClientesEstab
                               WHERE        ID = a.ClienteEstabID) 
           WHEN a.EntidadeID = 2 THEN
                             (SELECT        Morada
                               FROM            dbo.WR_Fornecedores
                               WHERE        Codigo = a.CodigoTerceiro) 
        END AS Morada, 
        CASE 
           WHEN a.EntidadeID = 1 THEN
                             (SELECT        Localidade
                               FROM            dbo.WR_ClientesEstab
                               WHERE        ID = a.ClienteEstabID) 
           WHEN a.EntidadeID = 2 THEN
                             (SELECT        Localidade
                               FROM            dbo.WR_Fornecedores
                               WHERE        Codigo = a.CodigoTerceiro) 
        END AS Localidade, 
        CASE 
           WHEN a.EntidadeID = 1 THEN
                             (SELECT        CodPostal
                               FROM            dbo.WR_ClientesEstab
                               WHERE        ID = a.ClienteEstabID) 
           WHEN a.EntidadeID = 2 THEN
                             (SELECT        CodPostal
                               FROM            dbo.WR_Fornecedores
                               WHERE        Codigo = a.CodigoTerceiro) 
        END AS CodPostal, CASE WHEN a.EntidadeID = 1 THEN
                             (SELECT        Telefone
                               FROM            dbo.WR_ClientesEstab
                               WHERE        ID = a.ClienteEstabID) END AS TelefoneEstab, CASE WHEN a.EntidadeID = 1 THEN
                             (SELECT        Telemovel
                               FROM            dbo.WR_ClientesEstab
                               WHERE        ID = a.ClienteEstabID) END AS TelemovelEstab, CASE WHEN a.EntidadeID = 1 THEN
                             (SELECT        Nome
                               FROM            dbo.WR_Clientes
                               WHERE        Codigo = a.CodigoTerceiro) WHEN a.EntidadeID = 2 THEN
                             (SELECT        Empresa
                               FROM            dbo.WR_Contactos
                               WHERE        ID = a.TerceiroID) WHEN a.EntidadeID = 3 THEN
                             (SELECT        Nome
                               FROM            dbo.WR_Fornecedores
                               WHERE        Codigo = a.CodigoTerceiro) END AS NomeTerceiro, CASE WHEN a.EntidadeID = 1 THEN
                             (SELECT        Telefone
                               FROM            dbo.WR_Clientes
                               WHERE        Codigo = a.CodigoTerceiro) WHEN a.EntidadeID = 2 THEN
                             (SELECT        Telefone
                               FROM            dbo.WR_Contactos
                               WHERE        ID = a.TerceiroID) WHEN a.EntidadeID = 3 THEN
                             (SELECT        Telefone
                               FROM            dbo.WR_Fornecedores
                               WHERE        Codigo = a.CodigoTerceiro) END AS Telefone, CASE WHEN a.EntidadeID = 1 THEN
                             (SELECT        Telemovel
                               FROM            dbo.WR_Clientes
                               WHERE        Codigo = a.CodigoTerceiro) WHEN a.EntidadeID = 2 THEN
                             (SELECT        Telemovel
                               FROM            dbo.WR_Contactos
                               WHERE        ID = a.TerceiroID) WHEN a.EntidadeID = 3 THEN
                             (SELECT        Telemovel
                               FROM            dbo.WR_Fornecedores
                               WHERE        Codigo = a.CodigoTerceiro) END AS Telemovel, CASE WHEN a.EntidadeID = 1 THEN
                             (SELECT        Contribuinte
                               FROM            dbo.WR_Clientes
                               WHERE        Codigo = a.CodigoTerceiro) WHEN a.EntidadeID = 2 THEN
                             (SELECT        Contribuinte
                               FROM            dbo.WR_Contactos
                               WHERE        ID = a.TerceiroID) WHEN a.EntidadeID = 3 THEN
                             (SELECT        Contribuinte
                               FROM            dbo.WR_Fornecedores
                               WHERE        Codigo = a.CodigoTerceiro) END AS Contribuinte, m.Linha, m.ArtigoCod, m.ArtigoDesc, m.Qtd, m.UN, m.ValorUnitario, m.DescontoPercentual, m.DescontoValor, m.Armazem, m.NumSerie, m.AnoERP, m.SerieERP, 
                         m.TipoDocERP, m.NumDocERP, m.DataExportadoERP, m.UserExportouERP, m.TaxaIva, m.TotalDescontos AS TotalDescontosLinha, m.TotalGeral AS TotalGeralLinhas, m.Ordenacao, m.ExportadaERP, m.DocERP, 
                         m.DescontoPercentual2, m.DescontoPercentual3, a.TotalMercadoria, a.TotalLiquido, a.TotalIVA, a.TotalGeral, a.TotalGeralEuros, a.TotalDescontosLinhas, a.TotalDescontosGlobal, a.TotalDescontos, a.EntidadeID, 
                         m.DescontoPercentual4
FROM            dbo.WR_AtivTecnicas AS a INNER JOIN
                         dbo.WR_Temas ON a.TemaID = dbo.WR_Temas.ID INNER JOIN
                         dbo.WR_AtivTecnicasMatSer AS m ON a.Numero = m.NumeroAtiv
GO

I tried to make only 3 Select Cases with all the fields, but without success.

you need to do something like this: as @jarlh mentioned, you can replace your selects in cases with left join,also since you have these rules in place:

EntidadeID = 1 gets data from Clients table
EntidadeID = 2 gets data from Supplier table
EntidadeID = 3 gets data from Contacts table

you can include them in your join criteria, so you can remove cases completely as example below:

SELECT
    *
     -- instead of case for example for Telemovel
    , COALESCE( ct.Telemovel, st.Telemovel, cts.Telemovel)
    -- replace all the case statements following above logic
FROM
    dbo.WR_AtivTecnicas                  AS A
    INNER JOIN dbo.WR_Temas
        ON A.TemaID = dbo.WR_Temas.ID
    INNER JOIN dbo.WR_AtivTecnicasMatSer AS m
        ON A.Numero = m.NumeroAtiv
    LEFT OUTER JOIN ClientsTable ct
      ON  ct.Codigo = a.CodigoTerceiro -- replace with proper condition
      AND EntidadeID = 1
    LEFT OUTER JOIN SupplierTable st
      ON  st.id = A.id  -- replace with proper condition
      AND EntidadeID = 2
    LEFT OUTER JOIN ContactsTable cts
      ON  cts.ID = a.TerceiroID  -- replace with proper condition 
      AND EntidadeID = 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM