MySQL Creating temporary table syntax error - mysql

I am getting a syntax error when I run a MySQL statement.
I know backticks can be added to the tablename to make it work but was wondering why it happens in the first place.
Create temporary table 6514202534e1b20f0d6331 (user_id INT (10)) ENGINE=HEAP;
If I put this in Mysql Query Browser it treats the table name as two seperate words - 6514202534e1 and b20f0d6331.
The table name is generated dynamically and I haven't had a problem with this before, so I was wondering why it stopped working all of a sudden.

I think this is because the server (mysql) understands it in this case as 6514202534*e^1 INT.
Using the ` character:
CREATE TEMPORARY TABLE `6514202534e1b20f0d6331` (user_id INT (10)) ENGINE=HEAP;
In this way the MySQL Server understands (explicitly) that the whole phrase is database, table or field not a value or function, etc.
For example `order` is legal while just order will rise an error for invalid order clause.

Related

Error when adding column with numeric name

I currently have a MariaDB database with columns named after dates : 20200105, 20200914 etc.
If I try to add a column using ALTER TABLE dates ADD COLUMN IF NOT EXISTS (test VARCHAR(255));, it works and the test column is created.
If I type ALTER TABLE dates ADD COLUMN IF NOT EXISTS (20201205 VARCHAR(255));, though (so, with a number replacing "test"), the creation does not work anymore and MariaDB tells me that there is an error with my SQL syntax.
I have tried to put quotes around the column name, but that does not work (not even with "test").
Is there something obvious I am missing ?
Use backticks to escape the column name:
ALTER TABLE dates ADD COLUMN IF NOT EXISTS (`20201205` VARCHAR(255));
But really best practice frowns upon the use of naming your database objects with mandatory backticks. The reason for using a name like 20201205 as a column name is that you will forever be needing to escape it using backticks. Also, from a data design point of view, your data should grow with new dates in terms of increasing the number of records, not columns.

Create Table in SQL where table name is from digits

When I try do next
mysql> CREATE TABLE '20181020';
sql return an error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MariaDB server version for the right syntax to use
near ''20181020'' at line 1
How can I solve it?
You needt to wrap identifier with backticks:
CREATE TABLE `20181020`(id INT);
I propose not to do so and use proper meaningful naming. Using date as name of table suggest that it could be table-per-date antipattern.
Related article: SELECT * FROM sales + #yymm
your can also use double quote for this type of table name
CREATE TABLE "20181020" (id INT);
insert into "20181020" values(1)
But this type of naming is not standard practice
The other answers cover the solution, which is to use backticks.
Let me add that using non-standard identifiers is a bad idea. If you start naming columns as number as well, who wants to figure out the differences between 20181020.1, 20181020.1, and 20181020.1. Is it so hard to use a prefix: t_20181020?
But you don't want to do that either. Let me explain. Presumably, if you have one table called 20181020, then tomorrow you will want another table 20181021. This is a really bad database design.
You should be putting all the data into a single table, with a date column specifying the date. You can then run queries over one table to see changes over time -- for instance.
If the tables are large and you want the ability to manipulate each day separately, then you use table partitioning to store each day's worth separately. This is handy, because partitions can be archived, restored, and dropped independently of other partitions.

create autoincrement in MySQL with pre text

I have trouble for my project using mysql, i want to create Auto Increment in view table, i create sintax like this one:
SELECT
concat(#AI:= #AI + 1,`code`)
FROM
`TEST TABLE`, (SELECT #AI:=0) as `AI`
Why if i add syntax in first line like this one:
CREATE VIEW `TEST VIEW` as
I have some error :
How fix it, or other method for this?. thanks for advance!
If you were using Oracle, you would use an object called a sequence for this purpose. But, who has the money for Oracle licenses?
If you need a series of numbers and you're using the MariaDB fork, you can do
SELECT seq FROM seq_0_to_99
or some such use of the SEQUENCE engine.
If you need persistent sequence numbers in MySQL, here's a workaround. It's a kludge: If you create the following table:
CREATE TABLE sequence ( /*MySQL*/
sequence_id BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`sequence_id`)
)
Then issue these three queries one after the other:
INSERT INTO sequence () VALUES (); /*MySQL*/
DELETE FROM sequence WHERE sequence_id < LAST_INSERT_ID();
SELECT LAST_INSERT_ID() AS sequence;
The third query is guaranteed to return a unique sequence number. This guarantee holds even if you have dozens of different client programs connected to your database. (The DELETE query merely keeps this otherwise pointless table from taking up too much space.)
The error message you received makes it clear that you can't use a session variable in a view.
https://dev.mysql.com/doc/refman/5.7/en/create-view.html says:
A view definition is subject to the following restrictions:
The SELECT statement cannot refer to system variables or user-defined variables.
You can't create a view for your query. You'll have to execute the query directly. The only other suggestion I can make is to develop a stored procedure for the query.
It sounds like you want to create a row number for a query result, not an auto-increment column to store in the table.
MySQL 8.0.2 has added the window function ROW_NUMBER(), but 8.0 is still under development as we're writing this. Perhaps in 2018 it will be finished and released as GA.

how to remove special characters from mysql field name

After importing an Excel table that contained some special characters (like carriage returns or line feeds) in the headers row, it seems that the phpMyAdmin utility handled this situation silently by inserting those chars in the field's name.
The problem arose later when I tried to import the table into other environments/tools like data integrators, etc. For example, the column "Date Start" was imported into the table as "Date\nStart", with a LINE FEED in the middle.
The field rename operation through phpMyAdmin fails with this error:
**\#1054 - Unknown column 'Date Start' in 'mytable'**
The obvious workaround would be to edit the original Excel file by hand (removing LF's) then reimporting the table in MySql as before, but I'm in the position of needing to refresh the schema while preserving the data in the table.
Next I tried this from an SQL panel in phpMyAdmin (note the \n in the field name, VARCHAR(16) is just an example, DATETIME or INT should work as well):
ALTER TABLE mytable CHANGE `Date\nStart` `Date Start` VARCHAR(16)
but again it gives error #1054 - Unknown column 'Date\nStart' in 'mytable'
I also checked the INFORMATION_SCHEMA db, but as #Steve stated below, it's a read-only database.
I'm using MySql 5.5.32 and phpMyAdmin 4.0.4.1 with a Win7 desktop. Any suggestions?
First of all, by reading the MySql manual you can appreciate (or hate) the extreme flexibility allowed by the naming rules, details on the special characters that are/aren't allowed in a table and column names can be found in this manual page:
https://dev.mysql.com/doc/refman/5.5/en/identifiers.html
After several attempts escaping the CR character I've found a solution that works from the phpMyAdmin SQL pane, I think it should work on command-line sessions as well (didn't try that).
In case you inadvertently created or imported columns with CR's in the name, it is possible to fix it by typing the ENTER key within the column name, inside the SQL ALTER TABLE statement (you MUST enclose names in backticks for this trick to work).
Example: To replace the unwanted 'Date\nStart' column name with 'Date Start' you should type this (please note, the CR/Enter at the end of the first line!):
ALTER TABLE mybuggytable CHANGE `Date
Start` `Date Start` VARCHAR(16)
As explained above, you can spot columns with CR's embedded with this statement:
USE INFORMATION_SCHEMA; SELECT * FROM COLUMNS WHERE COLUMN_NAME like '%\n%'
I typed the ALTER TABLE command in the my phpMyAdmin SQL pane, and it just worked fine.
I thought you couldn't write to INFORMATION_SCHEMA because of a permission issue, but after reading the MySQL Manual I realise this is expected behavior as the manual states:
Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.
To achieve a table rename by using the RENAME TABLE command, first run a select query to find all the tables that need changing and then rename them replacing the carnage return with a space character.
To rename just a column from within a table the ALTER TABLE command can be used with the CHANGE COLUMN parameters, for example:
ALTER TABLE table_name CHANGE COLUMN 'Date\nStart' 'Date Start' DATETIME
I know you've already said that is the command you need, so I've tested this myself by firstly selecting the tables and then running the ALTER TABLE command and it worked fine. I was using the command line interface, so maybe the problem lies with phpMyAdmin - can you confirm it isn't encoding or escaping \n?
Here is what I tested via the command line and worked OK:
SELECT COLUMN_NAME
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE TABLE_SCHEMA = 'test_345'
AND TABLE_NAME LIKE '%\n%';
ALTER TABLE test_table1 CHANGE COLUMN 'Date\nStart' 'Date Start' DATETIME;
Either of these could be wrapped up into a routine should you think this would be useful in the future.

How to create a temporary MySQL table with a UUID name in Coldfusion?

I'm using Coldfusion8 and MySQL 5.0.91 and am trying to create a temporary table, import some data from CSV, validate, store in database and drop the temp table.
I can do all steps in MySQL directly, where it works without a problem. However when I try to create the temp table in Coldfusion I keep getting a MySQL error.
This is what I have:
<cfset variables.tt = CreateUUID()>
<cfquery datasource="#session.datasource#">
DROP TEMPORARY TABLE IF EXISTS ##variables.tt;
CREATE TEMPORARY TABLE ##variables.tt (
tmp_kto VARCHAR(7) DEFAULT ''
, tmp_kz VARCHAR(3) DEFAULT ''
, tmp_preisliste VARCHAR(1) DEFAULT ''
, tmp_eg VARCHAR(3) DEFAULT ''
) ENGINE=MEMORY;
</cfquery>
which does not work. I also tried #variables.tt# and plain variables.tt but I keep getting the same error, while it works fine when I run the code in MySQL directly (with table name "test")
Question:
I have no clue what I'm doing wrong. Is there a max length for table names perhaps?
Thanks for some insights.
EDIT:
I get the usual error:
you have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'CREATE TEMPORARY TABLE #variables.tt (tmp_sa VARCHAR(3) DEFAULT ''
The most likely source of your problem is that the uuid is not suitable as a tablename. For one thing, it contains hyphens. I don't know if MySQL allows this, but I can't remember ever seeing hyphens in a table name.
We have a similar situation, but with redbrick. We want to create unique names for temporary tables. Our approach, written in a custom tag, is to use the string "temp" followed by a random number. We also have some try/catch stuff going on in case we get really unlucky with the random number.
I wrote that tag several years ago. If I were to do it again, I would probably replace the random number with the cftoken, cfid, and tickcount.
Also, you can't drop a table before you create it.
It looks to me you are missing the hash marks around your variable to output.
CREATE TEMPORARY TABLE ##variables.tt (
should be
CREATE TEMPORARY TABLE #variables.tt# (
The way you have it, MySQL is attempting to use the string #variables.tt (the doubled hash escapes the character in ColdFusion) when what you want is to create a temp table with the name of the value of variables.tt.