1

背景:

我有一系列 sql 查询要运行。根据查询,可能有要替换的标量变量。

问题:

SqlCommand即使查询中没有使用该变量,是否可以将标量变量添加到?

例子:

查询 #1 可以使用标量变量@CashSub,但查询 #2 不使用。我可以添加@CashSub为参数而不收到错误吗?

代码:

private void InsertStatements()
{
    foreach (string Query in Client.InsertStatements(CurrentCompany.Modules.ToArray()))
    {
        foreach (Branch CompBranch in CurrentCompany.Branches)
        {
            SqlCommand cmd = new SqlCommand(Query);
            cmd.Parameters.AddWithValue("DataDB", CompBranch.AppDB);
            cmd.Parameters.AddWithValue("OrigCpnyID", CompBranch.CompanyId);
            cmd.Parameters.AddWithValue("CashAcct", CompBranch.CashAccount);
            cmd.Parameters.AddWithValue("CashSub", CompBranch.CashSubAccount);

            Queries.RunQuery2(cmd, DestinationConnection.ConnectionString);
        }
    }       
}
4

1 回答 1

2

您如何看待在每个 addparam 前面添加如下内容:

   if(Query.Contains("DataDB")) cmd.Parameters.AddWithValue("DataDB",...)

也可以更干净地将参数存储在具有名称和值的字典中并循环。

编辑:

我是说:

   var paramRegistry = new Dictionary<string,object>{
      {"@DataDB", CompBranch.AppDB},
      {"@OrigCpnyID", CompBranch. CompanyId},
      {"@CashAcct", CompBranch. CashAccount},
      {"@CashSub", CompBranch. CashSubAccount},
      ...
  };

  foreach (string Query in Client.InsertStatements(CurrentCompany.Modules.ToArray()))
  {
    foreach (Branch CompBranch in CurrentCompany.Branches)
    {
        SqlCommand cmd = new SqlCommand(Query);

        foreach(var parName in paramRegistry.Keys){
            if (Query.Contains(parName)){
                 cmd.Parameters.AddWithValue(parName,paramRegistry[parName]);
            }
        }

        Queries.RunQuery2(cmd, DestinationConnection.ConnectionString);
    }
}   
于 2013-01-25T17:42:26.203 回答