Skip to content
Advertisement

MySQL – surrounding precomputed variable with single-quotes prior to inserting

The primary key of my table is a char of fixed length 11.

I have precomputed the key in my script, just like this:

SET pes = LPAD(person_number, 11, '0');

Now, my variable meets my critera. It only needs to be added to the database.

INSERT INTO db VALUES(pes, ...);

This is where my problem arises – since the primary key is supposed to be a char, I need to put the value of my variable in single quotes.

However, I don’t know how to do that. I tried to escape them, but

'''pes'''

doesn’t work.

Is there a simple way to accomplish that?

Advertisement

Answer

This should not be a problem !

The mySql varchar data-type should accept numbers!

CREATE TABLE USERS (USER_ID VARCHAR(255) NOT NULL UNIQUE PRIMARY KEY,
                    USER_NAME VARCHAR(255));
SET @U_ID = LPAD(2018, 11, '0');
INSERT INTO USERS VALUES (@U_ID, 'USER_1'),(2, 'USER_2');

SELECT * FROM USERS;

Will output :

USER_ID      |  USER_NAME
-------------------------
00000002018  |  USER_1
2            |  USER_2

This is a working fiddle

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement