0

I have this:

string a = "a+a";
SqlCommand q = new SqlCommand("SELECT * FROM table WHERE a = @a", conn);
q.Parameters.AddWithValue("@a", a);

But the parameterization totally erases the + from a, leaving me with a a instead of the desired a+a. I need that + in place; I just want it escaped, not removed.

Is there a way I can tell C# to escape the + instead of erasing it? I am using .NET Framework 2.0 and don't have the option to upgrade.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
jeffcook2150
  • 4,028
  • 4
  • 39
  • 51
  • What is a+a meant to be? A string literal "a+a" or an expressions "a added to a"? – gbn Sep 17 '10 at 04:59

3 Answers3

1

You need to explictly set a datatype for the parameter

gbn
  • 422,506
  • 82
  • 585
  • 676
1

instead try

q.Parameters.Add( "@a", SqlDbType.Text ).Value = a;

Just make sure if that's the problem

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
  • 1
    OP probably needs SqlDbType.NVarChar or SqlDbType.VarChar or similar. Not .Text which is a LOB. But, yes, it needs explicit parameter type to do this. – Jim L Sep 17 '10 at 05:12
  • Yeah, I was going to let him do the fine tuning ;) ... I just wanted to see if that would fix the problem in general. – jcolebrand Sep 19 '10 at 02:28
0

Thanks everyone. I'm not sure exactly what happened here but I ended up just replacing all + signs with zeros before storing.

I think I remember transferring this variable over the querystring, but I don't remember exactly. If I did, then probably the plus was eaten by the qs parser, not the parameterization code. You may want to check that.

I did not try specifying a datatype because I was in a hurry and replacing the + for something that doesn't get eaten like 0 was the fastest solution.

Thanks again to all contributors.

jeffcook2150
  • 4,028
  • 4
  • 39
  • 51