Have you used Set Term before and after this code?
All commands in Firebird must be terminated with a semi-colon. If you want to create a stored procedure you need to be able to distinguish between the terminating semi-colon from the semi-colons inside the stored procedure.
Something like this:
Please notice how the declaration of the stored procedure is terminated with ^, thus ending the statement. After the declaration you also restore the terminating semi-colon.
On a side note, I would recommend to copy firebird.msg to the location the error you get tells you so you can see what is really happening.
EDIT:
If you wish you can check this link. There you can find a lot of information regarding Firebird + IBExpress, including SET TERM (page 81).
EDIT 2:
Just tried at home with IBExperts + Firebird and I had no problem creating the stored procedure. My guess is you are trying to do one of the following things:
You have opened an SQL editor and are trying to compile the code directly. That will not work because IBExperts thinks you are trying to run DSQL sentences. Stored procedures are created with PSQL sentences.
You are trying to use the «New procedure» utility (check buttons in the upper right side of the main menu) and pasted the whole code into the editor. That will not work because in that editor you only have to put the body code. Stored procedure name is set in a field on the upper right side of the window you opened. Parameters and variables are introduced by using the «Insert Parameter/Variable» button on the left side above the code editor. The SET TERM sentences are created automatically by IBExperts. You can check the resulting code in the DDL tab.
Источник
Problems executing SQL-script using Firebird.NET 2.5 (Error Code = -104)
Sorry for my English first of all. I have a problem and need help. I have a simple tool made by myself on c#. This tool makes connect to local or remote firebird server (v.2.5). And my tool can create specified .fdb file (database) somewhere on the server.
Also I have a file with SQL statements (create table, triggers and so on). I want to execute this file after database was created. Executing this file will fill structure of user database — not data, only structure.
But then I try to execute my SQL script — firebird server returns a
That’s the line on this CREATE TABLE SQL statement, for example:
If I will leave only one create statement in my file — all will be good. I don’t know how I explained (it’s clear or not)) — another words — why can’t I execute full query with many create statements in one transaction? There is my main method which executes query:
There is a query is my SQL file.
2 Answers 2
As Victor already stated in his final comment, you can use the FBScript class for batch execution.
I was just confronted with the same task. This question pointed me in the right direction but i had to do some further digging.
I this example, the source of the statements is a external script file:
This will work fine, but you may wonder why this whole thing isn’t surrounded by a transaction. Actually there is no support to «bind» FbBatchExecution to a transaction directly.
The first thing i tried was this (will not work)
This will result in an exception stating: «Execute requires the Command object to have a Transaction object when the Connection object assigned to the command is in a pending local transaction. The Transaction property of the Command has not been initialized.»
This means nothing more than that the commands that are executed by FbBatchExecution are not assigned to our local transaction that is surrounding the code block. What helps here is that that FbBatchExecution provides the event CommandExecuting where we can intercept every command and assign our local transaction like this:
Note that i have uncommented the myTransaction.Commit() line. I was a little bit surprised by this behavior, but if you keep that line the transaction will throw an exception stating that it has already been committed. The bool parameter fbe.Execute(true) is named «autoCommit», but changing this to false seems to have no effect.
I would like some feedback if you see any potential issues with assigning the local transaction this way, or if it has any benefits at all or could as well be omitted.
Источник
Firebird SQL: error code -104, token unknown
I have a script, below, in Ostendo (an ERP), which runs on a firebird database. The script is written in Pascal. It returns an error «Firebird SQL: error code -104, token unknown, ’13/04/2018′ at the line TMPQuery2.ExecQuery. I removed the reference text DATEWORKED = AND and it works fine. I have commented out all the other lines I tried in solving it — of which none worked.
Any ideas as to where I am going wrong? I have a feeling it is do to with date format. I have tried dd-mm-yyyy, yyyy-mm-dd (which is how it works from a OBDC through excel), dd/mm/yyyy (which is how it is displayed in ostendo).
1 Answer 1
From where did you get the idea that date literal in Firebird is represented in format like ? The legal formats to cast string data types to the DATE is listed at «Literal Formats» section in the «Conversion of Data Types» chapter.
Basically the yyyy-mm-dd format is right but it must be a simple string ie DATEWORKED = »’ + TSDateWorked + »’ when concatenating strings in pascal.
But instead of building the query as a string one should use parametrized queries. Parameters in SQL string are usually represented by name which has a colon in front of it, ie :DateWorked . So your query would look like
The query component usually also has ParamByName methods so that instead of parameter position you can assign values using the names. I don’t konw the TpFIBQuery component so the property/method names might differ, consult the help of the component.
Я себе пишу вроде мануала, чтобы была в будущем подсказка под рукой: Прокоментируйте мои действия: С isql.exe не разобрался, для создания базы данных и таблицы в ней, использовал IB/FB Development Studio.
Запустить IB/FB Development Studio Войти в Редактор Баз Данных. Создать новую базу данных Указать сервер, указать путь к файлу Открыть Базу Данных Правая кнопка мыши — создать объект (новую таблицу) Правая кнопка мыши — создать поле, если нужно добавить первичный ключ и автоинкремент (создать генератор)
—————————————————————————- Запустить Delphi2007 Создать новый проект Из вкладки InterBase добавить на форму компонент TIBDatabase Из вкладки InterBase добавить на форму компонент TIBTransaction Из вкладки InterBase добавить на форму компонент TIBDataSet Из вкладки Data Access добавить на форму компонент TDataSource Из вкладки Data Controls добавить на форму компонент TDBGrid
—————————————————————————- Настройка компонента TIBDatabase: В свойстве компонента DefaultTransaction: имя компонента TIBTransaction Двойной клик по компоненту (или правая клавиша мыши) — вызвать Database Editor Remote localhost TCP ввести путь к файлу базы данных USER: SYSDBA PASSWORD: masterkey Свойство компонента Connected =TRUE
—————————————————————————- Настройка компонента TIBTransaction: В свойстве компонента DefaultDatabase: имя компонента TIBDatabase Двойной клик по компоненту (или правая клавиша мыши) — вызвать Transaction Editor Выбрать опцию Read Committed (для чтения и записи по подтвержением) Свойство компонента Active =TRUE
—————————————————————————- Настройка компонента TIBDataSet: В свойстве компонента Database: имя компонента TIBDatabase В свойстве компонента Transaction: имя компонента TIBTransaction Двойной клик по компоненту (или правая клавиша мыши) — вызвать DataSet Editor Select Table Name: (доступны только при активных предыдущих компонентах) Select Primary Keys (либо выбрать вручную автоинкрементное поле) Update Fields: (рекомендуется снять выбор с автоинкрементного поля) Нажать кнопку «Generate SQL» Свойства компонента DeleteSQL,InsertSQL,ModifySQL,RefreshSQL автоматически заполнятся. Выбрать свойство компонента SelectSQL в Object Inspector, вызвать CommandText Editor Выбрать таблицу, ввести SQL: Select * from (имя выбранной таблицы)
В свойстве компонента GeneratorField: выбрать имя генератора, выбрать поле, применить: On New Record Свойство компонента Active =TRUE
—————————————————————————- Настройка компонента TDataSource: В свойстве компонента DataSet: имя компонента TIBDataSet: Свойство компонента Enable =TRUE
—————————————————————————- Настройка компонента TDBGrid: В свойстве компонента DataSource: имя компонента TDataSource Двойной клик по компоненту (или правая клавиша мыши) — вызвать Columns Editor Если предыдущие компоненты активны (база данных подключена), то доступна кнопка «Добавить все поля» (Add All Fields) В Дельфи, на вкладке Structure — компонент TDBGrid/Columns — выбрать столбец, задать его ширину в пикселях. Тем столбцам, которые не надо показывать — сделать Visible=FALSE (либо удалить из списка в столбцов в Columns Editor)
————————————————————————————————————————— К сожалению, для информации у меня только книга Архангельского «Программирование в Delphi7» и интернет, поэтому будет много вопросов:
Вообщем, база данных подключилась. В базе данных Character Set = UNICODE_FSS (хочу и на русском и на европейских языках писать) Если ввожу в текстовые поля английские символы — всё нормально, если ввожу русские — выдает ошибку «malformed string».
Далее, хочу создать программку, в которой можно самому программно создавать таблицы с полями. Программный код создания таблицы отсюда: http://ibase.ru/devinfo/ibx.htm create table X (id int not null, name varchar(30), constraint PK_X primary key (id));
Мои вопросы — куда этот код вставлять? И как добавлять новые поля? Что это за ошибка «malformed string» (как от этого избавиться)?
В компоненте IBDatabase обнаружил UTF8, а вот в А вот в IB/FB Development Studio в свойствах базы данных только можно выбрать — UNICODE_FSS (UTF8 не обнаружил).
Как же быть?
Всего записей: 137 | Зарегистр. 12-07-2004 | Отправлено:20:37 22-06-2009
скачай лучше IBExpert он на русском и для жителей бывшего СНГ бесплатен
ОПА: (http://www.ibase.ru/unicode_faq.html) IBExpert не является unicode-приложением
15th June 2009 IBExpert new version with full Unicode support )) ХАРАШО!
Добавлено: Скачал IBExpert. Запустил. Создаю новую базу. Тест не работает — ругается! user name и password у меня по дефолту (SYSDBA|masterkey) и чего не так?
Unsuccessful execution caused by a system error that precludes successful execution of subsequent statements. Your user name and password are not defined. Ask your database administrator to set up a Firebird login.
Test: Attempting to connect to: localhost:C:\myBD\BD3.fdb
Connecting. Failed! ———————————— Unsuccessful execution caused by a system error that precludes successful execution of subsequent statements. I/O error during «CreateFile (open)» operation for file «C:\MYBD\BD3.FDB». Error while trying to open file. The system cannot find the file specified. .
Attempting to connect to services manager. Passed!
Disconnecting from database. Passed!
Я так понимаю, что файла этого нет, а разве он его сам не создает?
—————————————————————- С этим разобрался. Надо было сначала базу данных создать, а уже потом ее регистрировать. Поспешишь — людей насмешишь (опять!): Error Message: —————————————- Unsuccessful execution caused by a system error that precludes successful execution of subsequent statements. Your user name and password are not defined. Ask your database administrator to set up a Firebird login.
Добавлено: странно, в одном случае сервер (local), в другом localhost (надо самому вводить)
Не могу создать таблицу в базе данных (эти опции не активны в меню), предположительно это из-за ошибки доступа — не может подсоединиться, только почему я не пойму! Чисто административные проблемы, наверное, не люблю я такие проблемы — совсем это не программирование!
Всё заработало. Перезагрузка ноутбука помогла. В IBExpress теперь в новой базе данных создал таблицу с полями. Кодировка везде UTF8.
При подключении базы данных в Дельфи, пришлось использовать новый IBDataSet, так как в предыдущем были настройки на предыдущую базу данных, и генератов автоинкремента ключевого поля. А новый компанент выдает ошибку при попытки его активации:
Добавлено: Объясните, если возможно, почему в IBExpert регистрируешь базу данных, тестируешь — ОК: ——————————- (Attempting to connect to: LOCALHOST:C:\myBD\BD4.fdb Connecting. Passed! Server version: WI-T6.3.0.23247 Firebird 2.5 Beta 1 Attempting to connect to services manager. Passed! Disconnecting from database. Passed! ——————————-
А когда пытаешься подключиться к базе данных, то выдает ошибку: —————————— Error Message: Unsuccessful execution caused by a system error that precludes successful execution of subsequent statements. Your user name and password are not defined. Ask your database administrator to set up a Firebird login.
(перевод: Неудачное выполнение, вызванное ошибкой системы, которая устраняет успешное выполнение последующих утверждений. Ваше имя пользователя и пароль не определены. Попросите, чтобы Ваш администратор базы данных настроил логин Firebird.) С чего бы это!? Но ведь и user и password — введены регистрационную информацию! И тестовое подключение проходит успешно! Что за чушь!?
Добавлено: Понял! Ошибка появляется, когда выставляешь галочку: Trusted authentication — снимаешь галочку — подключается без ошибки, с галочкой — ошибка! Только почему?!
Открыть таблицу. Перейти на закладку поля. Правой клавишей нажать на нужное поле. Выбрать пункт меню «Удалить поле. «
Всего записей: 713 | Зарегистр. 31-03-2006 | Отправлено:15:03 24-06-2009
Kursist
Junior Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору Правый клик мышкой по полю. В popup-меню: New Filed Edit Field Drop Field Create Foreign Key.. Reorder Fields Copy Fields list to clipboard
Нет у меня «Delete Field»!
Если бы это было так очевидно, я бы не спрашивал.
Во вкладке DDL хотел удалить строку создания поля, в команде создание таблицы, но не разрешает..
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору Kursist 1. Если не открыт Эксплорер БД — нажать F11. 2. В нем (обычно он слева), в списке таблиц, найти нужную. 3. В списке полей, правый клик, в меню «Удалить поле» или нажать Ctrl-Del.
Если поле только одно, то удалить его таким образом нельзя.
P.S. А какая версия IBExperta ?
Всего записей: 1696 | Зарегистр. 13-10-2005 | Отправлено:15:53 24-06-2009
Kursist
Junior Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору data man
IB Expert — The Most Expert for InterBase, Firebird and Yaffil Copyright (C) 2000-2009 IBExpert KG All rights reserved.
Полей несколько. Команды «удалить поле» — НЕТ!
Цитата:
В popup-меню: New Filed Edit Field Drop Field Create Foreign Key.. Reorder Fields Copy Fields list to clipboard
+ не реагирует.
Всего записей: 137 | Зарегистр. 12-07-2004 | Отправлено:16:06 24-06-2009
Всего записей: 137 | Зарегистр. 12-07-2004 | Отправлено:16:08 24-06-2009
data man
Advanced Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору Kursist Может стоит переключить интерфейс IBExperta’а на русский ? P.S. Здесь cсылка лежит более новый перевод, чем в инсталле.
Всего записей: 1696 | Зарегистр. 13-10-2005 | Отправлено:16:25 24-06-2009 | Исправлено: data man, 16:38 24-06-2009
Kursist
Junior Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору data man в настройках язык интерфейса только English (Default)
Ещё вопрос: У меня по закрытию формы проиходит отсоединение от базы данных: IBDatabase1.Close; А почему в Дельфи, по возвращению в среду IBDatabase1.Connected=TRUE , это свойство не должно переходить в FALSE?
Добавлено: IBExpert Опять натолкнулся на проблему: Пытаюсь связать 2 таблицы (ORDERS и CLIENTS),
This operation is not defined for system tables. unsuccessful metadata update. could not find UNIQUE or PRIMARY KEY constraint in table CLIENTS with specified columns.