请考虑以下SQL小提琴:http://sqlfiddle.com/#!3/9d4fc/3
我有3份文件:
('id1', 'lorem ipsum dolor dog'),
('id2', 'the cat jumps over the lazy dog'),
('id3', 'i have no clue what to write');
我想动态搜索这些文件以寻找针头:
('a', 'dog'),
('b', 'dolor'),
('c', 'write');
我需要的结果是表tmp_auditlog_results
看起来像
doc needle string
---------------------------------------------
id1 dog lorem ipsum dolor dog
id2 dog the cat jumps over the lazy dog
id1 dolor lorem ipsum dolor dog
id3 write i have no clue what to write
我对添加到结果表的动态查询感到困惑。你能看看我如何从我现在的结果中得到这个结果吗?任何帮助将不胜感激。
答案 0 :(得分:0)
insert tmp_auditlog_results (doc,needle,string)
select doc, needles.needle, string
from haystacks
inner join needles on haystacks.string like '%'+needles.needle+'%'
答案 1 :(得分:0)
您不需要任何动态代码。您可以使用CHARINDEX
INSERT INTO tmp_auditlog_results
SELECT S.docid, F.NEEDLE
FROM tmp_auditlog_subselection AS S
CROSS JOIN tmp_auditlog_fields AS F
WHERE CHARINDEX(F.needle, S.haystack) != 0
答案 2 :(得分:0)
替换select语句:
select * from tmp_auditlog_fields;
以下声明:
SELECT DISTINCT 'id' + CAST(A.id as VARCHAR(9999)) AS doc, needle, B.haystack
FROM tmp_auditlog_fields A
INNER JOIN tmp_auditlog_subselection B
ON B.docid = 'id'+ CAST(A.id as VARCHAR(9999))