2016-04-27 3 views
0

Я пытаюсь установить значение в таблицу, используя следующую хранимую процедуру.Ошибка MySQL 1146 О хранимой процедуре

Create Definer = Current_User Procedure sp_set_drivers_cost (In driver_id Int) 
Not Deterministic 
Begin 
-- Variable that will holds the driver's total cost. 
Declare driver_cost Numeric(65,2) Default 0; 
-- Declaring loop_counter and a varialbe that will hold the sum of the cost. 
Declare loop_counter, temp_table_sum Int Default 1; 
-- Variable that will hold the driver's total cost. 
Declare local_cost Numeric(65,2) Default 0; 

Declare temp1 int; 

-- Dropping table if exists. 
Drop Table If Exists MyDB.temp_policy_id; 

-- Creating temp table that will hold the policy ids that the given driver is covered for. 
Create Table MyDB.temp_policy_id (
    id int not null auto_increment, 
    policy_id int not null default 0, 
    Primary Key (id) 
); 

-- Inserting the policy ids for the given driver id; 
Insert Into MyDB.temp_policy_id(policy_id) 
Select fk_policy_id 
From link_drivers_policies 
Where fk_driver_id = driver_id; 

-- Counting the rows of the temp table. 
Set temp_table_sum = (Select Count(*) From temp_policy_id); 

-- Looping through the rows of the table in order to get the total cost for each driver. 
While loop_counter <= temp_table_sum Do 
    Set temp1 = (Select policy_id From temp_policy_id Where id = loop_counter); 
    -- Getting the total cost, for the given driver, based on the policies they are covered by. 
    Set local_cost = local_cost + (Select cost From policies Where id = temp1); 

    -- Incrementing the loop counter by 1. 
    Set loop_counter = loop_counter + 1; 
End While; 

-- Updating the drivers cost. 
Update MyDB.drivers 
Set cost = local_cost 
Where id = driver_id; 

Drop Table MyDB.temp_policy_id; 
End// 

Когда я пытаюсь проверить процедуру, вызвав ее как «вызова sp_set_drivers_cost» Я получаю следующее сообщение об ошибке: вызов sp_set_drivers_cost (1) Код ошибки: 1146. Таблица «MyDB.MyDB» не существует 0,437 сек.

Я пробовал решения childinsh, например, с переменными, которые возвращают числовые значения, опускают имя базы данных и перезапускают сервис MySQL (я нахожусь в Windows 7). Кроме того, временная таблица, которую я создаю в рамках процедуры, существует в базе данных. Поэтому я предполагаю, что ошибка происходит в цикле или во время инструкции «Обновить». Я использую InnoDB. Спасибо.

UPDATE При попытке обновить таблицу «драйверы» я также получаю ту же ошибку.

Я попытался реализовать решение опубликовано here, как указано @Norbert van Nobelen, но безрезультатно. Кроме того, я хотел бы указать, что я использовал вкладку для отступов моего кода в разделах, где я написал остальные хранимые процедуры, и никаких ошибок там, где они присутствуют.

+0

Вы используете 'tab' или' space' для отступов кода? –

+0

@Norbert van Nobelen Да, я это сделал. – SMesa

+0

Вкладка или пробел есть или или ответ: Да, я сделал: я до сих пор не знал, что вы использовали .... –

ответ

0

Поскольку неясно, откуда возникла проблема, вы попали в ситуацию «Почему нет отладки для хранимых процедур».

Для отладки хранимой процедуры, которая компилирует хорошо, а затем не работает, вы можете использовать два подхода:

  • Добавить лесозаготовительные строки в процедуру
  • разобрать его и запустить его шаг за шагом

Вариант 1: Добавить лесозаготовительную линия

Поскольку регистрация линия просто SELECT заявления. Это вызвано в командной строке при вызове процедуры. Например:

Create Definer = Current_User Procedure sp_set_drivers_cost (In driver_id Int) 
Not Deterministic 
Begin 
-- Variable that will holds the driver's total cost. 
Declare driver_cost Numeric(65,2) Default 0; 
-- Declaring loop_counter and a varialbe that will hold the sum of the cost. 
Declare loop_counter, temp_table_sum Int Default 1; 
-- Variable that will hold the driver's total cost. 
Declare local_cost Numeric(65,2) Default 0; 

Declare temp1 int; 

-- Dropping table if exists. 
Drop Table If Exists MyDB.temp_policy_id; 

-- Creating temp table that will hold the policy ids that the given driver is covered for. 
Create Table MyDB.temp_policy_id (
    id int not null auto_increment, 
    policy_id int not null default 0, 
    Primary Key (id) 
); 
SELECT "Step 1 finished"; 
... 

Таким образом, вы можете следить за тем, что выполнено, а что нет.

Вариант 2: Возьмите процедуру обособленно шаг за шагом

Это похоже на логах исключением того, что вы бы повторно создать процедуру для каждого шага у вас есть:

Create Definer = Current_User Procedure sp_set_drivers_cost (In driver_id Int) 
Not Deterministic 
Begin 
-- Variable that will holds the driver's total cost. 
Declare driver_cost Numeric(65,2) Default 0; 
-- Declaring loop_counter and a varialbe that will hold the sum of the cost. 
Declare loop_counter, temp_table_sum Int Default 1; 
-- Variable that will hold the driver's total cost. 
Declare local_cost Numeric(65,2) Default 0; 

Declare temp1 int; 

-- Dropping table if exists. 
Drop Table If Exists MyDB.temp_policy_id; 

-- Creating temp table that will hold the policy ids that the given driver is covered for. 
Create Table MyDB.temp_policy_id (
    id int not null auto_increment, 
    policy_id int not null default 0, 
    Primary Key (id) 
); 
END; 

CALL temp_policy_id; 

, а затем следующая деталь:

Create Definer = Current_User Procedure sp_set_drivers_cost (In driver_id Int) 
Not Deterministic 
Begin 
-- Variable that will holds the driver's total cost. 
Declare driver_cost Numeric(65,2) Default 0; 
-- Declaring loop_counter and a varialbe that will hold the sum of the cost. 
Declare loop_counter, temp_table_sum Int Default 1; 
-- Variable that will hold the driver's total cost. 
Declare local_cost Numeric(65,2) Default 0; 

Declare temp1 int; 

-- Dropping table if exists. 
Drop Table If Exists MyDB.temp_policy_id; 

-- Creating temp table that will hold the policy ids that the given driver is covered for. 
Create Table MyDB.temp_policy_id (
    id int not null auto_increment, 
    policy_id int not null default 0, 
    Primary Key (id) 
); 

-- Inserting the policy ids for the given driver id; 
Insert Into MyDB.temp_policy_id(policy_id) 
Select fk_policy_id 
From link_drivers_policies 
Where fk_driver_id = driver_id; 
END; 

CALL temp_policy_id; 

И т.д. пока не появится ваша ошибка. Большую часть времени, когда точно известна линия с проблемой, решение становится более понятным.

+0

Мне удалось решить проблему по вашему предложению, проверив ее до проблемного триггера. Спасибо. – SMesa

0

В Windows MySQL должен игнорировать регистр, поскольку он использует файлы и каталоги для таблиц и баз данных. И Windows игнорирует случай. То есть CREATE TABLE lcase... и CREATE TABLE LCASE... не могут сосуществовать в Windows.

Изменение lower_case_table_names прошу о проблеме.

Смежные вопросы