0

I'm using variables to store values onto table.

f_nm holds first name and l_nm holds last name of the person.

What if these strings for first name or last name contain a single quote ( ' )? I've been encountered to an error right now which indicates error near ' .

How do I write an insert query for inserting first name and last where

f_nm = Kevin
l_nm = O'Brien

Here is an example of the code causing the error (pasted from comment):

INSERT INTO Person VALUES ( ' " + f_nm + " ' , ' " + l_nm " ' ) "
5
  • 2
    You should be using parameters, and then quotes and such is not a problem. Don't use string concatenation to build up SQL with both SQL statements and values, this is a recipe for disaster. Commented Jul 3, 2020 at 13:34
  • Why would an apostrophe be affecting you, unless you were using string concatenation to build your INSERT statement? Can you post more code please? Commented Jul 3, 2020 at 13:35
  • INSERT INTO Person VALUES ( ' " + f_nm + " ' , ' " + l_nm " ' ) " I'm executing it through a Windows Form Application. Commented Jul 3, 2020 at 13:40
  • Escape the ' in SQL. Two single quotes escape the single quote in SQL Server. Use parameters if inserting from C# code though. Commented Jul 3, 2020 at 13:44
  • See for instance bobby-tables.com/adodotnet Commented Jul 3, 2020 at 13:57

1 Answer 1

3

In SQL, you would double the single quote:

insert into t (f_nm, l_nm)
    values ('Kevin', 'O''Brien');

However, if you are inserting values from an application, you should be using parameters. Parameters would not have this problem. So my advice is to use parameters.

Sign up to request clarification or add additional context in comments.

2 Comments

No sir, I'm not directly inserting values. I'm accepting values through windows text boxes, assigning those values to variables f_nm & l_nm and then using those variables to information onto table.
Then you should use parameters. learn.microsoft.com/en-us/dotnet/api/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.