如何在sql中的两个字符串之间获得精确的字符差异

时间:2016-11-09 08:37:53

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

我有两个字符串,我希望在SQL中

中获得两个字符串内容的区别

例如,

Declare @String1 as varchar(100)='Please check requirement and let me know your feedback.';

Declare @String2 as varchar(100)='Please checkout requirement & let me know your feedback';

结果应该类似于字符串中不常见的单词。

例如checkout,&

3 个答案:

答案 0 :(得分:1)

您可以使用REPLACE,如下所示:

SELECT REPLACE(CASE WHEN LEN(@String1) < LEN(@String2) THEN @String2 ELSE @String1 END, 
               CASE WHEN LEN(@String1) < LEN(@String2) THEN @String1 ELSE @String2 END, '')

结果:.com

答案 1 :(得分:1)

此代码首先将字符串拆分为单个单词,然后检查其他字符串中不存在的单词

Declare @String1 as varchar(100)='Please check requirement and let me know your feedback.';
Declare @String2 as varchar(100)='Please checkout requirement & let me know your feedback';

WITH s1_Splitted AS
(
    SELECT wrd.value('.','nvarchar(max)') AS Word
    FROM
    (SELECT (
            SELECT CAST('<x>' + REPLACE((SELECT @String1 AS [*] FOR XML PATH('')),' ','</x><x>') + '</x>' AS XML)
            ) AS Casted
    ) AS derived
    CROSS APPLY derived.Casted.nodes('/x') AS A(wrd)
)
,s2_Splitted AS
(
    SELECT wrd.value('.','nvarchar(max)') AS Word
    FROM
    (SELECT (
            SELECT CAST('<x>' + REPLACE((SELECT @String2 AS [*] FOR XML PATH('')),' ','</x><x>') + '</x>' AS XML)
            ) AS Casted
    ) AS derived
    CROSS APPLY derived.Casted.nodes('/x') AS A(wrd)
)
SELECT 'only in s1',s1.Word
FROM s1_Splitted AS s1
WHERE NOT EXISTS(SELECT 1 FROM s2_Splitted AS s2 WHERE s2.Word=s1.Word)
UNION ALL
SELECT 'only in s2',s2.Word
FROM s2_Splitted AS s2
WHERE NOT EXISTS(SELECT 1 FROM s1_Splitted AS s1 WHERE s1.Word=s2.Word)

结果(关注 反馈后的. 被视为两个不同的词......)

only in s1  and
only in s1  check
only in s1  feedback.
only in s2  &
only in s2  checkout
only in s2  feedback

答案 2 :(得分:0)

假设@ String1是@ String2的前缀

select right (@String2,len(@String2)-len(@String1))
;