Supabase中PL/pgSQL声明游标报错:关系cursor1不存在
问题原因及解决方案
错误出在entry cursor1%rowtype;这一行:在PL/pgSQL中,%rowtype只能用于数据库表/视图或者表别名,不能直接用于游标变量。当你写cursor1%rowtype时,PostgreSQL会误认为你要引用名为cursor1的数据库表,但这个表不存在,因此抛出42P01: relation "cursor1" does not exist错误。
修复方案
方案1:用RECORD类型声明变量(推荐,无需额外定义类型)
直接将entry声明为RECORD类型,它会自动适配游标查询返回的行结构:
DECLARE cursor1 CURSOR FOR SELECT sc.cap, sc.spent, sc.image_cap, sc.image_spent, sc.id, sc.created_by FROM public.spending_cap sc JOIN public.user_profile up ON up.id = sc.created_by WHERE up.is_parent = true AND up.organisation IS NULL; entry RECORD; BEGIN -- 打开游标并遍历 OPEN cursor1; LOOP FETCH cursor1 INTO entry; EXIT WHEN NOT FOUND; -- 这里编写处理逻辑,比如打印字段值 RAISE NOTICE '额度上限: %, 创建人ID: %', entry.cap, entry.created_by; END LOOP; CLOSE cursor1; END;
方案2:使用隐式游标遍历(更简洁)
不需要显式声明游标,直接用FOR循环遍历查询结果,PL/pgSQL会自动管理游标生命周期:
DECLARE entry RECORD; BEGIN FOR entry IN SELECT sc.cap, sc.spent, sc.image_cap, sc.image_spent, sc.id, sc.created_by FROM public.spending_cap sc JOIN public.user_profile up ON up.id = sc.created_by WHERE up.is_parent = true AND up.organisation IS NULL LOOP -- 处理逻辑示例 RAISE NOTICE '已使用额度: %, 图片额度上限: %', entry.spent, entry.image_cap; END LOOP; END;
方案3:自定义复合类型(适合需要重复使用行结构的场景)
如果这个行结构需要在多个函数中使用,可以先创建自定义类型,再用该类型声明变量:
-- 先执行这条语句创建类型(字段类型要和表中对应字段一致) CREATE TYPE spending_cap_entry AS ( cap NUMERIC, spent NUMERIC, image_cap INTEGER, image_spent INTEGER, id UUID, created_by UUID );
然后在函数中使用:
DECLARE cursor1 CURSOR FOR SELECT sc.cap, sc.spent, sc.image_cap, sc.image_spent, sc.id, sc.created_by FROM public.spending_cap sc JOIN public.user_profile up ON up.id = sc.created_by WHERE up.is_parent = true AND up.organisation IS NULL; entry spending_cap_entry; BEGIN OPEN cursor1; LOOP FETCH cursor1 INTO entry; EXIT WHEN NOT FOUND; -- 处理逻辑 END LOOP; CLOSE cursor1; END;
内容的提问来源于stack exchange,提问作者progNewbie
相关产品推荐
相关产品推荐

