Home Forums SQL Server 2008 T-SQL (SS2K8) Passing Multiple Values As Parameters to get Multiple Columns with Comma Seperation(MSSQL) RE: Passing Multiple Values As Parameters to get Multiple Columns with Comma Seperation(MSSQL)

  • vsts.dev (4/5/2013)


    But I need to pass multiple values to the parameter

    like

    exec 4,5,6

    and desired result should be

    TranID | MonthValue

    1 | 50,30,11 ***-->;Comma Separated values of columns

    how can i acheive result like this??

    I noticed that the above part of the OPs question was never answered. As Jack Corbett suggested, you just need a good splitter and the code becomes simple.

    Here's the test data I used.

    DROP TABLE dbo.TblTran

    SELECT TranID, Month, MonthValue

    INTO dbo.TblTran

    FROM (

    SELECT 1, 4, 50 UNION ALL

    SELECT 1, 5, 30 UNION ALL

    SELECT 1, 6, 11 UNION ALL

    SELECT 1, 7, 30 UNION ALL

    SELECT 2, 4, 51 UNION ALL

    SELECT 2, 5, 39 UNION ALL

    SELECT 2, 6, 100 UNION ALL

    SELECT 2, 7, 30

    ) d (TranID, Month, MonthValue)

    ;

    Stored procedures are a real PITA if you want to use their data for something else so I made this as an iTVF (Inline Table Valued Function).

    CREATE FUNCTION dbo.SomeFunctionName

    (@MonthsCSV VARCHAR(100))

    RETURNS TABLE WITH SCHEMABINDING AS

    RETURN

    WITH cteGetData AS

    (

    SELECT t.TranID

    , t.Month

    , t.MonthValue

    FROM dbo.TblTran t

    JOIN dbo.DelimitedSplit8K(@MonthsCSV,',') split

    ON t.Month = split.Item

    )

    SELECT c1.TranID

    , MonthValues =

    STUFF(

    (

    SELECT ',' + CAST(MonthValue AS VARCHAR(10))

    FROM cteGetData c2

    WHERE c2.TranID = c1.TranID

    ORDER BY c2.[Month]

    FOR XML PATH('')

    )

    ,1,1,'')

    FROM cteGetData c1

    GROUP BY c1.TranID

    ;

    Then you can call it like the following:

    SELECT * FROM dbo.SomeFunctionName('4,5,6');

    That returns the desired answer:

    TranID MonthValues

    ----------- ------------

    1 50,30,11

    2 51,39,100

    As a bit of a sidebar, please consider not abbreviating names nor using reserved words like "Month" for names of objects or columns. 😉

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)