Dynamic SQL and escape characters

We have many dynamic sql stored procedures in our system

I am finding that on "search style" stored procedures I am running into issues where the DATA has a single quote in it
The parameter has an apostrophe has a single quote in it
But the dynamic SQL does an escape on the EXEC (@SQL)
Is there a "good way" to handle this?


Example...
Here is some code
DECLARE @SQL VARCHAR(MAX) = '';
DECLARE @param VARCHAR(10) = 'a''.com';
--SELECT @param;

SET @SQL = @SQL + 'select * from users where Username = ''' + @param + ''' order by username ';
PRINT @SQL;
EXEC ( @SQL );

Open in new window


And here is the message on execute
Screenprint
Larry Bristersr. DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nitin SontakkeDeveloperCommented:
Not sure at how many places you will have to do it, but you can replace all occurrences of a single quote with two single quotes as demonstrated below:

DECLARE @SQL VARCHAR(MAX) = '';
DECLARE @param VARCHAR(10) = 'a''.com';
--SELECT @param;

select @param = replace(@param, '''', '''''');

SET @SQL = @SQL + 'select * from users where Username = ''' + @param + ''' order by username ';
PRINT @SQL;
EXEC ( @SQL );

Open in new window


You can do it unconditionally. No need to look for it first before replacing, I believe.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Larry Bristersr. DeveloperAuthor Commented:
Thanks...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.