You're on the right track with using CHARINDEX to check for the existence of a value within a string, but the logic in your current query is a bit off if your goal is to check if something exists twice (i.e., appears two or more times) in a string like rp.VisitedItems.
🔍 Let's break down what you're doing:
AND CHARINDEX(CAST([Test].[Id] AS VARCHAR(MAX)), rp.VisitedItems,
(CHARINDEX(CAST([Test].[Id] AS VARCHAR(MAX)), rp.VisitedItems, 1))
) = 0
This is trying to do a double search:
- First find the first occurrence:
CHARINDEX(..., ..., 1)
- Then start from that position and look again.
If the second occurrence returns 0, it means there is no second appearance.
So this condition is actually checking that there is only one or zero occurrences of [Test].[Id] in VisitedItems.
✅ Goal: Check if [Test].[Id] appears 2 or more times
We want to check whether a second occurrence exists — i.e., after the first match, another match exists later in the string.
Here’s how you can write that:
AND CHARINDEX(CAST([Test].[Id] AS VARCHAR(MAX)), rp.VisitedItems,
CHARINDEX(CAST([Test].[Id] AS VARCHAR(MAX)), rp.VisitedItems, 1) + 1
) > 0
✅ Explanation:
- The first
CHARINDEX finds the first occurrence.
- The second
CHARINDEX starts searching after the first occurrence.
- If it finds a result > 0, then a second occurrence exists → so we know it appears at least twice.
🧠 Optional: Count how many times it appears
If you want to be even more precise and count how many times [Test].[Id] appears in VisitedItems, you could use a function like this:
CREATE FUNCTION dbo.CountOccurrences (@Text VARCHAR(MAX), @SearchFor VARCHAR(MAX))
RETURNS INT
AS
BEGIN
RETURN (LEN(@Text) - LEN(REPLACE(@Text, @SearchFor, ''))) / LEN(@SearchFor)
END
Then use it like:
WHERE dbo.CountOccurrences(rp.VisitedItems, CAST([Test].[Id] AS VARCHAR(MAX))) >= 2
⚠️ Caveats:
- These approaches are case-sensitive.
- They may have false matches if
VisitedItems contains substrings (e.g., looking for '12' when '123' is present).
- If
VisitedItems is a delimited list (like comma-separated), better to split it and compare exact values.
✅ Summary
To check if [Test].[Id] appears at least twice in rp.VisitedItems:
AND CHARINDEX(CAST([Test].[Id] AS VARCHAR(MAX)), rp.VisitedItems,
CHARINDEX(CAST([Test].[Id] AS VARCHAR(MAX)), rp.VisitedItems, 1) + 1
) > 0
Let me know if VisitedItems is a comma-separated list or structured differently – I can tailor the solution further!