0

I'm trying to set a database name for a MySQL query. I've been able to get my first query to work, but the second I'm struggling to figure out where my syntax error is. I'm guessing it has something to do with the variable, but I'm stuck.

SET @db = CONCAT('SELECT client_databases.database_name
FROM client_databases
JOIN jobs ON jobs.organisation_id = client_databases.organisation_id
WHERE jobs.transaction_reference="K01-REC0000001"');

SET @q = CONCAT('SELECT receipts_lines.id, product_code, product_name, receipts_lines.is_putaway
    FROM ', @db ,'.receipts
    JOIN ', @db ,'.receipts_lines ON receipts_lines.receipt_id = receipts.id
    WHERE reference_number="K01-REC0000001"');

PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
2
  • What's the database name? You are using a whole query as the value of @db. Commented Jan 12, 2020 at 15:11
  • yes, the whole query as the value. Commented Feb 1, 2020 at 2:31

1 Answer 1

1

You should do something like this. Where you select into @db the databasename and use this to build your stmt

SELECT client_databases.database_name INTO @db
FROM client_databases
JOIN jobs ON jobs.organisation_id = client_databases.organisation_id
WHERE jobs.transaction_reference="K01-REC0000001";

SET @q = CONCAT('SELECT receipts_lines.id, product_code, product_name, receipts_lines.is_putaway
    FROM ', @db ,'.receipts
    JOIN ', @db ,'.receipts_lines ON receipts_lines.receipt_id = receipts.id
    WHERE reference_number="K01-REC0000001"');

PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.