dynamic query

  • I have a table(emp_names) with two columns e_id and name and the tables data is shown below.

    e_id  name

    1 sam

    2 ram 

    3 john

    4 pollock

    5 chappel

    6 allen

    7 koby

    8 griffith

    9 sally

    10 neil

    I have to search a text field in another table with the words in the name field.

    Example.

    SELECT dept_id,dept_name

     FROM dept_heads WHERE name like '%sam%' OR name like '%ram%' OR name like '%john%' OR name like '%pollock%'

     OR name like '%chappel%' OR name like '%allen%' OR name like '%koby%' OR name like '%griffith%' OR name like '%sally%' OR   name like '%neil%'

    The rwos in the table may be added. So when a new row is added to the table tha query should also reflect that change.

    e_id  name

    1 sam

    2 ram 

    3 john

    4 pollock

    5 chappel

    6 allen

    7 koby

    8 griffith

    9 sally

    10 neil

    11 keith

    SELECT dept_id,dept_name

     FROM dept_heads WHERE name like '%sam%' OR name like '%ram%' OR name like '%john%' OR name like '%pollock%'

     OR name like '%chappel%' OR name like '%allen%' OR name like '%koby%' OR name like '%griffith%' OR name like '%sally%' OR   name like '%neil%' OR name like '%keith%'

    How can develop this query dynamically.

    Thanks.

  • select d.dept_id, d.dept_name, d.[name] from dept_heads d inner join emp_names e on d.[name] LIKE '%' + e.[name] +'%'

    ______________________________________________________________________

    Personal Motto: Why push the envelope when you can just open it?

    If you follow the direction given HERE[/url] you'll likely increase the number and quality of responses you get to your question.

    Jason L. Selburg
  • Hi Jason,

     

    It worked really good.

     

    Thanks.

  • Why are you using %% (%sam%, etc)?

    If you are searching a text field %sam% will return:

    balsam

    sam

    same

    sample

    samuel

    Instead, do % sam %.

    -SQLBill

  • Hi, thanks for both of you on ur help. Infact I have built my query in the way sqlbill has suggested.

    But I am into another issue. Some times my text column has html tags also. So for example if I am searching for a word border my search query will pull the the border from the html tags.

    <h1><img border="0".......

    So how can I by pass all the html tags when I search for a string.

    Thanks.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply