views:

49

answers:

2

Hi

I have the following code for searching multiple keywords within a document title which works fine. I want now to have a column that shows the number of keywords that are found in each title row and order in a descendent way. For example if I'm searching for "Maternity leave" I should get something like this:

Name -- Keywords found

Maternity Leave policy -- 2

Annual leave policy -- 1

Maternity advice for mothers-to-be -- 1

Hope it makes sense, Many thanks!

    Dim s As String = TextBox1.Text

    Dim SqlQuery As String = "SELECT Doc_LibraryTable.DocID, Doc_LibraryTable.DocName, Doc_LibraryTable.DocType WHERE Doc_LibraryTable.DocType = DocType"

    Dim ints As String() = s.Split(" ")
    Dim i As Integer 

    If UBound(ints) >= 1 Then
        SqlQuery += " AND (Doc_LibraryTable.DocName LIKE '%" + ints(0) + "%'"       

        For i = 1 To UBound(ints)
            If Not ints(i) = "of" And Not ints(i) = "the" And Not ints(i) = "in" And Not ints(i) = "or" Then
                SqlQuery += " OR Doc_LibraryTable.DocName LIKE '%"
                SqlQuery += ints(i) + "%'"
            End If
        Next



    ElseIf UBound(ints) < 1 Then
       For i = 0 To UBound(ints)
            SqlQuery += " AND (Doc_LibraryTable.DocName LIKE '%"
            SqlQuery += ints(i) + "%"
        Next

   End If

     If UBound(ints) >= 1 Then
        SqlQuery += ")"
    ElseIf UBound(ints) < 1 Then
        SqlQuery += "')"
    End If

    SqlDataSource2.SelectCommand = SqlQuery
    GridView1.DataSource = SqlDataSource2
A: 

You can do this my modifying your SELECT clause in a loop and using the CASE statement, e.g.:

Dim SqlQuery As String = "SELECT Doc_LibraryTable.DocID, Doc_LibraryTable.DocName, Doc_LibraryTable.DocType, "
Dim sep as String = ""
For i = 0 To UBound(ints)
    SqlQuery += sep + "CASE WHEN Doc_LibraryTable.DocName LIKE '%" + ints(i) + "%' THEN 1 ELSE 0 END"
    sep = " + "
Next
SqlQuery += " as MatchCount WHERE Doc_LibraryTable.DocType = DocType"
RedFilter
This is what I was looking for. Works perfectly, many thanks!!!!
A: 

Another way which is a bit messy is to do something like

select ...   
 , len(replace([DocName],'Maternity leave','Maternity leave' + '*')) - len([DocName])
  As NameHits

I used the following code to test this:-

set nocount on;
declare @t as table([name] varchar(10))
insert into @t values ('a bb c')
insert into @t values ('aa bc c')

declare @find varchar(5)
set @find = 'bc'

select
    *, 
    len(replace([name],@find,@find + '*')) - len(name)

from @t
Rippo
Actually this will only find the phrase "maternity leave" and maybe not be suitable!
Rippo