Ask Your Question
1

How can I import a csv file into MySQL so that a column with a varchar data type is loaded as numeric data type?

asked 2023-01-03 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-06-23 00:00:00 +0000

huitzilopochtli gravatar image

To import a CSV file into MySQL and load a column with a varchar data type as a numeric data type, you can use the following steps:

  1. Create a new table with the desired column data types, including the column you want to load as numeric data type.

  2. Open your MySQL command prompt and navigate to the directory where your CSV file is saved.

  3. Use the LOAD DATA INFILE statement to import the CSV file into your MySQL table.

  4. In the LOAD DATA INFILE statement, use the SET clause to specify the data types for each column, including the column you want to load as numeric data type. For example, if your CSV file has three columns (id, name, amount) and the amount column needs to be loaded as a numeric data type, you can use the following syntax:

LOAD DATA INFILE 'yourfile.csv' INTO TABLE yourtable FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS (id, name, @amount) SET amount = CAST(@amount AS DECIMAL);

In this example, the @amount variable is used to load the amount column as a varchar data type. The CAST function is then used to convert the @amount variable to a decimal data type and load it into the amount column in the MySQL table.

  1. Press enter to execute the LOAD DATA INFILE statement and import the CSV file into your MySQL table.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-03 11:00:00 +0000

Seen: 9 times

Last updated: Jun 23 '21