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

T-SQL - compare strings char by char(T-SQL - 按字符比较字符串)
本文介绍了T-SQL - 按字符比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I need to compare two strings character by character using T-SQL. Let's assume i have twor strings like these:

123456789    
212456789

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

Every time the character DO NOT match, I would like to increase the variable @Diff +=1. In this case the first three characters differ. So the @Diff = 3 (0 would be default 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 小提琴演示

这篇关于T-SQL - 按字符比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Creating table with T-SQL - can#39;t see created tables in Object explorer(使用 T-SQL 创建表 - 在对象资源管理器中看不到创建的表)
How to check if VARCHAR strings are (not) hexadecimal?(如何检查 VARCHAR 字符串是否为(非)十六进制?)
Arithmetic overflow error converting IDENTITY to data type int(将 IDENTITY 转换为数据类型 int 的算术溢出错误)
Where clause if there are multiple of the same ID(如果有多个相同的 ID,Where 子句)
Azure SQL: Invalid Object Name using Powershell#39;s quot;Invoke-sqlcmdquot; on Adventureworks(Azure SQL:使用 Powershell 的“Invoke-sqlcmd的无效对象名称在 Adventureworks 上)
How to Convert Table Data into xml format using sql with multiple sub nodes(如何使用具有多个子节点的sql将表数据转换为xml格式)