Anton Gogolev
Anton Gogolev

Reputation: 115691

T-SQL: When string concatenation is the only option or how to correctly escape SQL strings

I'm well aware that the only reliable way to parameterize SQL statements is, well, with parameters, named or otherwise.

Unfortunately, it's not always possible to use those. For example,

create login [user] with password = 'p@$$w0rd'

will not accept parameters at all.

What will be the most reliable way, given the circumstances, to escape strings in T-SQL?

Upvotes: 2

Views: 65

Answers (1)

Richard
Richard

Reputation: 30618

This answer looks relevant, but if you're after a more generic solution then you could ask the database to quote it for you:

SELECT QUOTENAME(@myvalue, '''')

This should return you a value that is safe to use in concatenated SQL.

Upvotes: 1

Related Questions