Search code examples
c#sql-serverparameterized-query

Parameterized SQL Values syntax issue


I'm not sure what the issue is but my code looks like:

function() {
string sqltext2;
sqltext2 = "INSERT into myTable";
SqlCommand myCommand2 = new SqlCommand(sqltext2, MyConnection2);

if (cond1) {

    sqltext2 = sqltext2 + "SELECT" + "@initOwnerFirstName" + "," + "@ownerFirstName"  + "UNION ALL ";
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@initOwnerFirstName";
    param.Value = initOwnerFirstName;
    SqlParameter param2 = new SqlParameter();
    param2.ParameterName = "@ownerFirstName";
    param2.Value = owner.FirstName;
    myCommand2.Parameters.Add(param);
    myCommand2.Parameters.Add(param2);

I'm completely new with parameterized SQL but the syntax seems right to me. The error I keep getting is:

Must declare the scalar variable "@initOwnerFirstName". The reason I'm writing the statement like that is because I intend to have multiple other if statements that will add to the SQLtext

EDIT: Here is the full part of the code after the if statement since my syntax makes little sense without the other variables. This is cleaned up after what JYelton suggested but I'm still getting the same error.

sqltext2 = sqltext2 + "SELECT" + "'" + currentUserId2 + "'," + "'" +  owner.Id.ToString() + "'," + "'" + DateTime.Now + "'," + "'FirstName', @initOwnerFirstName, @ownerFirstName UNION ALL ";
myCommand2.Parameters.AddWithValue("initOwnerFirstName", initOwner.FirstName);
myCommand2.Parameters.AddWithValue("OwnerFirstName", owner.FirstName);

Solution

  • Problem could be that you are concatenating your strings without spaces. You don't need to concatenate either. See my update below:

    function() {
    string sqltext2;
    sqltext2 = "INSERT into dbo.OwnerChanges ";
    SqlCommand myCommand2 = new SqlCommand(sqltext2, MyConnection2);
    
    if (cond1) {
        //no concatenating
        sqltext2 = sqltext2 + " SELECT @initOwnerFirstName , @ownerFirstName UNION ALL ";
        SqlParameter param = new SqlParameter();
        param.ParameterName = "@initOwnerFirstName";
        param.Value = initOwnerFirstName;
        SqlParameter param2 = new SqlParameter();
        param2.ParameterName = "@ownerFirstName";
        param2.Value = owner.FirstName;
        myCommand2.Parameters.Add(param);
        myCommand2.Parameters.Add(param2);
    

    I'm not sure what the rest of your code does but I suspect you are leaving a trailing UNION ALL at the end of all that. You could probably benefit by just putting each sub query into an array and using String.Join on them.

    UPDATE:

    I think I see the issue. You need to update CommandText and not the original string. So change this:

    sqltext2 = sqltext2 + " SELECT @initOwnerFirstName , @ownerFirstName UNION ALL ";
    

    to this:

    myCommand2.CommandText= sqltext2 + " SELECT @initOwnerFirstName , @ownerFirstName UNION ALL ";