概述
1.两个字段简单相似
CREATE FUNCTION DBO.FN_Resemble
(@Cloumna NVARCHAR(MAX),
@Cloumnb NVARCHAR(MAX)
)
RETURNS FLOAT
AS
BEGIN
DECLARE @num FLOAT,@len int
SET @Cloumna=ISNULL(@Cloumna,0)
SET @Cloumnb=ISNULL(@Cloumnb,0)
SET @len=1
SET @num=0
WHILE(LEN(@Cloumna)<>0 AND LEN(@CloumnB)<>0)
BEGIN
WHILE(@len<=LEN(@Cloumna))
BEGIN
DECLARE @a NVARCHAR(4)
SET @a=''
SET @a=SUBSTRING(@Cloumna,@len,1)
IF(CHARINDEX(@a,@CloumnB)>0)
BEGIN
SET @num=@num+1
END
SET @len=@len+1
END
SET @num=@num*1.0/LEN(@Cloumna)
BREAK
END
RETURN @num
END
----测试代码
SELECT DBO.FN_Resemble('ABDC321G','ABDC123G')
相似度 100%
2.两个字段顺序相似
CREATE FUNCTION DBO.FN_Resemble_order
(@Cloumna NVARCHAR(MAX),
@Cloumnb NVARCHAR(MAX)
)
RETURNS FLOAT
AS
BEGIN
DECLARE @num FLOAT,@len int
SET @Cloumna=ISNULL(@Cloumna,0)
SET @Cloumnb=ISNULL(@Cloumnb,0)
SET @len=1
SET @num=0
WHILE(LEN(@Cloumna)<>0 AND LEN(@CloumnB)<>0)
BEGIN
DECLARE @a NVARCHAR(4)
DECLARE @b NVARCHAR(4)
IF(LEN(@Cloumna)>=LEN(@CloumnB))
BEGIN
WHILE(@len<=LEN(@CloumnB))
BEGIN
SET @a=''
SET @a=SUBSTRING(@Cloumna,@len,1)
SET @b=''
SET @b=SUBSTRING(@CloumnB,@len,1)
IF(@a=@b)
BEGIN
SET @num=@num+1
END
ELSE
BEGIN
break
END
SET @len=@len+1
END
END
ELSE IF (LEN(@Cloumna)<LEN(@CloumnB))
BEGIN
WHILE(@len<=LEN(@Cloumna))
BEGIN
SET @a=''
SET @a=SUBSTRING(@Cloumna,@len,1)
SET @b=''
SET @b=SUBSTRING(@CloumnB,@len,1)
IF(@a=@b)
BEGIN
SET @num=@num+1
END
ELSE
BEGIN
break
END
SET @len=@len+1
END
END
SET @num=@num*1.0/LEN(@Cloumna)
BREAK
END
RETURN @num
END
----测试代码
SELECT DBO.FN_Resemble_order('ABDC456G','ABDC123G')
相似度 50%
3.两个字段一对一相似
CREATE FUNCTION DBO.FN_Resemble_onebyone
(@Cloumna NVARCHAR(MAX),
@Cloumnb NVARCHAR(MAX)
)
RETURNS FLOAT
AS
BEGIN
DECLARE @num FLOAT,@len int
SET @Cloumna=ISNULL(@Cloumna,0)
SET @Cloumnb=ISNULL(@Cloumnb,0)
SET @len=1
SET @num=0
WHILE(LEN(@Cloumna)<>0 AND LEN(@CloumnB)<>0)
BEGIN
DECLARE @a NVARCHAR(4)
DECLARE @b NVARCHAR(4)
IF(LEN(@Cloumna)>=LEN(@CloumnB))
BEGIN
WHILE(@len<=LEN(@CloumnB))
BEGIN
SET @a=''
SET @a=SUBSTRING(@Cloumna,@len,1)
SET @b=''
SET @b=SUBSTRING(@CloumnB,@len,1)
IF(@a=@b)
BEGIN
SET @num=@num+1
END
SET @len=@len+1
END
END
ELSE IF (LEN(@Cloumna)<LEN(@CloumnB))
BEGIN
WHILE(@len<=LEN(@Cloumna))
BEGIN
SET @a=''
SET @a=SUBSTRING(@Cloumna,@len,1)
SET @b=''
SET @b=SUBSTRING(@CloumnB,@len,1)
IF(@a=@b)
BEGIN
SET @num=@num+1
END
SET @len=@len+1
END
END
SET @num=@num*1.0/LEN(@Cloumna)
BREAK
END
RETURN @num
END
----测试代码
SELECT DBO.FN_Resemble_onebyone('ABDC456G','ABDC123G')
相似度 62.5%
测试结果:
最后
以上就是愤怒雪糕为你收集整理的SQL Server字符串相似度的全部内容,希望文章能够帮你解决SQL Server字符串相似度所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复