Wednesday 15 March 2017

String pattern between two columns and update something if one string is present in another column on same row:

create table StringMatch(ID int unique identity(1,1),String1 varchar(30),String2 varchar(30))

select * from StringMatch 
insert into StringMatch values('my word is my power','my power is my word') 
insert into StringMatch values('the way of mine','the mine of way') 
insert into StringMatch values('they are playing','are them playing') 
insert into StringMatch values('how are you today','today you are how') 
insert into StringMatch values('stop thinking','do your thoughs') 
alter table StringMatch add [Status] varchar(10)


select * from StringMatch

Now i want to update status if String1 is matching with String2 column .
Check below pasted code :

declare @s1 varchar(50)
declare @s2 varchar(50)
declare @c int
set @c=1
declare @count int
select @count=count(Distinct ID) from StringMatch
while(@c<=@count)
begin
select @s1=String1 from StringMatch where ID=@c
select @s2=String2 from StringMatch 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 case when exists(SELECT * FROM @t1 EXCEPT SELECT * FROM @t2) then 'are not' else 'are equal' end
update StringMatch set [status]=
case when exists(SELECT * FROM @t1 EXCEPT SELECT * FROM @t2) then 'are not' else 'are equal' end
where ID=@c
set @c=@c+1
delete from @t1
delete from @t2

end
Output Table :

No comments:

Post a Comment