简体   繁体   English

SQL Server(按顺序中断和执行操作)

[英]Sql Server (breaking sting and doing operations in that order)

I have varchar value of @Order as 'ST,OT,DT' OR 'OT,ST,DT' and so on with all possible combinations of ST,OT,DT . 我将@Order的varchar值设置为'ST,OT,DT'或'OT,ST,DT'等,并带有ST,OT,DT的所有可能组合。

Then I want to implement logic in stored procedure as below for @order = 'ST,OT,DT' if ST comes first then deduct from @SThours, If @SThours is zero , decuct from @OThours, if @OThours is zero, deduct from @DThours 然后我想在存储过程中实现以下逻辑:@order ='ST,OT,DT'如果ST首先出现,则从@SThours中扣除,如果@SThours为零,则从@OThours中扣除,如果@OThours为零,则扣除来自@DThours

I could go on and write if else condition for all possible combinations .. but wanted to have nice implementation so that in future if new value comes I dont need to change my code...... 我可以继续写所有可能的组合的其他条件..但是想要有一个很好的实现,以便将来如果有新的价值,我就不需要更改代码了……

Here's something you could do: 您可以执行以下操作:

declare @valueToDeductFrom int, @currentIndex int, @currentFieldName char(2)

set @valueToDeductFrom = 0
set @currentIndex = 1

while @currentIndex < 8 and @valueToDeductFrom = 0
begin
    set @currentFieldName = substring(@order, @currentIndex, 2)

    set @valueToDeductFrom = 
        case 
            when @currentFieldName = 'ST' then @SThours
            when @currentFieldName = 'OT' then @OThours
            when @currentFieldName = 'DT' then @DThours
            else 0
        end

    set @currentIndex = @currentIndex + 3
end

-- do something with @valueToDeductFrom here... Probably deduct from it. :)

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

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