سؤال

I have 3 existing tables: transactions, transaction_types, and expenses:

$> USE `mydb`;

   Datebase changed.

$> SHOW TABLES;

   expenses
   transactions
   transaction_types

After adding a stored procedure and 2 triggers on expenses that call the procedure, I'm no-longer able to insert into the table:

$> INSERT INTO `expenses` SET `date`='2013-12-22';

   1109. Unknown table 'expenses' in field list

$> INSERT INTO `expenses` (`date`) VALUES('2013-12-22');

   1109. Unknown table 'expenses' in field list

But I can select from the able just fine…

If I drop the triggers, I can insert into expenses again.

My 2 triggers are duplicates, 1 for update, 1 for insert:

USE `mydb`;

DELIMITER $$

DROP TRIGGER IF EXISTS `expense_updated_paid`
CREATE TRIGGER `expense_updated_paid`
    AFTER UPDATE ON `expenses` FOR EACH ROW
    BEGIN
        CALL `expense_paid`( NEW.`id` , NEW.`date paid` , NEW.`amount`);
    END$$

And the procedure:

USE `mydb`;
DROP procedure IF EXISTS `expense_paid`;

DELIMITER $$

CREATE PROCEDURE `expense_paid`(IN `expense_id` INT, IN `date` DATE, IN `amount` INT)
    BEGIN
        IF `expenses`.`date paid` IS NOT NULL THEN
            SET @type_id = (SELECT `id` FROM `transaction_types` WHERE `name` = 'reimbursement');
            INSERT INTO `transactions`
                SET
                    `transactions`.`date` = `date`,
                    `transactions`.`amount` = `amount`,
                    `transactions`.`type_id` = @type_id,
                    `transactions`.`note` = `expense_id`;
        END IF;
    END$$

I expect MySQL to complain about something in the trigger or procedure if that's causing a problem instead of telling me the table just doesn't exist…

هل كانت مفيدة؟

المحلول

Now that you provided the procedure code, the answer is clear:

    IF `expenses`.`date paid` IS NOT NULL THEN

The procedure has no context for expenses.*. That is, you can't use qualified column names inside the procedure when the qualifier refers to a query outside the procedure. This makes more sense if you accept that column qualifiers refer to correlation names in a given query, not to the table itself.

But the procedure does have the date input parameter, which you passed as the same value NEW.\date paid``. So change the line to the following:

    IF `date` IS NOT NULL THEN
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top