动态标量变量

时间:2013-01-25 17:24:24

标签: c# sqlcommand

背景

我有一系列的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);
        }
    }       
}

1 个答案:

答案 0 :(得分: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);
    }
}