IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'[dbo].[CPJ_Cliente_Xcampo]') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE [dbo].[CPJ_Cliente_Xcampo] 
END
GO

CREATE PROCEDURE [dbo].[CPJ_Cliente_Xcampo] @pJson VARCHAR(8000),   @pId_Cliente	INT
AS
SET NOCOUNT ON

/*Variables recibidas por parßmetro a traves del JSON*/
DECLARE @pId_Campo				INT

DECLARE @pValida				INT
DECLARE @pValor					VARCHAR(8000)
DECLARE @TipoDato				VARCHAR(100)

/*############################# Recorro Los Campos del Json ############################################*/
DECLARE curCliente_Xcampo CURSOR FOR
SELECT Id_Campo FROM xCampos WHERE Flag_Clientes=1

OPEN curCliente_Xcampo
FETCH NEXT FROM curCliente_Xcampo INTO @pId_Campo
WHILE @@FETCH_STATUS = 0
BEGIN


SET @pValor	= ISNULL(CONVERT(VARCHAR(8000), dbo.CF_JSON_VALUE(@pJson,@pId_Campo)), '')

	SELECT 
	@TipoDato = TipoDato 
	FROM xCampos
	WHERE
	Id_Campo = @pId_Campo
	
	IF(@pValor ='on')
	BEGIN
		SET @pValor  =1
	END

--select * from Clientes_xcampos

IF(@TipoDato = 'STRING')
BEGIN
	EXEC CP_xCampos_Guardar  'CLIENTE'/*@pTabla*/, @pId_Cliente/*@pId*/, @pId_Campo/*@pId_Campo*/,	@pValor/*String*/,	NULL/*Integer*/,	NULL/*DATETIME*/,	NULL/*DECIMAL(20,4)*/,	NULL/*TEXT-MEMO*/
END

IF(@TipoDato = 'INTEGER')
BEGIN
	EXEC CP_xCampos_Guardar  'CLIENTE'/*@pTabla*/, @pId_Cliente/*@pId*/, @pId_Campo/*@pId_Campo*/,	NULL/*String*/,	@pValor/*Integer*/,	NULL/*DATETIME*/,	NULL/*DECIMAL(20,4)*/,	NULL/*TEXT-MEMO*/
END


IF(@TipoDato = 'DATE')
BEGIN
	EXEC CP_xCampos_Guardar  'CLIENTE'/*@pTabla*/, @pId_Cliente/*@pId*/, @pId_Campo/*@pId_Campo*/,	NULL/*String*/,	NULL/*Integer*/,	@pValor/*DATETIME*/,	NULL/*DECIMAL(20,4)*/,	NULL/*TEXT-MEMO*/
END


IF(@TipoDato = 'DECIMAL')
BEGIN
	EXEC CP_xCampos_Guardar  'CLIENTE'/*@pTabla*/, @pId_Cliente/*@pId*/, @pId_Campo/*@pId_Campo*/,	NULL/*String*/,	NULL/*Integer*/,	NULL/*DATETIME*/,	@pValor/*DECIMAL(20,4)*/,	NULL/*TEXT-MEMO*/
END


IF(@TipoDato = 'MEMO')
BEGIN
	EXEC CP_xCampos_Guardar  'CLIENTE'/*@pTabla*/, @pId_Cliente/*@pId*/, @pId_Campo/*@pId_Campo*/,	NULL/*String*/,	NULL/*Integer*/,	NULL/*DATETIME*/,	NULL/*DECIMAL(20,4)*/,	@pValor/*TEXT-MEMO*/
END


FETCH NEXT FROM curCliente_Xcampo INTO @pId_Campo
END
CLOSE curCliente_Xcampo
DEALLOCATE curCliente_Xcampo

RETURN 0
