Mudassir Hasan
Mudassir Hasan

Reputation: 28741

Please help in escaping this SQL string to C# string

'<ad name="'+ am.name+ '" tag="C" cityid="'+cast(am.city_id as varchar) +'" 
 stateid="'+convert(varchar(11),cast(cm.state_id as varchar)) +'" capital="N"> 
 </ad>' as chkdata 

I have above statement in SQL query.

I want to add this to C# string

Unsucessful attempt

string sqlqry = "\'<ad name=""\'+ am.name_id + \'"" tag=""C"" 
cityid=""\'+cast(am.city_id as varchar) +\'"" 
stateid=""\'+convert(varchar(11),cast(cm.state_id as varchar)) +\'"" capital=""N"">
</ad>\' as chkdata ,";

Later I am doing this . I am building a query in string.

sqlcountcmd = new SqlCommand(finalsqlqry, sqlconn);

+1 to all guaranteed

Upvotes: 1

Views: 111

Answers (2)

RemarkLima
RemarkLima

Reputation: 12037

So, if I've understood correctly, you'll only need to escape the double quotes " and not single quotes '

string sqlqry = "'<ad name=\"'+ am.name_id + '\" tag=\"C\" " +
"sectordetailid=\"'+cast(am.sector_detail_id as varchar) +'\" " +
"stateid=\"'+convert(varchar(11),cast(cm.state_id as varchar)) +'\" capital=\"N\">" +
"</ad>' as chkdata";

You can use the verbatim character @ I'm sure, but I've not got Visual Studio in front of me to check.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062560

presumably that entire thing is to be treated as sql - not a composite of sql and C#. Thus if we use a verbatim literal we only need to worry about the "s:

string s = @"'<ad name=""'+ am.name+ '"" tag=""C"" cityid=""'+cast(am.city_id as varchar) +'"" 
stateid=""'+convert(varchar(11),cast(cm.state_id as varchar)) +'"" capital=""N""> 
</ad>' as chkdata ,";

However! I strongly suggest not doing this. You should just return the columns from SQL, and let your app tier worry about xml/html etc.

Upvotes: 2

Related Questions