Solved

MySQL: Using variable with create and insert

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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
php image upload 3 48
MySQL ERROR 1045 (28000) 2 81
Amazon Redshift 2 35
updating the date data 12 30
This guide whil teach how to setup live replication (database mirroring) on 2 servers for backup or other purposes. In our example situation we have this network schema (see atachment). We need to replicate EVERY executed SQL query on server 1 to…
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…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

803 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