Home All Groups Group Topic Archive Search About

dynamic sql and replacing double quotes with single quotes

Author
23 Sep 2005 9:06 PM
JT
i know, i know, dynamic sql=bad idea...

anyways, what is the correct way to write this statement in dynamic sql- i
can't seem to get it right..

im just trying to replace all double quotes with single quotes in my
resultset-


declare @sql as varchar(255)
set @sql + "select replace(t1.log_text, '"', ''') as log_text" + space(1) +
char(13) + char(10)
set @sql + @sql "from myLog"

thanks,

jt

Author
23 Sep 2005 9:52 PM
Bob Barrows [MVP]
JT wrote:
Show quote
> i know, i know, dynamic sql=bad idea...
>
> anyways, what is the correct way to write this statement in dynamic
> sql- i can't seem to get it right..
>
> im just trying to replace all double quotes with single quotes in my
> resultset-
>
>
> declare @sql as varchar(255)
> set @sql + "select replace(t1.log_text, '"', ''') as log_text" +
> space(1) + char(13) + char(10)
> set @sql + @sql "from myLog"
>
> thanks,
>
> jt

Here is what you would need to do without dynamic sql:
declare @s varchar(50)
set @s='9" hammer'
print @s
set @s=replace(@s,'"','''')
print @s

one single quote, one double-quote,one single quote, the comma, then 4
single quotes.

So the idea is to create the same number of single quotes in the statement
assigned to @sql. You do this by doubling up the single quotes:
set @sql = 'select replace(t1.log_text, ''"'', '''''''') as log_text' +

so there are 2 single-quotes, 1 double-quote,two single quotes, a comma,
then 8 single quotes

HTH,
Bob Barrows
PS. Stop using dynamic sql ;-)
--
Microsoft MVP -- ASP/ASP.NET
Please reply to the newsgroup. The email account listed in my From
header is my spam trap, so I don't check it very often. You will get a
quicker response by posting to the newsgroup.
Author
23 Sep 2005 9:57 PM
Erland Sommarskog
JT (jt@nospam.com) writes:
Show quote
> i know, i know, dynamic sql=bad idea...
>
> anyways, what is the correct way to write this statement in dynamic sql- i
> can't seem to get it right..
>
> im just trying to replace all double quotes with single quotes in my
> resultset-
>
>
> declare @sql as varchar(255)
> set @sql + "select replace(t1.log_text, '"', ''') as log_text" + space(1)
> +
> char(13) + char(10)
> set @sql + @sql "from myLog"

Looks like you are running with SET QUOTED_IDENTIFIER OFF, which, well it
is practical when you work with dyanmic SQL, but there are some contexts
where QUOTED_IDENTIFIER is required to be on, and it's on by default in
most places as well.

Anyway:

declare @sql as nvarchar(255)
set @sql = 'select replace(t1.log_text, ''"'', @q) as log_text from my_log'
EXEC sp_executesql @sql, N'@q char(1)', @q = ''''



--
Erland Sommarskog, SQL Server MVP, esq***@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinfo/productdoc/2000/books.asp

AddThis Social Bookmark Button