简体   繁体   中英

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 .

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

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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