我想删除名称未知的约束,所以我使用以下代码:
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 $$;
答案 0 :(得分:0)
这应该可以解决您的问题:
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:处理带有双引号的对象/约束时要小心。