Ошибка синтаксиса примерное положение begin

I use PostgreSQL 12

I have the following two tables:

table_a:

table_a_id   |   version 
1            |     v1
2            |     v1
3            |     v1
4            |     v2
5            |     v2
6            |     v2

table_b:

table_b_id   |   version   |  table_a_id
1            |     v1      |     1  
2            |     v1      |     2         
3            |     v1      |     3  
4            |     v2      |     4  
5            |     v2      |     5  
6            |     v2      |     6 

table_b must reference same version table_a_id
i.e The below data is valid entry because table_a_id -> 1 belongs to version ‘v1’

table_b_id   |   version   |  table_a_id
1            |     v1      |     1  

But the below data is invalid entry because table_a_id -> 4 belongs to version ‘v2’

table_b_id   |   version   |  table_a_id
1            |     v1      |     4  

I am new to Postgres trigger functions

I have created the following trigger function to validate ON BEFORE INSERT OR UPDATE to table_b:

CREATE FUNCTION version_check() 
    RETURNS TRIGGER AS 
$BODY$
  BEGIN
    IF NOT EXISTS (
      SELECT
        *
      FROM
        "table_a"
      WHERE
        "table_a"."table_a_id" = NEW."table_a_id"
      AND
        "table_a"."version" = NEW."version";
    )
    THEN
      RAISE EXCEPTION 'table_a and table_b Version do not match';
    END IF;

    RETURN NEW;
  END;

$BODY$
LANGUAGE plpgsql;

CREATE TRIGGER "version_check" BEFORE INSERT OR UPDATE ON "table_b"
  FOR EACH ROW EXECUTE PROCEDURE version_check();

I am getting the following error on saving the Trigger function in pgAdmin 4

ERROR: syntax error at or near "BEGIN"
LINE 8: BEGIN
^

Am i doing any syntax error? Also will the above trigger function work fine for my requirement ?

Thanks in advance!

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

Alex V's user avatar

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 Brandstetter's user avatar

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 (Все метки)


Напишите процедуру на ввод записей о преподавателях ВГУ. Идентификационные номера преподавателей должны вводится в порядке возрастания.
Мое решение:

SQL
1
2
3
4
5
6
CREATE OR REPLACE FUNCTION insert_lect(INTEGER, text, text, text, INTEGER) RETURNS text
AS $$ DECLARE id_lect ALIAS FOR $1
BEGIN INSERT INTO lectures(recturer_id, surname, name, city, univ_id) VALUES(id_lect, $2, $3, $4);
RETURN id_lect;
END;
$$ LANGUAGE 'plpgsql';

но выдает:»ошибка синтаксиса (примерное положение: «begin»)»
хехе не очень хорошо понял тему про функции))

Ввод записей в pgAdmin

Вот таблица.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

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 настройка
Добрый день. Такой вопрос возник:
поставил PostgreSQL 9.3 и pgAdmin III. Из под консоли работаю с…

Распределенная БД в pgAdmin
Подскажите пожалуйста. Как создать распределенную базу данных в pgAdmin III? Если можно, на примере…

Ограничить ввод определенных записей в форме
У меня есть таблица ПоступлениеКниги: КодКниги, Название и КоличествоЭкземпляров данной книги при…

Организовать ввод, хранение и сортировку записей
Имеется информация о сотрудниках отдела: ФИО, должность, оклад, стаж. Организовать ввод, хранение и…

Изменение и ввод записей непосредственно в DBGrid
Здравствуйте, есть бд созданная в firebird 2.5 и делфи 2010, на форме дбгрид, привязанный к бд…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

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
$$
  • Remove From My Forums
  • Question

  • Hello ,

    I am getting this error. Whats the issue?

    begin

    if 

      not exists(select 1 from dbo.Dashboard where Effective_Date=@cut_date)

    begin

    INSERT INTO dbo.dashboard (

            [Effective_Date]

           ,[Invoice_gen]

           ,[unclaimed_payments]

           ,[Tot_Payments_received]

           ,[tdu_charge]

           ,[payments_received]  

           ,[meter_cnt_active] 

      ,[meter_cnt_cancelled]

           ,[meter_cnt_churn]

      ,[meter_cnt_intransit]

           ,[ag_tot_unstat]

           ,[ag_active_unstat]

           ,[ag_inactive_unstat]

    select 

            @cut_date 

           ,@invoice_gen

           ,@unclaimed_payment

           ,@payment_received

           ,@tdu_charge

           ,@coll_payment_received

           ,@meter_active

           ,@meter_Cancelled

           ,@meter_churn

           ,@meter_intransit

           ,tot_cte.tot_unstat

           ,tot_cte.active_unstat

           ,tot_cte.inactive_unstat

    FROM ecp_tot_cte 

       CROSS JOIN tot_cte  

    end

    Please help.

    Thanks

Answers

  • Since there is no variable declarations in the code you posted, and there are variables in the batch, you did obviously not the post the full batch. I guess the error is in the part you did not post.

    If you post the complete code, please also post the complete error message. The full error message includes a line number. That information is valuable.

    Also, please use the squiggly button in the web UI to post code. It is not particularly amusing to read code where every second line is blank.


    Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

    • Marked as answer by

      Thursday, January 19, 2012 3:35 PM

    • Edited by
      Naomi N
      Friday, January 6, 2012 4:10 PM
    • Marked as answer by
      Kalman Toth
      Thursday, January 19, 2012 3:35 PM
  • You really like derived tables, don’t you… It make the entire thing quite unreadable.

    Others have already pointed out the obvious syntax error. You are not using the CTEs immediately following their declaration, which is mandatory.

    I notice you are not using recursion in your CTEs. That means that you could rewrite them as views (not in your stored procedure, but permanent). You can access views whenever you want, also in your current «if» or «else» block.

    The same is true for many of your derived tables. With smart naming, turning them into views would make your code must more readable, and because of that better to maintain.


    Gert-Jan

    • Proposed as answer by
      Naomi N
      Friday, January 6, 2012 9:55 PM
    • Marked as answer by
      Kalman Toth
      Thursday, January 19, 2012 3:34 PM

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»;

SitePoint Forums | Web Development & Design Community

Loading

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка система vac не смогла проверить игровую сессию
  • Ошибка синтаксиса при установке apk как исправить
  • Ошибка система trc выключена тойота
  • Ошибка синтаксиса около неожиданной лексемы newline

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии