在另一个存储过程中使用存储过程中的值

时间:2018-11-27 12:06:53

标签: tsql stored-procedures

因此,在我正在从事的项目中,有一个存储过程(我们称为SP_Premium)为我提供了一些值,包括我需要的Premium数字。

我发现我不能使用Linq to EF解决我的问题,所以我应该使用存储过程。

这里的问题是,我需要在新存储过程中使用Premium中的SP_Premium号。

如何将此SP_Premium添加到我自己的存储过程中并获取所有值?

ALTER PROCEDURE [dbo].[SP_Premium]
 @RequestId int = 104622
AS

BEGIN
declare @precision int = 10

select 
     P.Premium
     P.ONP
    ,P.ONEP
    ,P.retention
    ,P.retentionValue
    ,P.retentionValueEndorsement
    ,P.OCP
    ,P.OCEP
    ,P.cededShare
    ,T.amount
    ,T.endorsementAmount
    ,T.cededAmount
    ,T.cededEndorsementAmount
    ,RC.cost
    ,RC.endorsementCost
 from requestbackoffice bo
    cross apply [dbo].[Report_Get_BO_original_premium](@RequestId,@precision) P
    outer apply [dbo].[Report_Get_BO_taxes](@RequestId,@precision) T
    outer apply [dbo].[Report_Get_BO_reinsurance_costs](@RequestId,@precision) RC
 where bo.requestId=@requestId
END

2 个答案:

答案 0 :(得分:1)

在新的存储过程中,您只需执行现有过程并将结果保存在那里,即可在新代码中使用。

如果是我,我将首先从SP_Premium(注意:Avoid Naming User Stored Procedures SP% or SP_%)执行现有查询,使用INTO子句创建表,然后使用管理Studio编写结果表的脚本。使用该脚本在新过程中生成一个临时表。这是正确处理所有数据类型的一种懒惰方法。

因此,伪编码看起来像这样:

CREATE PROCEDURE usp_NewProc
AS

BEGIN

  IF OBJECT_ID('tempdb..#InterimTable','U') IS NOT NULL
    DROP TABLE #InterimTable;

  CREATE TABLE #InterimTable(
  <using the script that SSMS made for you>
  );

  DECLARE @ParamVariable INT;

  SELECT @ParamVariable = <Code to assign a parameter value>;

  INSERT INTO #InterimTable (<Field List>)
  EXECUTE SP_Premium @RequestID = @ParamVariable;

  <Carry on with whatever else you need to do>;

  --Arguably unnecessary, but I like to clean up after myself
  IF OBJECT_ID('tempdb..#InterimTable','U') IS NOT NULL
    DROP TABLE #InterimTable;

END;

答案 1 :(得分:0)

我认为最好的方法是使用临时表,然后将其删除:

ALTER PROCEDURE [dbo].[SP_Premium]
 @RequestId int = 104622
AS

BEGIN
declare @precision int = 10

IF object_id('tempdb..##tmp_result_sp_premium') IS NOT NULL 
    DROP TABLE ##tmp_result_sp_premium

select 
     P.Premium
     P.ONP
    ,P.ONEP
    ,P.retention
    ,P.retentionValue
    ,P.retentionValueEndorsement
    ,P.OCP
    ,P.OCEP
    ,P.cededShare
    ,T.amount
    ,T.endorsementAmount
    ,T.cededAmount
    ,T.cededEndorsementAmount
    ,RC.cost
    ,RC.endorsementCost
 into ##tmp_result_sp_premium
 from requestbackoffice bo
    cross apply [dbo].[Report_Get_BO_original_premium](@RequestId,@precision) P
    outer apply [dbo].[Report_Get_BO_taxes](@RequestId,@precision) T
    outer apply [dbo].[Report_Get_BO_reinsurance_costs](@RequestId,@precision) RC
 where bo.requestId=@requestId
END

然后在您的过程中使用结果,然后

IF object_id('tempdb..##tmp_result_sp_premium') IS NOT NULL 
    DROP TABLE ##tmp_result_sp_premium

使用 ## 代替允许您访问其他会话中的数据。

相关问题