How to compare if two strings contain the same words in T-SQL for SQL Server 2008?

前端 未结 8 1144
长情又很酷
长情又很酷 2021-01-18 05:22

When I compare two strings in SQL Server, there are couple of simple ways with = or LIKE.

I want to redefine equality as:

If

8条回答
  •  醉话见心
    2021-01-18 05:55

    declare @s1 varchar(50) = 'my word'
    declare @s2 varchar(50) = 'word my'
    
    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 case when exists(SELECT * FROM @t1 EXCEPT SELECT * FROM @t2) then 'are not' else 'are equal' end
    

提交回复
热议问题