SQL /存储过程问题

时间:2012-09-03 14:01:06

标签: c# sql stored-procedures

我有一种情况,我正在执行存储过程并在我的c#代码中获取返回55条记录的结果,现在我在行中有一列需要显示为执行另一个sql查询的结果。我已经尝试了所有方法,但无法弄清楚如何实现。请帮忙。

我称之为正常工作的C#代码是:

public static MonthlyFinancialReportCollection GetList(SASTransaction withinTransaction)
{
    MonthlyFinancialReportCollection records = null;

    using (DataSet ds = Helpers.GetDataSet("ShowPremiumCalcReport", withinTransaction))
    {
        if (ds.Tables.Count > 0)
        {
            records = new MonthlyFinancialReportCollection();

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (!string.IsNullOrEmpty(dr[0].ToString())) 
                     records.Add(FillDataRecord(dr));                        
            }
        }
    }

    return records;
}

现在我想针对上面函数中的被调用过程运行查询,因此它将使用查询的计算结果填充列中的一个。

select 
    Sum(WorkingHours.WHO_Amount * dbo.PremiumLevel.PLE_Premium) as Snr_Teaching_Amt
from policy, policyline, coveroption,
     premiumlevel, WorkingHours
where policy.pol_id=policyline.pli_pol_id 
and   policyline.pli_cop_seniorteachingcoverid=coveroption.cop_id 
and   premiumlevel.ple_own_id=policy.pol_own_id 
and   premiumlevel.ple_sca_id=coveroption.cop_sca_id 
and   WorkingHours.who_pos_id=policyline.pli_pos_id
and   pol_dcsf=row["snr teaching staff"]`

2 个答案:

答案 0 :(得分:0)

这不是问题

第一个选项

 You execute the first stored procedure.
 Then foreach row 
    You execute the Second one with a parameter from the first one
 endfor

第二个选项:

 You use a Cursor on the first stored procedure to get all the results in one call

答案 1 :(得分:0)

最慢最简单的方式:

  • 使您的第二个查询成为接受“snr教学人员”的存储过程 作为参数。
  • 使用以下命令从第一次查询向DataTable添加新列: ds.Tables [0] .Columns.Add(“Snr_Teaching_Amt”,typeof(decimal));
  • 为您创建的第二个存储过程创建一个SqlCommand和一个SqlParameter。
  • 循环使用DataTable并将“snr教学人员”放入SqlParameter的值。
  • 使用ExecuteScalar运行SqlCommand,返回的值是第二个查询的结果,您可以将其保留在创建的列中。

但是我不推荐这种方式,因为你将有55 + 1次服务器往返,这并不酷。

中间方式:

由于您的第二个查询返回单个值,因此请将第二个查询作为Sql函数。你可以在第一个程序中调用它,如:

SELECT *, dbo.MyFunction([snr teaching staff]) AS Snr_Teaching_Amt FROM ...

这将具有更好的性能并且更易于维护。 但是,我同意Massanu,您可以使用子查询组合这些过程。祝你好运; - )