【发布时间】:2015-06-07 08:15:40
【问题描述】:
我正在编写一个存储过程来查找主项的子项并对其进行更新。剧情是这样的
Id Item Name Parent Id
1 Item A 14.1 NULL
2 Item B 14.1.1 1
3 Item C 14.1.2 1
4 Item B 14.1.3 1
5 Item A 14.1.1.1 2
我在 SO String matching in PostgreSQL 8.4 上发布了另一个问题,以获取项目的子项。根据该答案,我必须转义项目代码并必须在查询中使用它。但是我没有任何方法可以逃脱。 SP如下:
CREATE OR REPLACE FUNCTION updateitemparentnew(bigint, int) RETURNS text
LANGUAGE plpgsql STRICT
AS $$
DECLARE
itemdetail RECORD;
codeSearch text;
codeEscapedSearch text;
result text;
BEGIN
--Get th details of the current item
SELECT INTO itemdetail * FROM om_item WHERE item_id = $1;
codeSearch = itemdetail.item_code||'.';
codeEscapedSearch = codeSearch; --Need to be corrected. It should escape the item code
-- Event 1=> add 2 => edit 3 => delete
IF $2 = 1 THEN
--Find new children and update then
result = 'UPDATE om_item SET item_parentid = '||itemdetail.item_id
||' WHERE item_id IN (
SELECT item_id FROM om_item
WHERE item_code LIKE \''||codesearch||'%\'
AND item_code ~ \''||codeEscapedsearch||'[^.]+$\');';
END IF;
return result;
END;
$$;
在查询中codeEscapedSearch 应该被转义以处理代码本身中的. 和正则表达式中的.。
【问题讨论】:
标签: regex postgresql stored-procedures plpgsql