简体   繁体   English

使用相同的参数在C#中执行多个SQL Server存储过程

[英]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块中执行多个存储过程,还是将参数传递给每个存储过程,还是需要向每个单独的存储过程显式添加相同的参数。

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. 如果仅重用部分参数而不是全部重用,则最终每个存储过程都有新的Add() 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 . 每个依赖于先前在SQLCommand的参数中添加的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. 如果确实发现自己在不同的存储过程调用之间重用了一组变量,那么我将创建一个将这些变量添加到SQLCommand并返回SQLCommand ,然后为每个存储过程调用该方法。

Yes that is a tiny amount of extra processing time, but it will make your code much more maintainable. 是的,这是很少的额外处理时间,但是它将使您的代码更易于维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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