Solved

MySQL: Using variable with create and insert

Posted on 2014-01-24
1
325 Views
Last Modified: 2014-01-26
How can I use a variable with "create" and "insert" statements?

This does not work:
SET @now := (SELECT DATE_FORMAT(NOW(),'tbl_%Y_%m_%d_%H_%i'));
CREATE TABLE (SELECT @now) LIKE tbl;
INSERT (SELECT @now) SELECT * FROM tbl;

Open in new window

0
Comment
Question by:hankknight
1 Comment
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39807402
You'll need to CONCAT the variable into a statement and then execute that:

SET @newTable := (SELECT DATE_FORMAT(NOW(),'tbl_%Y_%m_%d_%H_%i'));

SET @sql := CONCAT('CREATE TABLE ', @newTable,' LIKE tbl');
PREPARE stmt FROM @sql; 
EXECUTE stmt;

SET @sql := CONCAT('INSERT INTO ', @newTable, ' SELECT * FROM tbl');
PREPARE stmt FROM @sql; 
EXECUTE stmt;

Open in new window

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction In this installment of my SQL tidbits, I will be looking at parsing Extensible Markup Language (XML) directly passed as string parameters to MySQL 5.1.5 or higher. These would be instances where LOAD_FILE (http://dev.mysql.com/doc/refm…
This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question