Solved

MySQL: Using variable with create and insert

Posted on 2014-01-24
1
323 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
selecting date modified field from a table 2 52
MySQL  on Tomcat 8 68
sql_mode 1 30
Select Query - Group By Function Producing Unexpected Results 8 29
Introduction In this article, I will by showing a nice little trick for MySQL similar to that of my previous EE Article for SQLite (http://www.sqlite.org/), A SQLite Tidbit: Quick Numbers Table Generation (http://www.experts-exchange.com/A_3570.htm…
I have been using r1soft Continuous Data Protection (http://www.r1soft.com/linux-cdp/) for many years now with the mySQL Addon and wanted to share a trick I have used several times. For those of us that don't have the luxury of using all transact…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
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…

840 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