I have a list of 20 (or more) words (string) and want to select the rows that have these word in 3 of their column. I should use like expression of sql. but I don't know how to use more than one string in like expression.
(I do it with union now, but I have at least 60 select statement and think it reduced the performance, Is it really reduce the performance?)
//get the advertise that have similar keywords
foreach (string str in keywords)
{
if (str != "")
{
if (!string.IsNullOrEmpty(sqlQuery)) sqlQuery += " union";
sqlQuery = "select * from AD_Advertise where (AdKeyWords like N'%" + str + "%'"
+ " OR AdTitle like N'%" + str + "%' "
+ " OR AdDescription like N'%" + str + "%' "
+ " OR AdGroupItemCode=" + adinfo.AdGroupItemCode + ")"
+ " AND AdSiteID=" + CMSContext.CurrentSiteID
+ " AND AdShow='True' "
+ " AND ItemID != " + ADId;
}
}
ds = cn.ExecuteQuery(sqlQuery,null);//("AD.Advertise.selectall", null, where, "ItemModifiedWhen");
Answer:
At last I used below code:
if object_id('tempdb..#WordList') is not null
drop table #WordList
CREATE TABLE #WordList ( KeyWord nvarchar(100))
insert into #WordList values (N'حقوقی'),(N'وکیل');
SELECT DISTINCT *
FROM AD_ADvertise a
LEFT JOIN #WordList k
ON a.AdKeywords LIKE '%' + k.KeyWord + '%'
OR a.AdTitle LIKE '%' + k.KeyWord + '%'
OR a.AdDescription LIKE '%' + k.KeyWord + '%'
WHERE
(k.KeyWord IS NOT NULL OR a.AdGroupItemCode = @AdGroupItemCode)
AND a.AdSiteId = @AdSiteId
AND a.AdShow = 'True'
AND a.ItemId != @ItemId
;drop table #WordList
"OR"statement inforeachloop and than build a final query later.ORstatement inwhereclause don't reduce the speed?