我有一个包含20个(或更多)单词(字符串)的列表,并希望在其列的3个中选择包含这些单词的行。我应该使用like
sql的表达式。但我不知道如何在表达式中使用多个字符串。
(我现在用union
做,但我有至少60个选择语句并认为它降低了性能,是否真的降低了性能?)
//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");
最后我使用了以下代码:
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
答案 0 :(得分:1)
答案 1 :(得分:1)
创建一个带有表值参数的存储过程,该参数带有您的字符串列表。
在表值参数和表格AD_Advertise之间建立连接。
继承人如何处理表类型+存储过程:
CREATE TYPE WordList AS TABLE (Word NVARCHAR(50));
GO
CREATE PROCEDURE GetAddsMatchingKeywords
@KeywordList WordList READONLY,
@AdGroupItemCode VARCHAR(50),
@AdSiteId INT,
@ItemId INT
AS
SELECT DISTINCT
a.AdTitle,
a.ItemId -- extend to the full column list
FROM AD_ADvertise a
LEFT JOIN @KeywordList k ON a.AdKeywords LIKE '%' + k.Word + '%' OR a.AdTitle LIKE '%' + k.Word + '%' OR a.AdDescription LIKE '%' + k.Word + '%'
WHERE
(k.Word IS NOT NULL OR a.AdGroupItemCode = @AdGroupItemCode)
AND a.AdSiteId = @AdSiteId
AND a.AdShow = 'True'
AND a.ItemId = @ItemId
GO
编辑 - 误读原始问题 - 认为您想要匹配3个或更多单词。 这个版本匹配任何3列中任何一个单词的任何一个 - 就像你想的那样。
答案 2 :(得分:0)
//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 + AdTitle + 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");