Flatten association table to multi-value column?

后端 未结 4 1125
旧时难觅i
旧时难觅i 2021-01-07 07:48

I have a table with just product ID\'s and category ID\'s (products can be in more than one category). How can I flatten the category ID\'s into a product column so I end us

4条回答
  •  梦毁少年i
    2021-01-07 08:23

    Use a function.
    This does a lookup to text so you will need to adapt.
    The COALESCE is just to put a ,.
    This is from a large scale production application - it works and it fast.
    Function was questioned by JustinPony as function is slow
    I am hitting some tables of million of records but only returning 100 rows.
    The function is only applied to the hundred rows.

    usage:

    select top 5 sID, ( select [dbo].[JoinMVEnum](docSVsys.sID, '140') ) as [Flag Issue]
    from docSVsys
    

    function

    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE FUNCTION [dbo].[JoinMVText]
    (
       @sID int,
       @fieldID tinyint
    )
    RETURNS VARCHAR(MAX)
    AS 
    BEGIN
        DECLARE @MVtextList varchar(max)
        SELECT @MVtextList = COALESCE(@MVtextList + '; ', '') + docMVtext.value
        FROM docMVtext with (nolock) 
        WHERE docMVtext.sID = @sID and fieldID = @fieldID
        RETURN @MVtextList
    END
    
    GO
    

提交回复
热议问题