SQL Server Trying to search for needles in haystacks using dynamic queries

ut6juiuv  于 2023-10-15  发布在  其他
关注(0)|答案(4)|浏览(159)

Please consider the following SQL Fiddle: http://sqlfiddle.com/#!3/9d4fc/3

I have 3 documents:

  1. ('id1', 'lorem ipsum dolor dog'),
  2. ('id2', 'the cat jumps over the lazy dog'),
  3. ('id3', 'i have no clue what to write');

I want to dynamically search these documents for needles:

  1. ('a', 'dog'),
  2. ('b', 'dolor'),
  3. ('c', 'write');

The results I need would be table tmp_auditlog_results looking like

  1. doc needle string
  2. ---------------------------------------------
  3. id1 dog lorem ipsum dolor dog
  4. id2 dog the cat jumps over the lazy dog
  5. id1 dolor lorem ipsum dolor dog
  6. id3 write i have no clue what to write

I got confused by the dynamic query adding to the result table. Could you please have a look how I can get this result from the result I have now? Any help would be appreciated.

olmpazwi

olmpazwi1#

You don't need any dynamic code. You can use CHARINDEX

  1. INSERT INTO tmp_auditlog_results
  2. SELECT S.docid, F.NEEDLE
  3. FROM tmp_auditlog_subselection AS S
  4. CROSS JOIN tmp_auditlog_fields AS F
  5. WHERE CHARINDEX(F.needle, S.haystack) != 0
jmp7cifd

jmp7cifd2#

Replace the select statement:

  1. select * from tmp_auditlog_fields;

with following statement:

  1. SELECT DISTINCT 'id' + CAST(A.id as VARCHAR(9999)) AS doc, needle, B.haystack
  2. FROM tmp_auditlog_fields A
  3. INNER JOIN tmp_auditlog_subselection B
  4. ON B.docid = 'id'+ CAST(A.id as VARCHAR(9999))
x6yk4ghg

x6yk4ghg3#

The answer from podiluska needed some renaming of column names. So i created this example starting from his query

Given these Tables

  1. CREATE TABLE Haystacks (
  2. docid varchar(255),
  3. haystack varchar(255)
  4. )
  5. CREATE TABLE Needles (
  6. id int identity(1,1),
  7. fieldid varchar(255),
  8. needle varchar(255)
  9. )

And these records

  1. insert into Haystacks (docid, haystack) values
  2. ('id1', 'lorem ipsum dolor dog'),
  3. ('id2', 'the cat jumps over the lazy dog'),
  4. ('id3', 'i have no clue what to write');
  5. insert into Needles (fieldid, needle) values
  6. ('a', 'dog'),
  7. ('b', 'dolor'),
  8. ('c', 'write');

This query

  1. SELECT docid, needles.needle, haystack
  2. FROM Haystacks
  3. INNER JOIN Needles ON Haystacks.haystack
  4. like '%'+Needles.needle+'%'

returns this result

See this demo fiddle this matches the expected query result

  1. doc needle string
  2. ---------------------------------------------
  3. id1 dog lorem ipsum dolor dog
  4. id2 dog the cat jumps over the lazy dog
  5. id1 dolor lorem ipsum dolor dog
  6. id3 write i have no clue what to write
展开查看全部
92vpleto

92vpleto4#

  1. INSERT tmp_auditlog_results (doc,needle,string)
  2. SELECT doc, needles.needle, string
  3. FROM haystacks
  4. INNER JOIN needles ON haystacks.string like '%'+needles.needle+'%'

相关问题