jeudi 21 juillet 2016

sql case with function

I have the following dynamic query that creates a pivoted table for each account_id against the products using a UDF.I need to add spaces after the UDF is executed depending up the account_id being matched to the specific tables. eg- the account id in the pivot matches the id present in test_rev then 2 spaces if the account_id in the pivot matches the id present in test_oncontract then 3 spaces so on

    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.A_NAME) 
            FROM TEST c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT account_id, ' + @cols + '  from
                (

                    SELECT 
                        CASE WHEN (SELECT account_id from test_rev)
                        THEN dbo.make_table(a,b,c,d,e,f) +space(2) ELSE END AS newvalue
                        CASE WHEN (SELECT account_id from tbl_on_contract)
                        THEN dbo.make_table(a,b,c,d,e,f) +space(3) ELSE END AS newvalue
                        CASE WHEN (SELECT account_id from Test_prod)
                        THEN dbo.make_table(a,b,c,d,e,f) +space(4) ELSE END AS newvalue
                        ,a_name
                    from TEST_1


           ) x
            pivot 
            (
                MAX(newvalue)
                for a_name in (' + @cols + ')
            ) p '


execute(@query)

Aucun commentaire:

Enregistrer un commentaire