I’m trying to create a function, like so:
CREATE FUNCTION RETURNONE(DATE)
BEGIN
RETURN 1;
END
However, when I run this in psql 9.5 I get the following error:
ERROR: syntax error at or near "BEGIN"
LINE 2: BEGIN
^
END
I did see this other StackOverflow thread with a reminiscent problem. Per the second answer, I re-encoded my code in UTF 8, which did nothing. This is my first ever SQL function, so I’m sure I’m missing something painfully obvious. Let me know what!
asked Feb 27, 2019 at 1:00
![]()
3
You omitted some essential syntax elements:
CREATE FUNCTION returnone(date)
RETURNS integer
LANGUAGE plpgsql AS
$func$
BEGIN
RETURN 1;
END
$func$;
The manual about CREATE FUNCTION.
answered Feb 27, 2019 at 1:19
Erwin BrandstetterErwin Brandstetter
577k139 gold badges1034 silver badges1188 bronze badges
4
Syntax errors are quite common while coding.
But, things go for a toss when it results in website errors.
PostgreSQL error 42601 also occurs due to syntax errors in the database queries.
At Bobcares, we often get requests from PostgreSQL users to fix errors as part of our Server Management Services.
Today, let’s check PostgreSQL error in detail and see how our Support Engineers fix it for the customers.
What causes error 42601 in PostgreSQL?
PostgreSQL is an advanced database engine. It is popular for its extensive features and ability to handle complex database situations.
Applications like Instagram, Facebook, Apple, etc rely on the PostgreSQL database.
But what causes error 42601?
PostgreSQL error codes consist of five characters. The first two characters denote the class of errors. And the remaining three characters indicate a specific condition within that class.
Here, 42 in 42601 represent the class “Syntax Error or Access Rule Violation“.
In short, this error mainly occurs due to the syntax errors in the queries executed. A typical error shows up as:

Here, the syntax error has occurred in position 119 near the value “parents” in the query.
How we fix the error?
Now let’s see how our PostgreSQL engineers resolve this error efficiently.
Recently, one of our customers contacted us with this error. He tried to execute the following code,
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
WITH m_ty_person AS (return query execute sql)
select name, count(*) from m_ty_person where name like '%a%' group by name
union
select name, count(*) from m_ty_person where gender = 1 group by name;
END
$$ LANGUAGE plpgsql;
But, this ended up in PostgreSQL error 42601. And he got the following error message,
ERROR: syntax error at or near "return"
LINE 5: WITH m_ty_person AS (return query execute sql)
Our PostgreSQL Engineers checked the issue and found out the syntax error. The statement in Line 5 was a mix of plain and dynamic SQL. In general, the PostgreSQL query should be either fully dynamic or plain. Therefore, we changed the code as,
RETURN QUERY EXECUTE '
WITH m_ty_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM m_ty_person WHERE name LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM m_ty_person WHERE gender = 1 GROUP BY name$x$;
This resolved the error 42601, and the code worked fine.
[Need more assistance to solve PostgreSQL error 42601?- We’ll help you.]
Conclusion
In short, PostgreSQL error 42601 occurs due to the syntax errors in the code. Today, in this write-up, we have discussed how our Support Engineers fixed this error for our customers.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
|
Ayil 0 / 0 / 0 Регистрация: 15.05.2019 Сообщений: 2 |
||||
|
1 |
||||
|
26.03.2020, 09:11. Показов 846. Ответов 1 Метки pgadmin, sql (Все метки)
Напишите процедуру на ввод записей о преподавателях ВГУ. Идентификационные номера преподавателей должны вводится в порядке возрастания.
но выдает:»ошибка синтаксиса (примерное положение: «begin»)» Вот таблица.
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
26.03.2020, 09:11 |
|
1 |
|
1184 / 914 / 367 Регистрация: 02.09.2012 Сообщений: 2,785 |
|
|
26.03.2020, 16:25 |
2 |
|
декларация переменной должны заканчиваться точкой с запятой
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
26.03.2020, 16:25 |
|
Помогаю со студенческими работами здесь Не заходит в pgAdmin PgAdmin настройка Распределенная БД в pgAdmin Ограничить ввод определенных записей в форме Организовать ввод, хранение и сортировку записей Изменение и ввод записей непосредственно в DBGrid Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 2 |
БЛОГ НА HUSL
- Деловая переписка на английском языке: фразы и советы
- Принцип цикады и почему он важен для веб-дизайнеров
- В популярных антивирусах для ПК обнаружили лазейки в защите
Триггерная функция, которая удаляет роль
Автор вопроса: Azonos
Код триггерной функции:
begin
prepare myfun(text) as
drop role $1;
execute myfun(old.employee_login);
end;
При попытке сохранения выдает ошибку : ошибка синтаксиса (примерное положение: «drop»). В чем может быть проблема?
Источник
Ответы (1 шт):
Автор решения: Azonos
Рабочий код:
begin
execute 'DROP ROLE '|| old.employee_login;
return null;
end;
→ Ссылка
licensed under cc by-sa 3.0 with attribution.
Вопрос:
Я пытаюсь создать функцию, которая суммирует результат всех значений запроса и сравнивает ее с рядом других простых запросов.
Это то, что у меня есть, однако я получаю синтаксическую ошибку около начала (2-я строка):
CREATE FUNCTION trigf1(sbno integer, scid numeric(4,0)) RETURNS integer
BEGIN
declare sum int default 0;
declare max as SELECT totvoters FROM ballotbox WHERE cid=scid AND bno=sbno;
for r as
SELECT nofvotes FROM votes WHERE cid=scid AND bno=sbno;
do
set sum = sum + r.nofvotes;
end for
if sum > max
then return(0);
else
return(1);
END
Это приводит к:
Ошибка синтаксиса рядом с ‘BEGIN’
Я использую postgreSQL и pgadminIII (на всякий случай это актуально).
Я понятия не имею, почему я получаю эту ошибку, все, кажется, точно так же, как определяется учебник. (Это текстовая книга, которую я использую: http://digilib.usu.ac.id/buku/107859/Database-systems-concepts,-6th-ed.html)
Лучший ответ:
Я не знаю, какой “учебник” вы использовали, но если все, что вы написали, точно так же, как в этой книге, эта книга совершенно неверна:
CREATE FUNCTION trigf1(sbno integer, scid numeric(4,0))
RETURNS integer
AS -- error #1: no AS keyword
$body$ -- error #2: use dollar quoting to specify the function body as a string
DECLARE -- error #3: the declare block comes before the actual code
sum_ integer := 0; -- error #5: you can't use a reserved keyword as a variable
max_ integer; -- error #6: you can't initialize a variable with a select,
r record; -- you need to declare the record for the cursor loop
BEGIN
select totvoters
into max_
from ballotbox
WHERE cid=scid AND bno=sbno;
-- error #7: the syntax for a loop uses IN not AS
-- error #8: you need to declare R before you can use it
-- error #9: the SELECT for a cursor loop must NOT be terminated with a ;
FOR r IN SELECT nofvotes FROM votes WHERE cid=scid AND bno=sbno
loop -- error #10: you need to use LOOP, not DO
sum_ := sum_ + r.nofvotes; -- error #11: you need to use := for an assignment, not SET
end loop; -- error #12: it END LOOP
-- error #13: you need to terminate the statement with a ;
if sum_ > max_ then
return 0;
else
return 1;
end if; -- error #14: an END if is required
END;
$body$
language plpgsql; -- error #14: you need to specify the language
В руководстве указано все это:
- ошибка № 1, № 2: http://www.postgresql.org/docs/current/static/sql-createfunction.html
- ошибка № 3: http://www.postgresql.org/docs/current/static/plpgsql-structure.html
- ошибка № 6: http://www.postgresql.org/docs/current/static/plpgsql-declarations.html
- ошибка # 7, # 8, # 9, # 10, # 12: http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING
- ошибка № 11: http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-ASSIGNMENT
- ошибка № 14: http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-CONDITIONALS
Весь цикл FOR не нужен и крайне неэффективен. Его можно заменить на:
SELECT sum(nofvotes)
into sum_
FROM votes
WHERE cid=scid AND bno=sbno;
Postgres имеет собственный булевский тип, лучше использовать это вместо целых чисел. Если вы объявите функцию как returns boolean, последняя строка может быть упрощена до
return max_ > sum_;
Эта часть:
select totvoters
into max_
from ballotbox
WHERE cid=scid AND bno=sbno;
будет работать только в том случае, если cid, bno уникален в камере голосования. В противном случае вы можете получить ошибку во время выполнения, если выбор возвращает более одной строки.
Предполагая, что выбор на ballotbox использует первичный (или уникальный) ключ, вся функция может быть упрощена до небольшого выражения SQL:
create function trigf1(sbno integer, scid numeric(4,0))
returns boolean
as
$body$
return (select totvoters from ballotbox WHERE cid=scid AND bno=sbno) >
(SELECT sum(nofvotes) FROM votes WHERE cid=scid AND bno=sbno);
$body$
language sql;
Ответ №1
Я не человек postgresSQL, но я бы подумал
declare max as SELECT totvoters FROM ballotbox WHERE cid=scid AND bno=sbno;
должно быть
declare max := SELECT totvoters FROM ballotbox WHERE cid=scid AND bno=sbno;
Ответ №2
Тело функции должно быть строкой после ключевого слова as, то есть as 'code...'. Обычно используется строка с кавычками в долларах:
CREATE FUNCTION trigf1(sbno integer, scid numeric(4,0)) RETURNS integer
AS $$
BEGIN
declare sum int default 0;
declare max as SELECT totvoters FROM ballotbox WHERE cid=scid AND bno=sbno;
for r as
SELECT nofvotes FROM votes WHERE cid=scid AND bno=sbno;
do
set sum = sum + r.nofvotes;
end for
if sum > max
then return(0);
else
return(1);
END
$$