jeudi 2 juin 2016

How to conditionally exclude or add columns when calculating row total

I have a stored procedure with a parameter defined like below

    @CategoryNames  NVARCHAR(MAX)

The above parameter gets a comma separated string from the application, for example the value can be like this @StaffCategoryIds=N'Category1,Category2,Category3,Category4,Category5'

Then i have the sample below sql query

SET @sql = @sql + 'TypeId, 
        TypeName, 
        Condition,
        Region, 
        (Category1 + Category2 + Category3 + Category4 + Category5) AS Total INTO ##QueryResults
FROM Table1;'

When computing my Total column in the query above, how can i first check whether a category column (say Category2 or Category5) exists in my @StaffCategoryIds comma separated string before including it in the computation of my Total column?

Eg. if 'Category2' exists in @StaffCategoryIds, then i include it in computation of Total else i exclude it.

Aucun commentaire:

Enregistrer un commentaire