IF EXISTS( SELECT * FROM sys.views
			WHERE object_id = OBJECT_ID(N'[dbo].[V_EST_PROD_EAN]'))
    BEGIN
        DROP VIEW [dbo].[V_EST_PROD_EAN];
    END;
GO

SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO

CREATE VIEW [dbo].[V_EST_PROD_EAN]
AS
     SELECT
            CD_EMP
          , CD_PROD
          , DS_PROD
          , [1] AS EAN01
          , [2] AS EAN02
          , [3] AS EAN03
          , [4] AS EAN04
          , [5] AS EAN05
          , [6] AS EAN06
          , [7] AS EAN07
          , [8] AS EAN08
          , [9] AS EAN09
          , [10] AS EAN10
     FROM
(
    SELECT
           P.CD_EMP
         , P.CD_PROD
         , P.DS_PROD
         , A.CD_BARRA
         , COUNT(*) ORDEM
    FROM
         EST_PROD P
       , EST_PROD_CD_BARRA A
       , EST_PROD_CD_BARRA B
    WHERE P.CD_PROD = A.CD_PROD
          AND P.CD_EMP = A.CD_EMP
          AND A.CD_PROD = B.CD_PROD
          AND A.CD_BARRA <= B.CD_BARRA
	  AND B.FLAG_PRE_VENCIDOS = 0
          --AND A.EAN_VALIDO = 1
          --AND B.EAN_VALIDO = 1
    GROUP BY
             P.CD_EMP
           , P.CD_PROD
           , P.DS_PROD
           , A.CD_BARRA
    HAVING COUNT(*) <= 10
) tab PIVOT(MIN(tab.CD_BARRA) FOR tab.ORDEM IN(
                                               [1]
                                             , [2]
                                             , [3]
                                             , [4]
                                             , [5]
                                             , [6]
                                             , [7]
                                             , [8]
                                             , [9]
                                             , [10])) AS pvt;
GO