list parent records with children in one field ?

  • Hi folks.

    Can someone help with the following: -

    I have a budget table (parent) and a budget holders table (child)

    I would like to return the following

    BudgetID   BudgetDesc    BudgetHolderNames

    1             Transport       Fred, John, Jane

    2             Activities       Malcolm

    3             Training         Sam, Susan

     

    What I am trying to do is list the child records horizontally amonst the parent records. the two tables are linked on budgetID.

    Thanks for any assistance.

    CCB

  • One of ways to do it:

    create scale function (fn_list(budgetid)) list parent, chidren in csv format by passing budgetid.

    select budgetid, budgetdesc, fn_list(budgetid) as budgeholdernames from

    table.

  • Thanks for the advice.

    What is a scale function, and what do I code to create it ?

    CCB.

  • Here is an alternate way to achieve the goal.  I am sure it can be reduced to a smaller chunk of code, but this will get you started.

    DECLARE @tmpTable TABLE (GID NUMERIC IDENTITY (1,1)  NOT NULL,

             BudgetID numeric,

               budgetdesc varchar(64),

             budgetholders varchar(1024))

    declare @MinGID numeric, @MaxGID numeric, @thisgid numeric

    DECLARE @BUDGETHOLDERLIST VARCHAR(1000)

    INSERT INTO @tmpTable (BudgetID, budgetdesc) SELECT DISTINCT BUDGETID, BUDGETDESC FROM BUDGET

    select @MinGID = min (gid), @MaxGID = max(GID) from @tmpTable

    WHILE @MinGID <= @MaxGID

    begin

       set @BUDGETHOLDERLIST = NULL

       select @thisgid = gid from @tmpTable WHERE gid = @MinGID

     SELECT @BUDGETHOLDERLIST = COALESCE(@BUDGETHOLDERLIST + ',', '') + RTRIM(budgetholdername)--  as aName

         from budgetholders

       where BUDGETID = @thisgid

       update @tmpTable set budgetholders = @BUDGETHOLDERLIST WHERE gid = @thisgid

       set @mingid = @mingid + 1

    end

    select * from @tmpTable

  • My mistake, it is scalar function.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply