• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 443
  • Last Modified:

comparing two strings

Hello All:

I am working on a stored procedure and I have 2 strings that need to be compared and if the 2 of them contain 6 characters which are the same at any position of either one, it should return 'Equal' otherwise 'Not Equal'
e.g.
0010723543289035 should be equal to 137107235ABC001 since the 2 strings contain '107235'
5272235 should not be equal to 123891113

Can please anyone help me?  Any ideas would be appreciated.

Thank you,
0
gloriagalvez
Asked:
gloriagalvez
1 Solution
 
HuaMinChenBusiness AnalystCommented:
The way is similar to this

declare @cnt int,
@end_pos int,
@str1 varchar(50),
@str2 varchar(50),
@found bit

set @found=0
set @str1='0010723543289035'
set @str2='137107235ABC001'
set @cnt=1
set @end_pos=len(@str1)-5

while @cnt<=@end_pos
begin
      if charindex(substring(@str1,@cnt,6),@str2)>0
            set @found=1
            
end

if @found=1
begin
      ...
      /* this means you have found one substring of 6 characters which appears in both string */
end

Many Thanks & Best Regards,
HuaMin
0
 
Habib PourfardCommented:
You can try the following function:
CREATE FUNCTION IsEqual
    (
     @string1 VARCHAR(256)
    ,@string2 VARCHAR(256)
    )
RETURNS BIT
AS BEGIN
	
    DECLARE @stringToCompare CHAR(8)
    DECLARE @isEqual BIT = 0
    DECLARE @i TINYINT
    
    SET @i = 1

    WHILE @i <= LEN(@string1) - 5
        BEGIN
            SET @stringToCompare = '%' + SUBSTRING(@string1, @i, 6) + '%'
            SET @i = @i + 1

            IF PATINDEX(@stringToCompare, @string2) > 0 
                BEGIN
                    SET @isEqual = 1
                    BREAK
                END
        END
    
    RETURN @isEqual

   END

Open in new window

when two strings are equal then it returns 1 otherwise 0:
SELECT dbo.IsEqual('0010723543289035', '137107235ABC001')

Open in new window

0
 
gloriagalvezAuthor Commented:
Thank you very much for your quick response.  This function worked perfect for what I was trying to accomplish. cheers!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now