views:

33

answers:

3

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.

+1  A: 

You need to explictly set a datatype for the parameter

gbn
+1  A: 

instead try

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

Just make sure if that's the problem

drachenstern
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 Leonardo
Yeah, I was going to let him do the fine tuning ;) ... I just wanted to see if that would fix the problem in general.
drachenstern
A: 

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.

cookiecaper