DROP PROC Valida_TPC_ClienteProc
GO
CREATE PROC Valida_TPC_ClienteProc
( @CUSTIDSS	UD_CODCLIENT,
  @CADENA_TPC	VARCHAR(255)
)
AS

BEGIN

	DECLARE @CADENA_TPC_2 AS VARCHAR(2000) 	
	DECLARE @CADENA AS VARCHAR(8000)

	SET 	@CADENA_TPC_2=''

	DECLARE @PRCLVLCUSTID UD_PRCLVLCUSTID 
	DECLARE COD_LISTA_PRECIOS CURSOR
	FOR SELECT  PRCLVLCUSTID FROM OP_CUSTOMER_PRCLVL WHERE CUSTIDSS=@CUSTIDSS
	OPEN COD_LISTA_PRECIOS
	FETCH NEXT FROM COD_LISTA_PRECIOS INTO @PRCLVLCUSTID

	WHILE @@FETCH_STATUS=0
        BEGIN    
		SET @CADENA_TPC_2= @CADENA_TPC_2 + "'" + LTRIM(RTRIM(@PRCLVLCUSTID)) + "',"
		FETCH NEXT FROM COD_LISTA_PRECIOS INTO @PRCLVLCUSTID
        
        END /* Termina while */

	CLOSE COD_LISTA_PRECIOS
	DEALLOCATE COD_LISTA_PRECIOS

	SET @CADENA_TPC=@CADENA_TPC_2 + @CADENA_TPC


	SET @CADENA ="SELECT '" + @CUSTIDSS + "' AS CLIENTE,OP_PRCLVLCUSTDET.SITEID,SITE.NAME,OP_PRCLVLCUSTDET.INVTIDSKU,IN_INVENTORY.DESCR,OP_PRCLVLCUSTDET.PRCLVLCUSTID,OP_PRCLVLCUST.DESCR AS DESCR2 " + 
		    "FROM OP_PRCLVLCUSTDET JOIN SITE ON OP_PRCLVLCUSTDET.SITEID=SITE.SITEID JOIN IN_INVENTORY ON " +
		    "OP_PRCLVLCUSTDET.INVTIDSKU=IN_INVENTORY.INVTIDSKU JOIN OP_PRCLVLCUST ON " +
		    "(OP_PRCLVLCUSTDET.PRCLVLCUSTID=OP_PRCLVLCUST.PRCLVLCUSTID AND OP_PRCLVLCUSTDET.SITEID=OP_PRCLVLCUST.SITEID) " +
		    "WHERE OP_PRCLVLCUSTDET.PRCLVLCUSTID IN (" + @CADENA_TPC + ") " +
		    "AND OP_PRCLVLCUSTDET.SITEID in  (SELECT SITEID  " + 
		    "FROM OP_PRCLVLCUSTDET " +
		    "WHERE PRCLVLCUSTID IN (" + @CADENA_TPC + ")  " +
		    "GROUP BY SITEID,INVTIDSKU HAVING COUNT(INVTIDSKU)>1 ) " +
		    "AND OP_PRCLVLCUSTDET.INVTIDSKU in  (SELECT INVTIDSKU  " + 
		    "FROM OP_PRCLVLCUSTDET " +
		    "WHERE PRCLVLCUSTID IN (" + @CADENA_TPC + ")  " +
		    "GROUP BY SITEID,INVTIDSKU HAVING COUNT(INVTIDSKU)>1 ) " 
	
	EXEC (@CADENA)
END 

