简体   繁体   中英

Case expression with subquery error: coud not be bound

I'm trying to use a Case Expression when a I have a subquery, and SQL keeps me returning

The multi-part identifier "local1.DescricaoLotacao" could not be bound.

    CASE WHEN (SELECT local1.[DescricaoLotacao] FROM sgp.dbo.[LOTACAO] AS [local1]
                 WHERE local1.IdLotacao = (SELECT TOP 1 [uai].[IdLotacao] FROM sgp.dbo.[UnidadeAdministrativaInterna] AS [uai]
                                            WHERE uai.[CodigoPessoal] = p.[CodigoPessoal] AND uai.[DataFinal] IS NULL ORDER BY [uai].[DataInicial] DESC)
                                           ) IS NOT NULL
        THEN local1.[DescricaoLotacao]
        ELSE ''
    END,

I know it's why my local.descricaoLotacao is out of my parentheses. But I don't know how to fix it. I thing there is another way to do this kind of select.

If you are sure that the query will return only 1 row then instead of CASE use COALESCE() :

COALESCE(
  (
    SELECT local1.[DescricaoLotacao] FROM sgp.dbo.[LOTACAO] AS [local1]
    WHERE local1.IdLotacao = (
      SELECT TOP 1 [uai].[IdLotacao] 
      FROM sgp.dbo.[UnidadeAdministrativaInterna] AS [uai]
      WHERE uai.[CodigoPessoal] = p.[CodigoPessoal] AND uai.[DataFinal] IS NULL 
      ORDER BY [uai].[DataInicial] DESC
  ), 
  ''
)

I suggest using EXISTS This is assuming the local1.[DescricaoLotacao] portion exists outside of the CASE WHEN section.

CASE WHEN EXISTS (SELECT local1.[DescricaoLotacao] FROM sgp.dbo.[LOTACAO] AS [local1]
                 WHERE local1.IdLotacao = (SELECT TOP 1 [uai].[IdLotacao] FROM sgp.dbo.[UnidadeAdministrativaInterna] AS [uai]
                                            WHERE uai.[CodigoPessoal] = p.[CodigoPessoal] AND uai.[DataFinal] IS NULL ORDER BY [uai].[DataInicial] DESC)
                                           ) 
        THEN local1.[DescricaoLotacao]
        ELSE ''
    END

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