Computed column using replace

Computed column using replace

I have created a computed column using replace in a view that might be useful for others and decided to share it. My query-based view has many tables in the datasource. It is showing all possible combinations of PaymTerm and CashDisc for some reasons that are not relevant here. This field is the code or id field for the combinations. When there is no cash disc I have to return  ‘PaymTerm.PaymTermId’ else I need to return a combination of ‘PaymTerm.PaymTermId’ and ‘CashDisc.CashDiscCode’ but unfortunately there is the character ‘%’ used in the database for the discount code and that should be excluded in the result.

The solution was the combination of  ‘SysComputedColumn::if’, ‘isNullExpression’ and as there was no function for ‘replace’, I had to create my own code for that.

Computed column X++ code

static server str paymTermDiscCode()
{
    return 
        SysComputedColumn::if(
            SysComputedColumn::isNullExpression(SysComputedColumn::returnField(tableStr(PEPPaymTerm), identifierStr(CashDisc_1) , fieldStr(CashDisc, CashDiscCode))),
            SysComputedColumn::returnField(tableStr(PEPPaymTerm), identifierStr(PaymTerm_1) , fieldStr(PaymTerm, PaymTermId)),
            '('+SysComputedColumn::returnField(tableStr(PEPPaymTerm), identifierStr(PaymTerm_1) , fieldStr(PaymTerm, PaymTermId))
                + ') +\'_\'+ replace(' +
                SysComputedColumn::returnField(tableStr(PEPPaymTerm), identifierStr(CashDisc_1) , fieldStr(CashDisc, CashDiscCode))
                + ',\'\%\',\'\')'
            );
}

Computed column in SQL

(CAST ((CASE WHEN T3.CASHDISCCODE IS NULL THEN T1.PAYMTERMID ELSE (T1.PAYMTERMID) +'_'+ replace(T3.CASHDISCCODE,'%','') END) AS NVARCHAR(20))) AS PEPPAYMTERM

 

Leave a Reply

Your email address will not be published. Required fields are marked *