1

I'm trying to create a database named 'uppg' and then use that database once it's created. The first statement executes as it should, but nothing happens when I try to use the database with the variable. I have tried multiple variations but I don't know why it's not working.

SET @dbname = 'uppg';

SET @q1 = CONCAT(
'CREATE DATABASE `', @dbname, '`');
PREPARE stmt1 FROM @q1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

SET @q2 = CONCAT(
'USE ', @dbname,
);

PREPARE stmt2 FROM @q2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;

1 Answer 1

2

There exists complete list of statements allowed in PREPARE: SQL Syntax Permitted in Prepared Statements.

USE is not mentioned in it. So you cannot alter current database using dynamic SQL.

The simplest solution: use complete tables names (including database name) in your queries. In this case the current DB can be any (but not none) - this won't effect your queries.

Sign up to request clarification or add additional context in comments.

1 Comment

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.