簡體   English   中英

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

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

我需要使用 T-SQL 逐個比較兩個字符串。 讓我們假設我有兩個這樣的字符串:

123456789    
212456789

每次字符不匹配時,我想增加變量@Diff +=1。 在這種情況下,前三個字符不同。 所以@Diff = 3(0 是默認值)。

謝謝你的所有建議。

此代碼應計算輸入字符串中的差異並將此數字保存到計數器變量並顯示結果:

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

對於您不想使用逐行方法的表中的列,請嘗試以下方法:

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

下面的查詢比較,顯示不同的字符並為您帶來差異的計數

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'

輸出將是這樣的:

輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM