我是PostgreSQL的初学者。尝试在此处循环传递我传递的值:
companyregistration
仅呼叫companyRegistrationValidator
函数调用:
SELECT companyregistration(
'876786576544',
'TraderAnalytics',
'TraderAnalytics@gmail.com,
'@kjvfhjh88976',
ARRAY['86578657865','Natali','Vladimirov','Natali.Vladimirov1990@gmail.com', '+@jvfhjh88976'],
ARRAY [['Maks','Burkov'],['Yan','Burkov']],
'Netherlands',
'Company');
[2018-10-28 18:29:15] [42804] ERROR: FOREACH expression must yield an array, not type text [2018-10-28 18:29:15] Where: PL/pgSQL function companyregistrationvalidator(character varying,character varying,character varying,character varying,text[],text[],character varying) line 28 at FOREACH over array
函数定义:
CREATE OR REPLACE FUNCTION companyRegistrationValidator (company_id VARCHAR, comp_name VARCHAR, comp_email VARCHAR, comp_password VARCHAR, employees text[], creators text[], country VARCHAR)
RETURNS BOOLEAN AS $$
DECLARE
checked BOOLEAN := FALSE ;
r_id VARCHAR; r_name VARCHAR; r_email VARCHAR; r_password VARCHAR; r_country VARCHAR;
cr_counter INTEGER = 0; em_counter INTEGER = 0; c_ar_length INTEGER = 0; e_ar_length INTEGER = 0;
ar_index text; creator text; val text;
BEGIN
SELECT id_r , email_r , password_r , country_r , firstname_r INTO r_id , r_email , r_password, r_country , r_name FROM regex;
c_ar_length := cardinality(creators);
e_ar_length := cardinality(employees);
FOREACH val IN ARRAY employees LOOP
IF val ~ r_id THEN em_counter := +1;
ELSEIF val ~ r_name THEN em_counter := +1;
ELSEIF val ~ r_email THEN em_counter := +1;
ELSEIF val ~ r_password THEN em_counter := +1;
END IF;
END LOOP;
FOREACH creator IN ARRAY creators LOOP
FOREACH ar_index IN ARRAY creator LOOP
IF ar_index ~ r_name THEN cr_counter := +1;
END IF;
END LOOP;
END LOOP;
IF cr_counter = c_ar_length AND em_counter = e_ar_length AND company_id ~ r_id AND comp_name ~ r_name AND comp_email ~ r_email AND comp_password ~ r_password AND country ~ r_country
THEN checked := TRUE;
END IF;
RETURN checked;
END;
$$ LANGUAGE plpgsql;
我的代码有什么错误?
答案 0 :(得分:1)
此嵌套循环构造非常适合您引用的错误:
FOREACH creator IN ARRAY creators LOOP
FOREACH ar_index IN ARRAY creator LOOP
IF ar_index ~ r_name THEN cr_counter := +1;
END IF;
END LOOP;
END LOOP;
外部循环中的循环变量creator
定义为类型text
,可以。但是您不能像尝试那样通过creator
嵌套另一个循环-也不需要。
The manual on Looping Through Arrays:
按存储顺序访问元素,而与数组维数无关。
因此,要遍历所有基本元素,而不必考虑数组维数 ,
FOREACH creator IN ARRAY creators LOOP
IF creator ~ r_name THEN cr_counter := cr_counter + 1;
END IF;
END LOOP;
还请注意,cr_counter := +1
不会像您正在尝试的那样增加cr_counter
。只需重复分配1
。我将其替换为实际上可以增加的表达式。
然而,就像通常那样,除非数组很小,否则基于 set-set的方法会更快。喜欢:
SELECT INTO cr_counter
count(*) FILTER (WHERE _creator ~ r_name)::int
FROM unnest(creators) _creator;
(您确定要在其中使用正则表达式运算符~
吗?)