Solved

MySQL: Using variable with create and insert

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

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

757 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now