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 2000 Forums
 Transact-SQL (2000)
 Complex Search query

Author  Topic 

adlo
Posting Yak Master

108 Posts

Posted - 2004-11-02 : 11:25:11
I have a search field that gives me a value that can consist of one string value. (e.g. Search for 'Britney Spears')

How do I make a query that splits the string into an array of items using space(' ') as a delimiter
and then use OR statements in the query's where clause?

I.e. Search for 'Britney' OR 'Spears'.


------------------------------------------------------------

Also how does one implement complex search queries such as google's search?

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2004-11-02 : 11:53:24
Here's one way to implement a search, similiar to Google's, if you dont' want to (or can't) use full text indexing. This allows you to pass a string of words, and indicate that either ALL words must match, ANY must match, or the exact string must match.

This is a stripped-down, highly edited version of code I wrote a while ago here at work. This will perform a search in the table "SomeTable", checking the text in the column "SomeColumn".

Use only if you are not searching lots of rows -- less than a few thousand should be fairly efficient; any more than that and you should use SQL's text indexing features.


create procedure SearchSample (@SearchString varchar(200), @MatchType int = 0)
as

-- SeachString: String of 1 or more search terms, all seperated by spaces
-- MatchType: 0=match any, 1 =match all, 2 = exact match of entire expression only

-- Results are returned in order of relevance

declare @i1 int;
declare @i2 int;

declare @Word varchar(100);
declare @Words table (Word varchar(200) not null);
declare @WordCount as integer;

set nocount on

-- Parse the SearchString to extract all words:

if (@MatchType != 2)
begin

set @SearchString = ' ' + @SearchString + ' ';

set @i1 = 1;
while (@i1 != 0)
begin
set @i2=charindex(' ', @SearchString, @i1+1)
if (@i2 != 0)
begin
set @Word = rtrim(ltrim(substring(@SearchString, @i1+1, @i2-@i1)))
if @Word != '' insert into @Words select @Word
end
set @i1 = @i2
end
end
else
insert into @Words select ltrim(rtrim(@SearchString))

-- Get the total # of words:

set @WordCount = (select count(*) from @Words)

-- Return Results in order of relevance:

select
a.MatchPct, T.*
from
SomeTable T
inner join
(
select
ID, Count(*) * 1.0 / @WordCount as MatchPct
from
SomeTable T
inner join
@Words W
on
' ' + T.SomeColumn + ' ' like '%[^a-z]' + Word + '[^a-z]%'
group by
ID
) a
on
T.ID = a.ID
where
MatchPct = 1 or @MatchType <>1
order by
MatchPct


- Jeff
Go to Top of Page

rockmoose
SQL Natt Alfen

3279 Posts

Posted - 2004-11-02 : 15:59:50
Impressive as usual Jeff

rockmoose
Go to Top of Page
   

- Advertisement -