Home Forums SQL Server 2008 T-SQL (SS2K8) Generate all possible number combinations for a provided list of numbers RE: Generate all possible number combinations for a provided list of numbers

  • Mark-101232 (4/2/2013)


    Another one to try

    WITH Numbers(N) AS (

    SELECT N

    FROM ( VALUES(1),(2),(3),(4) ) Numbers(N)),

    Recur(N,Combination) AS (

    SELECT N, CAST(N AS VARCHAR(1000))

    FROM Numbers

    UNION ALL

    SELECT n.N,CAST(r.Combination + ',' + CAST(n.N AS VARCHAR(10)) AS VARCHAR(1000))

    FROM Recur r

    INNER JOIN Numbers n ON n.N > r.N)

    SELECT Combination

    FROM Recur

    ORDER BY LEN(Combination),Combination;

    Very good one Mark......I was just about to post this....

    After I posted my solution...I started thinking that I could do it recursively.....Its a lot easier and would be a lot better performance wise.

    Vinu Vijayan

    For better and faster solutions please check..."How to post data/code on a forum to get the best help" - Jeff Moden[/url] 😉