Monday, February 8, 2016

Find all text occurrence in a given text TSQL


declare @prodId int
declare @mrPosition int
declare getproduct cursor for select mrid,mrgeneration from [dbo].[master28_descriptions_Final_ind]
    where mrDESCRIPTION like '%IMG%' order by mrid

declare @imgString varchar(200)
declare @endPos int
declare @desc nvarchar(max)
declare @position int
declare @outputDesc varchar(max)

    open getproduct
fetch next from getproduct into @prodId,@mrPosition
--print @prodId
while @@FETCH_STATUS = 0
begin

            -- get product Id
    select @desc= mrDESCRIPTION from [dbo].[master28_descriptions_Final_ind]   where mrid = @prodId and mrgeneration= @mrPosition
   --print @desc
  --gets the index of the first instance of <img
    select @position = CHARINDEX('<img', @desc)



    while @position < len(@desc)
    begin
        --this assumes that we are not at the end of the description field
        if (SUBSTRING(@desc, @position, 4) = '<img')
        begin

--print @position
--print 'im in the loooopp' + SUBSTRING(@desc, @position, 500)
     
        select @endPos = charIndex('/>', substring(@desc, @position, 500))
                select @imgString = substring(@desc, @position, @endPos)

    --insert into dbo.ProductImage(ProductId, ImageUrl, DisplayName, IsPrimaryImage)
        --            select @prodId, @imgString, DisplayName, 0
        --            from Product where Id = @prodId
        --                         and not exists (select ImageUrl from ProductImage where ProductId = @prodId and ImageUrl = @imgString)

--print @endPos
print REPLACE( @imgString,'__d','.')

-- TODO
-- insert into tbl_output (mrid,image_path) values ( @prodId,@imgString)
             
select @outputDesc = REPLACE(@desc, @imgString, 'QQQQQQQQQQ')

--print REPLACE(@desc, @imgString, 'QQQQQQQQQQ')

                --select @outputDesc = Replace(@outputDesc, '</img>', '')

                select @position = @endPos

--print @position
        end
        else
        begin
            -- if we have reached here, there are no more instances of <img
            -- set @position to end of description field to prevent continuous looping
            select @position = len(@desc)
        end
    end

    select @outputDesc

    update [master28_descriptions_Final_ind]
    set mrDESCRIPTION = @outputDesc
    where mrId = @prodId and mrgeneration= @mrPosition

    --select Description from Product where Id = @prodId

fetch next from getproduct into @prodId,@mrPosition
end

close getproduct
deallocate getproduct

No comments:

Post a Comment