Wednesday 15 March 2017

String pattern between two columns and update third column with matched and unmatched values:

create table #temp_eg(Col1 varchar(50),Col2 varchar(50))
alter table #temp_eg add ID int unique identity(1,1)
insert into #temp_eg values('60t,50o,40c,','60t,50o,40c,76yu,gh89,')
insert into #temp_eg values('60t,50o,100c,','60t,50o,40c,100c,gh89,')
insert into #temp_eg values('100rs,200rs,300rs,','300rs,200rs,400rs,500rs,600rs,',null)
select * from #temp_eg

alter table #temp_eg add [Results] varchar(50)

Execute the below code and see the results.
declare @s1 varchar(50)
declare @s2 varchar(50)
declare @c int
set @c=1
declare @count int
select @count=count(Distinct ID) from #temp_eg
while(@c<=@count)
begin
select @s1=col1 from #temp_eg where ID=@c
select @s2=Col2 from #temp_eg where ID=@c
declare @t1 table (word varchar(50))
while len(@s1)>0
begin
    if (CHARINDEX(',', @s1)>0)
    begin     
 insert into @t1 values(ltrim(rtrim(LEFT(@s1, charindex(',', @s1)))))       
 set @s1 = LTRIM(rtrim(right(@s1, len(@s1)-charindex(',', @s1))))
    end
    else
    begin
        insert into @t1 values (@s1)
        set @s1=''    
    end    
end
declare @t2 table (word varchar(50))
while len(@s2)>0
begin
    if (CHARINDEX(',', @s2)>0)
    begin     
  insert into @t2 values(ltrim(rtrim(LEFT(@s2, charindex(',', @s2)))))       
  set @s2 = LTRIM(rtrim(right(@s2, len(@s2)-charindex(',', @s2))))
    end
    else
    begin
        insert into @t2 values (@s2)
        set @s2=''    
    end    
end
--SELECT * FROM @t1
--SELECT * FROM @t2
select word into #temp from @t2 where  word not in (SELECT word FROM @t1)
union all SELECT * FROM @t1
--select * from #temp
declare @output as varchar(50)
select @output=STUFF((SELECT ' ' + word
            FROM #temp
            FOR XML PATH('')) ,1,0,'')
   --select @output
update #temp_eg set [Results]=@output where ID=@c
set @c=@c+1
delete from @t1
delete from @t2
drop table #temp
end

Output:

or we can use this Function also:


No comments:

Post a Comment