Reputation: 763
What's the difference with or without the leading character (@
or :
) in a parameter name of SqlCommand in C#?
command.CommandText = "SELECT * FROM myTable WHERE name = @myName";
command.Parameters.Add(new SqlParameter("@myName", "bob"));
But this is OK
command.Parameters.Add(new SqlParameter("myName", "bob"));
even this works
command.Parameters.Add("myName", "bob");
I haven't tested the second one, but I can see all of them on the Internet.
I have tried out against Oracle, and both worked, with or without :
.
So which is better, or are they just the same?
Upvotes: 0
Views: 113
Reputation: 125630
@
is added automatically when you don't specify it. Check the source code here:
internal string ParameterNameFixed {
get {
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('@' != parameterName[0])) {
parameterName = "@" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}
That's the property used when SQL query string is generated for your command.
Upvotes: 3
Reputation: 59252
The @
before the paramter tells the sql interpreter that it is a parameter and nothing else.
If you omit that, it may work, because there might be ambiguity between column name and parameter name.
In your case:
SELECT * FROM myTable WHERE name = @myName
will work correctly even if you have a column named myName
, but this:
SELECT * FROM myTable WHERE name = myName
will not work, as the sql interpreter is confused whether you are referring to the column myName
or the parameter myName
.
Upvotes: 0