3

我需要使用 T-SQL 逐个字符地比较两个字符串。假设我有两个这样的字符串:

123456789    
212456789

每次字符不匹配时,我想增加变量@Diff +=1。在这种情况下,前三个字符不同。所以@Diff = 3(0 是默认值)。

感谢您的所有建议。

4

3 回答 3

4

此代码应计算输入字符串中的差异并将此数字保存到计数器变量并显示结果:

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
于 2013-09-02T14:45:16.573 回答
4

对于您不想使用逐行方法的表中的列,请尝试以下方法:

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 小提琴演示

于 2013-09-02T14:50:07.453 回答
1

下面的查询比较,显示不同的字符,并为您带来差异计数

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'

输出将是这样的:

输出

于 2020-06-03T00:31:48.497 回答