Say I have a table called PHRASES
containing some text strings
+--+---------------+
|ID|PHRASE |
+--+---------------+
|0 |"HELLO BYE YES"|
+--+---------------+
|1 |"NO WHY NOT" |
+--+---------------+
|2 |"NO YES" |
+--+---------------+
And I want to add the number of times each of the following words occur to the OCCURRENCE
column, let's call this table KEYWORDS
:
+--------+----------+
|KEYWORD |OCCURRENCE|
+--------+----------+
|"YES" |NULL |
+--------+----------+
|"NO" |NULL |
+--------+----------+
|"HELLO" |NULL |
+--------+----------+
|"CHEESE"|NULL |
+--------+---------+
I now want to write a query that would update KEYWORDS
to the following:
+--------+----------+
|KEYWORD |OCCURRENCE|
+--------+----------+
|"YES" |2 |
+--------+----------+
|"NO" |2 |
+--------+----------+
|"HELLO" |1 |
+--------+----------+
|"CHEESE"|0 |
+--------+----------+
Note that I have already got a function called dbo.RegExIsMatch
that can take care of string matches, such that it returns 1
if parameter 1 matches against the string in parameter 2:
UPDATE KEYWORDS SET OCCURRENCE =
(
SELECT SUM
(
-- the following returns 1 if the keyword exists in the phrase, or 0 otherwise
CASE WHEN dbo.RegExIsMatch('.*' + KEYWORDS.KEYWORD + '.*',PHRASES.PHRASE,1) = 1 THEN 1 ELSE 0 END
)
FROM PHRASES
CROSS JOIN KEYWORDS
)
This doesn't work though, it just ends up filling each row with the same number. I'm sure this is a simple problem I'm just struggling to get my head around SQL-think.