insert into #pricePhotos ( idPhoto , idPricing , priority ) select _photo.id , _pricing.id , case when ( _price_category_priority.priority is not null ) then _price_category_priority.priority else 9999 end as priority from _photo inner join _price_category on _price_category.id = @idCategory left join _price_category_priority on _price_category_priority.idPhoto = _photo.id and _price_category_priority.idPrice = _price_category.id inner join _pricing on _pricing.idPhoto = _photo.id or _photo.id in ( select idPhoto from __batchPhotos where idBatch = _pricing.idBatch and idBatch in ( select id from _photo_batch where id = _pricing.idBatch and is_active = 1 and disable_photos <> 1 ) ) inner join _artist on _artist.id = _photo.idArtist where _artist.is_active = 1 and ( ( _pricing.price >= @priceFrom and ( @priceTo is null or _pricing.price <= @priceTo ) ) or ( _pricing.resin_price >= @priceFrom and ( @priceTo is null or _pricing.resin_price <= @priceTo ) ) ) order by _price_category_priority.priority , _photo.title