通过存储在 Postgresql 中带有特殊字符的变量名中来删除约束
Posted
技术标签:
【中文标题】通过存储在 Postgresql 中带有特殊字符的变量名中来删除约束【英文标题】:Drop constraint by stored in a variable name with special characters in Postgresql 【发布时间】:2018-10-22 06:50:22 【问题描述】:我想删除名称未知的约束,所以我使用以下代码:
EXECUTE 'ALTER TABLE public."IntravenousTherapyAppointment" DROP CONSTRAINT '||fk_Name||';';
问题是 fk_Name 以 '~' 结尾,所以出现语法错误。
完整代码:
DO $$
DECLARE fk_Name TEXT;
BEGIN
fk_Name := (SELECT
tc.constraint_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='IntravenousTherapyAppointment' AND ccu.table_name='MedicamentMeasurementUnit');
IF fk_Name IS NOT NULL THEN
EXECUTE 'ALTER TABLE public."IntravenousTherapyAppointment" DROP CONSTRAINT '||fk_Name||';';
END IF;
END $$;
【问题讨论】:
【参考方案1】:这应该可以解决您的问题:
DO $$
DECLARE fk_Name TEXT;
BEGIN
fk_Name := (SELECT
tc.constraint_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='IntravenousTherapyAppointment' AND ccu.table_name='MedicamentMeasurementUnit');
IF fk_Name IS NOT NULL THEN
EXECUTE 'ALTER TABLE public."IntravenousTherapyAppointment" DROP CONSTRAINT "'||fk_Name||'";';
END IF;
END $$;
P.S:处理带有双引号名称的对象/约束时要小心。
【讨论】:
我在我的 posgres 数据库中遇到了这种类型的变量赋值问题。我需要它类似于 oracle :SELECT constraint_name INTO fk_Name。 PL 脚本中的一个好主意是使用 RAISE NOTICE 'Some text to be logged out';查看脚本导航到的位置。以上是关于通过存储在 Postgresql 中带有特殊字符的变量名中来删除约束的主要内容,如果未能解决你的问题,请参考以下文章