我有 2 张桌子。一个包含键/值对。另一个包含 varchar 列,需要将文本中的所有键实例替换为相应的值。
我已经使用有效的游标在存储过程中实现了这一点。但我确实需要存储过程尽可能高效地执行。我的第一个想法是删除光标。那可能吗?也许使用递归cte?示例如下。
设置
DECLARE @Dictionary TABLE
(
WordKey NVARCHAR(255),
WordValue NVARCHAR(4000)
)
INSERT INTO @Dictionary
VALUES
('[key1]', 'Value1'),
('[key2]', 'Value2'),
('[key3]', 'Value3')
DECLARE @Phrasings TABLE
(
Phrasing1 NVARCHAR(4000),
Phrasing2 NVARCHAR(4000),
Phrasing3 NVARCHAR(4000)
)
INSERT INTO @Phrasings
VALUES
('[key1]','random text','random text'),
('random text','random [key2] text','random text'),
('random text [key1]','random [key2] text','random [key1] [key3] text')
主要查询
DECLARE @WordKey NVARCHAR(255)
DECLARE @WordValue NVARCHAR(max)
DECLARE parsing_cursor CURSOR FOR
SELECT WordKey,WordValue FROM @Dictionary
OPEN parsing_cursor
FETCH NEXT FROM parsing_cursor
INTO @WordKey, @WordValue
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE @Phrasings SET
Phrasing1 = REPLACE(Phrasing1, @WordKey, @WordValue),
Phrasing2 = REPLACE(Phrasing2, @WordKey, @WordValue),
Phrasing3 = REPLACE(Phrasing3, @WordKey, @WordValue)
FETCH NEXT FROM parsing_cursor
INTO @WordKey, @WordValue
END
CLOSE parsing_cursor
DEALLOCATE parsing_cursor
预期结果
Phrasing1 Phrasing2 Phrasing3
^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^
"Value1" "random text" "random text"
"random text" "random Value2 text" "random text"
"random text Value1" "random Value2 text" "random Value1 Value3 text"