Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 SQL Query For String Searching

Author  Topic 

lhsunshine
Starting Member

2 Posts

Posted - 2013-01-10 : 09:23:48


My case is
Input is "abdknmgbm".
BUT
The record in database that i want to query out is "abkdnmgmb"
The input and database record is quite similar.
String length is same, only some arrangement of character are not same.
In the above case, dk and kd ; bm and mb.
How i write query for this string searching?
Help and Thanks.

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2013-01-10 : 09:30:34
What do you want to match on?
chars 3 and 4 can be swapped and last 2 chars can be swapped.
4 chars can be mismatched but all letters need to be there.
Something else.

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

lhsunshine
Starting Member

2 Posts

Posted - 2013-01-10 : 17:51:57
Actually the swap char will not always are char 3 and 4 and last 2 chars.

For example it may also be like this :
Input: " abcdkazbmopdkubmgt "
The wanted result is : "abckdazmbopkdumbgt"
Input and wanted result length are same.
BUT the input string length is not always same.
Very hard to solve this. :( Tq.
Go to Top of Page

pctune
Starting Member

1 Post

Posted - 2013-01-10 : 18:58:29
Although the two strings have different lengths and the characters are in a different order, they still have the same count of each alpha character. In your examples " abcdkazbmopdkubmgt " and "abckdazmbopkdumbgt" both have 2xAs, 3xBs, 1xC, 2xDs, 1xG, 2xKs, 2xMs, 1xO, 1xP, 1xT, 1xU and 1xZ (and no other alpha).

Here's a function that will count each alpha in your string. Note, I'm a novice so there's probably a more efficient coding method...


CREATE FUNCTION [dbo].[FN_CharID]
(@StringtoAssess VARCHAR(100))
RETURNS char(26)
AS
BEGIN
declare @position as int
declare @ComparisonString as char(26) = 'abcdefghijklmnopqrstuvwxyz'
declare @CurrentLetter as char(1)
declare @cnt as int
declare @tmpresult as char(26)

set @position = 1
set @tmpresult = '00000000000000000000000000'

while @position < 27
begin
set @cnt = 0
set @CurrentLetter = substring(@ComparisonString,@position,1)

WHILE charindex(@CurrentLetter,@StringtoAssess) > 0
BEGIN
set @cnt = @cnt + 1
set @StringtoAssess = stuff(@StringtoAssess, charindex(@CurrentLetter, @StringtoAssess), 1, '')
END

set @tmpresult = stuff(@tmpresult, @position, 1, @cnt)
set @position = @position + 1
end

set @StringtoAssess = @tmpresult

RETURN @StringtoAssess
END



Running the function across your strings both return "23120010002020110001100001". I hope this is useful.
Go to Top of Page
   

- Advertisement -