简体   繁体   中英

Executing multiple SQL Server stored procedures in C# with the same parameters

Curious to know if I execute multiple stored procedures within the same using block, will the parameters be passed to each stored procedure or will I need to explicitly add the same parameters to each individual stored procedure.

using (sqlConnection)
{
    SQLCommand cmd = new SQLCommand("sproc1", sqlConnection)
    cmd.CommandType = CommandType.StoredProcedure;

    //adding parameters for the first SQL query
    cmd.Parameters.Add(new SQLParameter("@ID", id));
    cmd.Parameters.Add(new SQLParameter("@Sport", sportId));
    cmd.Parameters.Add(new SQLParameter("@Player", playerId));
    cmd.ExecuteNonQuery();

    cmd.CommandText = "sproc2";
    cmd.CommandType = CommandType.StoredProcedure;
    //Will parameters from above be passed in this stored procedure, or will they need to be added again?
    cmd.ExecuteNonQuery();
};

Yes. However I would not do that for three maintenance reasons:

  1. It's not normal (at least I have never seen this), so this code may be misread by other developers or future you.

  2. If only some of the parameters are reused but not all, you end up having new Add() s for each stored procedure. And then it's difficult to keep track, as you read the code, which exact parameters are used for any given stored procedure.

  3. The different stored procedure calls are no longer modular. Each one relies on what has previously been added to the parameters in the SQLCommand .

If you do find yourself reusing a group of variables between different stored procedure calls, then I would just create a method that adds those variables to a SQLCommand and returns the SQLCommand , and then call that method for each of the stored procedures.

Yes that is a tiny amount of extra processing time, but it will make your code much more maintainable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM