在此Question中使用bitwise XOR
PHP
中的{{1}}找到第一个不同的两个字符串的Charindex。如何在SQL查询中实现此解决方案,还是有更好的解决方案来解决这个问题?
答案 0 :(得分:1)
更新:这是Sql XOR 解决方案:
仅适用于len字母大于8的字符串
DECLARE @A VARCHAR(50)
DECLARE @B VARCHAR(50)
DECLARE @Pos INT
set @A='ABrC12@4'
set @B='ABrC1234'
SET @Pos=( select
case
when len(@A)<>LEN(@B) then -1
when @A=@B then 0
ELSE 1+PATINDEX('%[1-9]%',
CONVERT(varchar(max),cast(cast(CAST(@A AS varbinary) as BIGINT) ^
cast(CAST(@B AS varbinary) as BIGINT)
as varbinary ),2))/2
end)
Print @Pos
你可以使用一个不错的结果:
create FUNCTION [dbo].[fnFirstPosDif]
(
@Word as Nvarchar(70),
@Word2 as Nvarchar(70)
)
RETURNS INT
AS
BEGIN
declare @Strings2 TABLE
(
FirstPosDif INT
)
declare @FirstPosDif as int
;with C as
(
select @Word as Word,@Word2 as Word2 ,0 as Iteration
union all
select cast(substring(@Word,Iteration+1,1)as Nvarchar(70)) as Word,cast(substring(@Word2,Iteration+1,1)as Nvarchar(70)) as Word2,Iteration + 1 from C
WHERE Iteration < len(@Word) and cast(substring(@Word,Iteration+1,1)as Nvarchar(70))=cast(substring(@Word2,Iteration+1,1)as Nvarchar(70))
)
insert into @Strings2(FirstPosDif) select MAX(Iteration) as FirstPosDif from C
set @FirstPosDif=(select top 1 FirstPosDif from @Strings2)
return @FirstPosDif
END
答案 1 :(得分:0)
我不相信您为SQL Server引用的问题中显示的任何方法都等效。
唯一的方法似乎是手动遍历字符串(根据PHP建议),但在SQL中,由于您无法解决CHAR
类型,就好像它们是数组一样,因此更加费力:
DECLARE @A NVARCHAR(50)
DECLARE @B NVARCHAR(50)
DECLARE @I INT
DECLARE @Pos INT
SET @A = 'Hello World!'
SET @B = 'Hella World!'
SET @I = 0
SET @Pos = 0
-- Loop through each character
WHILE (@I < LEN(@A) AND @I < LEN(@B) AND @Pos = 0)
BEGIN
-- See if the characters at this position differ
IF (SUBSTRING(@A, @I, 1) != SUBSTRING(@B, @I, 1))
SET @Pos = @I
SET @I = @I + 1
END
IF (@Pos > 0)
PRINT 'Difference at position ' + CAST(@Pos AS VARCHAR) + ' A:' + SUBSTRING(@A, @Pos, 1) + ' B:' + SUBSTRING(@B, @Pos, 1)
ELSE
PRINT 'Strings are the same'
按照上面的说法运行它将产生以下输出:
Difference at position 5 A:o B:a
请注意,如果您经常使用它,可以将其放入UDF中,而且我还没有包含对NULL
值的检查。