CREATE OR REPLACE FUNCTION accounts_search(v_user_id int4, v_criteria varchar)
RETURNS SETOF view_account_list AS
$BODY$
DECLARE
r view_account_list%rowtype;
v_global bool := users_global(v_user_id);
v_operator int4 := users_operator(v_user_id);
BEGIN
if v_global = TRUE then
for r in select * from view_account_list
WHERE ((m2id like '%' || v_criteria || '%') OR
(sys_accountno like '%' || v_criteria || '%') OR
(first_name like '%' || v_criteria || '%') OR
(last_name like '%' || v_criteria || '%') OR
(company like '%' || v_criteria || '%') OR
(svc_addr like '%' || v_criteria || '%') OR
(phone like '%' || v_criteria || '%') OR
(phone2 like '%' || v_criteria || '%') OR
(cast(device_mac as varchar) like '%' || v_criteria || '%')) loop
return next r;
end loop;
else
for r in select * from view_account_list
WHERE (((m2id like '%' || v_criteria || '%') OR
(sys_accountno like '%' || v_criteria || '%') OR
(first_name like '%' || v_criteria || '%') OR
(last_name like '%' || v_criteria || '%') OR
(company like '%' || v_criteria || '%') OR
(svc_addr like '%' || v_criteria || '%') OR
(phone like '%' || v_criteria || '%') OR
(phone2 like '%' || v_criteria || '%') OR
(cast(device_mac as varchar) like '%' || v_criteria || '%')) AND (operatorid = v_operator)) loop
return next r;
end loop;
end if;
return;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;