Showing posts with label quotes. Show all posts
Showing posts with label quotes. Show all posts

Friday, March 23, 2012

How do I insert a string value with quotes into a nvarchar column

I am reading data from another data source and storing it in the sqlce database. Some of the string values I'm trying to insert into the database have single quotes in the string (i.e. Johnny's Company). When I try to insert the values with the single quotes, it throws an exception. The code I use to insert the records is as follows:

cmd.CommandText = "INSERT sy_company " +

" (company_id, company, co_name, companyid) " +

"VALUES(" +

"'" + dtSYCompany.Rows[x]["company_id"] + "'," +

"N'" + dtSYCompany.Rows[x]["company"] + "'," +

"N'" + dtSYCompany.Rows[x]["co_name"] + "'," +

"'" + dtSYCompany.Rows[x]["companyid"] + "')";

cmd.ExecuteNonQuery();

When the company name (co_name) has a single quote in it, I get the error. How do I write the insert statement so it will work even though the value being inserted into co_name has a single quote in it?

Thanks so much!

Use parameters. It’s also great for performance and security.

By the way, it appears you’re using DataTable. In that case you could use DataAdapter.Update() instead of running commands manually. CommandBuilder can generate parametrized command for you.

|||That did it!!! Thanks so much.

Wednesday, March 21, 2012

How do I handle single quotes in data fields

I want to set company name in table company to "Don's Autoworks". When I run
a simple query:
update company
set company_name = 'Don''s Autoworks'
where id = 125
Server: Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 's'.
However, select queries with 2 single quotes like below work fine:
select * from company
where company_name = 'Mel''s Diner'
What should I do to insert or update data with single quotation marks in it.
Thanks,
Ashhad.>I want to set company name in table company to "Don's Autoworks". When I
>run
> a simple query:
> update company
> set company_name = 'Don''s Autoworks'
> where id = 125
> Server: Msg 170, Level 15, State 1, Line 2
> Line 2: Incorrect syntax near 's'.
This query should work. Where are you running it?
A|||Query Analyzer, SQL Server 2000, on Windows 2000
"Aaron Bertrand [SQL Server MVP]" wrote:

> This query should work. Where are you running it?
> A
>
>|||The query seems correct. Check it again
Madhivanansql