【问题标题】:Stored Procedure set parameter based on other parameters input存储过程根据输入的其他参数设置参数
【发布时间】:2017-07-05 23:26:10
【问题描述】:

尝试在 SQL 2008R2 中创建存储过程。 我有两个参数输入,根据它们的输入,理想情况下将另一个参数的值设置为四个值之一。试图确定这是否可以做到,如果可以,将其放在 SP 中的最佳位置是什么。 这是我的代码的精简版。

Declare @FWIdle as bYN, @NewComp as bYN

set @FW = 'Y'           
set @NEW = 'Y'  

select Case(
when w.WearRate <0.400 then round((- 50*w.WearRate+112.5),2
when w.WearRate <0.450 then round((-100*w.WearRate+132.5),2)
when w.WearRate <0.550 then round((- 50*w.WearRate+110.5),2)
else 52.5 END as Score

from EMWear w

希望将所有 w.WearRate 替换为 @Wear 并根据两个参数的组合将 @Wear 设置为视图中四个可能的字段之一。

比如:

if @FW = 'Y' and @NEW = 'N' then @Wear = w.FWRate else
if @FW = 'N' and @NEW = 'Y' then @Wear = w.NewRate else
if @FW = 'Y' and @NEW = 'Y' then @Wear = w.FWNewRate else
@Wear = w.WearRate

由于我有 150 多行代码来处理这个速率,我宁愿不必编写此代码 4 次来获得所需的值。任何有关我如何编写并保持干净/简单的帮助将不胜感激。

【问题讨论】:

    标签: sql-server-2008 stored-procedures parameters


    【解决方案1】:

    您可以将所有代码简化为这样的内容。

    SELECT w.EMCo, w.Component,w.CompType, CASE 
    WHEN @FW = 'Y' AND @NEW = 'Y' THEN w.FwIdleWearRate
    WHEN @FW = 'Y' AND @NEW = 'N' THEN w.FwWearRate
    WHEN @FW = 'N' AND @NEW = 'Y' THEN w.IdleWearRate
    ELSE w.StdWearRate
    END AS WearRate
    FROM bcvEMCompWearAdj w
    

    【讨论】:

    • 这将拉入正确的 WearRate,但不显示这将如何用于我使用该 WearRate 的多行计算。感谢您的意见。
    【解决方案2】:

    我的问题的解决方案最终是创建一个临时表并插入我想使用的 WearRate。

    If OBJECT_ID('tempdb.dbo.#TempWear','U') IS NOT NULL 
    Drop Table #TempWear;
    
    Create Table #TempWear 
        EMCo tinyint Null,
        Component varchar(10) NULL,
        CompType varchar(10) NULL,
        WearRate decimal(38,5) NULL
        );
    
    if @FW = 'Y' and @New = 'Y'
    Begin
        Insert into #TempWear
        (EMCo, Component, CompType, WearRate)
        select w.EMCo, w.Component,w.CompType, w.FwIdleWearRate 
        from bcvEMCompWearAdj w
    END
    else 
    if @FW = 'Y' and @New = 'N'
    Begin
        Insert into #TempWear
        (EMCo, Component, CompType, WearRate)
        select w.EMCo, w.Component,w.CompType, w.FwWearRate 
        from bcvEMCompWearAdj w
    END
    else
    if @FW = 'N' and @New = 'Y'
    Begin
        Insert into #TempWear
        (EMCo, Component, CompType, WearRate)
        sselect w.EMCo, w.Component,w.CompType, w.IdleWearRate
        from bcvEMCompWearAdj w
    END
    else
    --if @FW = 'N' and @New = 'N'
    Begin
        Insert into #TempWear
        (EMCo, Component, CompType, WearRate)
        select w.EMCo, w.Component,w.CompType, w.StdWearRate    
        from bcvEMCompWearAdj w
    END
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多