I have two tables with the following (dummy) structure:
Table 1
idText sText(nvarchar(500))
1 Text with some keywords
2 Text2 with one keyword
3 Text3 with three keywords
Table 2
idText idKey sKeyword
1 1 some
1 2 keywords
2 3 one
3 4 with
3 2 keywords
3 5 three
Is there any way to execute a nested replace among all the related keywords from Table2
?
There are some solutions around like creating a function, but I do not think is a good solution because this is not going to be reused anywhere else. I did try a recursive CTE as well but without success.
The result must be something like this:
Table 1
idText sText(nvarchar(500))
1 Text with Replaced_some Replaced_keywords
2 Text2 with Replaced_one keyword
3 Text3 Replaced_with Replaced_three Replaced_keywords
PS.
- The Replaced string is fixed. So you can use the string you prefer. The Replace sentence would be something like this:
replace(sText, sKeyword, 'Replaced_' + sKeyowrd)
- IdKey is useless in this case, however it is part of our real DB structure
This is my failed attemp using a recursive CTE:
DECLARE @Table1 TABLE( ID int, sText nvarchar(200))
DECLARE @Table2 TABLE( ID int, sKeyword nvarchar(10))
INSERT INTO @Table1 VALUES(1, 'Text with some keywords')
INSERT INTO @Table1 VALUES(2, 'Text2 with one keyword')
INSERT INTO @Table1 VALUES(3, 'Text3 with three keywords')
INSERT INTO @Table2 VALUES(1, 'some')
INSERT INTO @Table2 VALUES(1, 'keywords')
INSERT INTO @Table2 VALUES(2, 'one')
INSERT INTO @Table2 VALUES(3, 'with')
INSERT INTO @Table2 VALUES(3, 'keywords')
INSERT INTO @Table2 VALUES(3, 'three')
;WITH CTE AS(
SELECT ID, sText FROM @Table1
UNION ALL
SELECT c.ID, CAST(REPLACE(sText, sKeyword, 'New_' + sKeyword) AS nvarchar(200)) FROM CTE c
INNER JOIN @Table2 t2 ON t2.ID = c.ID
)
SELECT * FROM CTE
The result is an infinite loop, it does not stop.
Any help will be appreciated