简体   繁体   English

T-SQL - 按字符比较字符串

[英]T-SQL - compare strings char by char

I need to compare two strings character by character using T-SQL.我需要使用 T-SQL 逐个比较两个字符串。 Let's assume i have twor strings like these:让我们假设我有两个这样的字符串:

123456789    
212456789

Every time the character DO NOT match, I would like to increase the variable @Diff +=1.每次字符不匹配时,我想增加变量@Diff +=1。 In this case the first three characters differ.在这种情况下,前三个字符不同。 So the @Diff = 3 (0 would be default value).所以@Diff = 3(0 是默认值)。

Thank you for all suggestions.谢谢你的所有建议。

This code should count the differences in input strings and save this number to counter variable and display the result:此代码应计算输入字符串中的差异并将此数字保存到计数器变量并显示结果:

declare @var1 nvarchar(MAX)
declare @var2 nvarchar(MAX)
declare @i int
declare @counter int

set @var1 = '123456789'
set @var2 = '212456789'
set @i = LEN(@var1)
set @counter = 0

while @i > 0
begin
   if SUBSTRING(@var1, @i, 1) <> SUBSTRING(@var2, @i, 1)
   begin 
   set @counter = @counter + 1
   end
   set @i = @i - 1
end

select @counter as Value

for columns in table you don't want to use row by row approach, try this one:对于您不想使用逐行方法的表中的列,请尝试以下方法:

with cte(n) as (
    select 1
    union all
    select n + 1 from cte where n < 9
)
select
    t.s1, t.s2,
    sum(
      case
      when substring(t.s1, c.n, 1) <> substring(t.s2, c.n, 1) then 1
      else 0
      end
    ) as diff
from test as t
    cross join cte as c
group by t.s1, t.s2

=>sql fiddle demo => sql 小提琴演示

The below query compares, shows the different characters and bring you the count of differences下面的查询比较,显示不同的字符并为您带来差异的计数

Declare @char1 nvarchar(1), @char2 nvarchar(1), @i int = 1, @max int
Declare @string1 nvarchar(max) = '123456789'
        , @string2 nvarchar(max) = '212456789'
Declare @diff_table table (pos int , string1 nvarchar(50) , string2 nvarchar(50), Status nvarchar(50))
Set @max = (select case when len(@String1+'x')-1 > len(@string2+'x')-1 then len(@String1+'x')-1 else len(@string2+'x')-1 end)
while @i < @max +1

        BEGIN
        Select @char1 = SUBSTRING(@string1,@i,1), @char2 = SUBSTRING(@string2,@i,1)
        INSERT INTO @diff_table values 
        (
            @i,
            case when UNICODE(@char1) is null then '' else concat(@char1,' - (',UNICODE(@char1),')') end,
            case when UNICODE(@char2) is null then '' else concat(@char2,' - (',UNICODE(@char2),')') end,
            case when ISNULL(UNICODE(@char1),0) <> isnull(UNICODE(@char2),0) then 'CHECK' else 'OK' END
        )
        set @i+=1
        END

Select * from @diff_table
Declare @diff int = (Select count(*) from @diff_table where Status = 'Check')
Select @diff 'Difference'

The output will be like this:输出将是这样的:

输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM