tags:

views:

165

answers:

2

i am doing a continuously select every 10seconds, so i thought i would do some premature optimsing and save creating a cmd and paramater objects in everyloop

if i do this in one method

public void FirstSelect() {

    // select data
    this.cmdSelectData = new SqlCommand(SQL_SELECT_DATA, conn);

    this.paramBranchId = new SqlParameter("@branch_id", 1);
    this.cmdSelectData.Parameters.Add(paramBranchId);

    // fetch data blah, blah, blah...
}

and then this in another method

public void SecondSelect() {

    this.paramBranchId.Value = 2;
   // fetch data
}

would that work as expected, one select using branch 1, one select using branch 2 or do i need to

this.cmdSelectData.Parameters.Clear();
ths.cmdSelectData.Parameters.Add(new SqlParameter( // for branch 2)

}

+1  A: 

You need to create a new Parameter for each one you add.

Mitch Wheat
see Matt's fuller answer (I answered before question was complete!)
Mitch Wheat
+3  A: 

Yes, setting the Value on an existing parameter does affect subsequent executions of the command. It's quite handy if you want to execute the same command a few times with different values for one or more parameters, without having to rebuild the whole thing each time.

Matt Hamilton
+1. But, I actually prefer not to reuse parameter instances (or for that matter, reusing variables for other tasks) as it can lead code that is more prone to bugs being introduced (such as during maintenance)
Mitch Wheat
Yeah I know where you're coming from, Mitch. I really only do this when it's a *very* simple command with just the one parameter.
Matt Hamilton