Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel escaping quotes or apostrophes in cell values

Tags:

I get a lot of database information from clients in excel spreadsheets. I frequently need to insert/update this data back into the database.

I often use excel to generate the insert and update statements via concatenating a bunch of cells together. Sometimes the data includes text cells which can have single quotes in them. If not dealt with carefully, these single quotes will make the SQL statements break.

How can I escape single quotes in text data, via formulas, when concatenating a bunch of cell values together, so that my resulting SQL scripts are valid?

like image 764
Mir Avatar asked Sep 26 '14 19:09

Mir


People also ask

Why does the apostrophe disappear in Excel?

Answers. An apostrophe at the beginning of a cell value is an indicator that the value should be treated as text even if it looka like a number or a date. Such an apostrophe will not be displayed. If you want to display an apostrophe at the beginning of a cell value, type two apostrophes.

Why does Excel add quotation marks?

Microsoft Excel uses double quotation marks to signify text within formulas. When it sees these marks, it uses the text and discards the quotes. Typing quotation marks directly into a cell is not an issue because Excel automatically recognizes that you are entering text and therefore keeps the quotation marks.

How do I enclose all single quotes in Excel?

To insert single quotes around the cell values, please apply this formula: ="'" & A1 & "'".


1 Answers

The best solution I have found is to use the following:

=SUBSTITUTE(A1, "'", "''") 

This will replace all single quotes with two single quotes which, in T-SQL statements escapes the character and treats it as string data.

like image 190
Mir Avatar answered Nov 13 '22 19:11

Mir