Search code examples
c#sql-serversqlcommandoraclecommand

What's the difference with or without the leading (@) for a command parameter in C#


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?


Solution

  • @ 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.