繁体   English   中英

SQL /存储过程问题

[英]SQL/Stored Procedure Issue

我有一种情况,我正在执行存储过程并在返回55条记录的c#代码中获取结果,现在我在行中有一列,由于执行另一个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"]`

这不是问题

第一选择

 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

最慢最简单的方法:

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

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

中间方式:

由于第二个查询返回单个值,因此使第二个查询成为Sql函数。 您可以在第一个过程中调用它,例如:

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

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

暂无
暂无

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

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