call spQuery_Lista_Habitacion_Reserva(1, 1, '2012-08-30','2012-08-31', NULL, 1);

DROP PROCEDURE IF EXISTS spQuery_Lista_Habitacion_Reserva;
CREATE PROCEDURE spQuery_Lista_Habitacion_Reserva(
  varEmpresa  int,
  varSegmento int,
  varFechaIni datetime,
  varFechaFin datetime,
  varCodigo   int,
  varUsuario  int
  )
BEGIN
  DECLARE varCadCod text default '';
  if varCodigo is not null then
    set varCadCod = CONCAT(" and H.id_habitacion = ", varCodigo, " ");
  end if;
  
  set @sql = CONCAT("select H.id_habitacion as CHAB, H.numero as NUM, ",
                    "CAST(CONCAT(H.id_tipo_habitacion, ' - ', T.nombre) AS CHAR) AS TIPO, ",
                    "CAST(CONCAT(H.id_piso, ' - ', P.nombre) AS CHAR) as PISO, ",
                    "CONCAT(CASE WHEN H.flag_terma='S' THEN 'TERMA / ' ELSE '' END, ",
                    "      CASE WHEN H.flag_tv='S' THEN 'TV / ' ELSE '' END, ",
                    "      CASE WHEN H.flag_aire='S' THEN 'AIRE / ' ELSE '' END, ",
                    "      CASE WHEN H.flag_radio='S' THEN 'RADIO / ' ELSE '' END, ",
                    "      CASE WHEN H.flag_jacuzzi='S' THEN 'JACUZZI / ' ELSE '' END, ",
                    "      CASE WHEN H.flag_friobar='S' THEN 'FRIOBAR' ELSE '' END) AS CARACTERISTICA, ",
                    "(select precio_24 from _sh_tarifario TH  ",
                    "where TH.id_segmento = ", varSegmento, " ",
                    "and TH.id_empresa   = H.id_empresa ",
                    "and TH.id_habitacion = H.id_habitacion  ",
                    ") as COSTO ",
                    "from _sh_habitacion H ",
                    "inner join _sh_tipo_habitacion T ON H.id_tipo_habitacion = T.id_tipo_habitacion ",
                    "inner join _sh_piso P ON H.id_piso = P.id_piso ",
                    "where H._estado  ='A' ",
                    "and H.id_empresa in (select distinct id_empresa from _sys_usuario_almacen where id_usuario=", varUsuario, ") ",
                    "and H.id_empresa = ", varEmpresa, " ",
                    varCadCod,
                    "and H.id_habitacion not in (select DISTINCT id_habitacion  ",
                    "                            from _sh_reservacion_habitacion RH ",
                    "                            inner join _sh_reservacion R ON RH.id_reservacion = R.id_reservacion ",
                    "                            where R.id_empresa = ", varEmpresa, " ",
                    "                            and R._estado = 'A' ",
                    "                            and R.estado  = 'AC' ",
                    "                            and (('", varFechaIni, "' between R.fecha_ingreso and R.fecha_salida) ",
                    "                            OR   ('", varFechaFin, "' between R.fecha_ingreso and R.fecha_salida)) ",
                    "    