T-SQL - 用char比较字符串char

时间:2013-09-02 14:37:07

标签: sql sql-server tsql

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

123456789    
212456789

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

感谢您提出的所有建议。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 fiddle demo

答案 2 :(得分:0)

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

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'

输出将如下所示:

Output