call spQuery_Tipo_Forma_Pago('', '', null, null);

DROP PROCEDURE IF EXISTS spQuery_Tipo_Forma_Pago;
CREATE PROCEDURE spQuery_Tipo_Forma_Pago(
  varCodigo int,
	varNombre varchar(60),
  varField  varchar(60),
  varOrder  varchar(5)
)
BEGIN
  DECLARE varCadCod, varCadNom  text default '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  if varCodigo <> '' and varCodigo is not null then
    set varCadCod = CONCAT(" and id_forma_pago = ", varCodigo, " ");
  end if;
	if varNombre <> '' and varNombre is not null then
    set varCadNom = CONCAT(" and nombre like '%", varNombre,"%' ");
  end if;
  
   -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'M._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'M._date_update'
                        ELSE varField
                   END;
    SET varCadOrd = CONCAT("ORDER BY ", varField, " ");
    IF varOrder is not null and varOrder <> '' THEN
      SET varCadOrd = CONCAT(varCadOrd, varOrder, " ");      
    END IF;
  END IF;
  
  SET @sql = CONCAT("select id_forma_pago as CTIP, C.nombre as DESCRIPCION, ABREV, ",
                    "date_format(C._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(C._date_update,'%d/%m/%Y %h:%i:%s %p') AS FECHA_MODIFI, ",
                    "UPPER(UN.usuario) as USER_CREADO, ",
                    "UPPER(UU.usuario) as USER_MODIFI ",
                    "from _sv_forma_pago C ",
                    "left join _sys_usuario UN ON C._user_create = UN.id_usuario ",
                    "left join _sys_usuario UU ON C._user_update = UU.id_usuario ",
                    "where C._estado = 'A' ", 
                    varCadCod, varCadNom, varCadOrd);
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1; 
END;