I have a Keywords table with the fields KeywordsEn and KeywordsFr.
I have another MediaObjectsMetadata with the field Values.
I need to check that the Value field contains at least one of the words from the Keywords table (either in KeywordsEn or KeywordsFr field).
I thought I would use the Contains function like this, where @priorityKeywords contains all the KeywordsEn and KeywordsFr concatenated with OR, but then I have over 16000 characters in my string, and the Contains function can only allow 4000.
Part of my SP
SELECT FKMediaObjectId
FROM dbo.gs_MediaObjectMetadata
WHERE UPPER([Description]) = 'KEYWORDS'
AND FKMediaObjectId >=
(SELECT TOP 1 MediaObjectId
FROM dbo.gs_MediaObject
WHERE DateAdded > @lastcheck
ORDER BY MediaObjectId)
AND Contains([Value] , @priorityKeywords);
C# function which generates @priorityKeywords
public static string GetPriorityKeywordsList()
{
string keywordString = String.Empty;
using (IDataReader dr = GetCommandPriorityKeywordsList().ExecuteReader(CommandBehavior.CloseConnection))
{
while (dr.Read())
{
if (keywordString.Length > 0)
{
keywordString += " OR ";
}
// max 4000 chars allowed in COntains sql function of sp
keywordString += "'" + dr["KeywordEn"].ToString() + "' OR '" + dr["KeywordFr"].ToString() + "'";
}
}
return keywordString;
}
What solution would you recommend for my stored procedure?
Edit (Solution):
Here is the solution proposed by Andomar, adapted to my situation:
select *
from gs_MediaObjectMetadata yt
where
UPPER([Description]) = 'KEYWORDS'
AND not exists
(
select *
from dbo.fnSplit(Replace(yt.Value, '''', ''''''), ',') split
where split.item in (select KeywordEn from gs_Keywords) or split.item in (select KeywordFr from gs_Keywords)
)
If you’re using SQL Server 2008, you can use a table-valued parameter to pass the list of keywords to the stored procedure. You can use the variable like you would use a
table, in ajoinor aninclause. For example:EDIT: if you have more than one keyword in the value field, you could use a split function. For example:
This demands that all keywords in the value column (separated by a space) are present in the
@listparameter.