Add variable number of rows into a table based on the values in another table (without cursors/while loops)

  • Below is a simplified version of my tables:

    set nocount on

    drop table #x

    create table #x (docid int, pages int)

    insert into #x values (1, 1)

    insert into #x values (2, 5)

    insert into #x values (3, 2)

    insert into #x values (4, 3)

    select * from #x;

    drop table #y

    create table #y (docid int, pagenumber int)

    insert into #y values (1, 1)

    insert into #y values (2, 1)

    insert into #y values (2, 2)

    insert into #y values (2, 3)

    insert into #y values (2, 4)

    insert into #y values (2, 5)

    insert into #y values (3, 1)

    insert into #y values (3, 2)

    insert into #y values (4, 1)

    insert into #y values (4, 2)

    insert into #y values (4, 3)

    select * from #y;

    set nocount off

    So basically I have an input table #x with a docid and total number of pages within that docid.

    How can I construct the output table #y that has n rows per #x.docid where n is #x.pages?

    I can do it with cursors or while loops etc in a few different ways (either per docid or one insert/select per distinct #x.pages value)

    I am wondering if there is a set based T-SQL solution to this? Can CTEs be somehow used for this?

    I am creating code ultimately for SQL Server 2008 R2 enterprise edition.

    Any help is greatly appreciated!

    Thanks.

  • Sure this isn't too hard using a tally table.

    insert #y

    select #x.DocID, t.N

    from #x

    join tally t on t.N <= #x.pages

    select * from #y

    You can read about a tally table here. http://www.sqlservercentral.com/articles/T-SQL/62867/[/url]

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Sean Lange (3/20/2013)


    Sure this isn't too hard using a tally table.

    insert #y

    select #x.DocID, t.N

    from #x

    join tally t on t.N <= #x.pages

    select * from #y

    You can read about a tally table here. http://www.sqlservercentral.com/articles/T-SQL/62867/[/url]

    I'm starting to see a pattern with some of the posts. Looks like people are coming here to get their homework done. Anyone else seeing this?

  • Lynn Pettis (3/20/2013)


    Sean Lange (3/20/2013)


    Sure this isn't too hard using a tally table.

    insert #y

    select #x.DocID, t.N

    from #x

    join tally t on t.N <= #x.pages

    select * from #y

    You can read about a tally table here. http://www.sqlservercentral.com/articles/T-SQL/62867/[/url]

    I'm starting to see a pattern with some of the posts. Looks like people are coming here to get their homework done. Anyone else seeing this?

    Yep... I'm thinking the instructor is going to make a mess in his britches when everyone turns in the Tally Table solution. Hopefully, the instructor learns something in the process. 😛

    --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)

  • Jeff Moden (3/20/2013)


    Lynn Pettis (3/20/2013)


    Sean Lange (3/20/2013)


    Sure this isn't too hard using a tally table.

    insert #y

    select #x.DocID, t.N

    from #x

    join tally t on t.N <= #x.pages

    select * from #y

    You can read about a tally table here. http://www.sqlservercentral.com/articles/T-SQL/62867/[/url]

    I'm starting to see a pattern with some of the posts. Looks like people are coming here to get their homework done. Anyone else seeing this?

    Yep... I'm thinking the instructor is going to make a mess in his britches when everyone turns in the Tally Table solution. Hopefully, the instructor learns something in the process. 😛

    LOL. I guess my "homework meter" has been temporarily disabled. It should be back online in the next few minutes.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • Thank you Sir! Not sure how to interpret the other replies and so I will leave it at that. The article was really helpful. Thank you again.

  • charles99 (3/20/2013)


    Thank you Sir! Not sure how to interpret the other replies and so I will leave it at that. The article was really helpful. Thank you again.

    You are welcome.

    The other replies are in response to some people that come here and post their homework questions. There is nothing wrong with that per se but if you are a student then it is a disservice by myself or any other posters to simply provide the answer. Sort of the old "teach a man to fish" concept.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • I see ... I wish I were still a student. The pros are making me nervous asking my next "real-world" question on this site again! 🙂

  • charles99 (3/20/2013)


    I see ... I wish I were still a student. The pros are making me nervous asking my next "real-world" question on this site again! 🙂

    Don't worry about it. There was something in the way you had worded your post that made it sound as though it might be a homework type question. Ask away, somebody will come along and help.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/

  • charles99 (3/20/2013)


    I see ... I wish I were still a student. The pros are making me nervous asking my next "real-world" question on this site again! 🙂

    The question you asked has properties very similar to several questions asked by others, so it really is just the pattern that set off a "possible homework" alarm. We are more than willing to help. If we know it is homework, we tend to take a more hands off approach (or at least try to) and try to guide instead just answering the question.

    We want people to understand what they are doing. For real world questions, we'll answer than normal work backward on the understanding side because you are still the one who will get the call at 3:30 in the morning when things break, not us.

  • The article is great. had a question: In Production, is it possible that the login that runs such a query might not have access to Master..syscolumns and so I should use some table from within my own database that i know is always 10k in size or more? Maybe a stupid because it is possible that everyone has read access to such system views. I will test but thought someone may have an answer. BOL says: "In SQL Server 2005 and later versions, the visibility of the metadata in catalog views is limited to securables that a user either owns or on which the user has been granted some permission."

  • You could build a tally table in your database an use it directly, or you could use the following as a start for building a dynamic tally table when needed with a query:

    with

    e1(n) as (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)), -- 10 rows

    e2(n) as (select 1 from e1 a cross join e1 b), -- 100 rows

    eTally(n) as (select row_number() over (order by (select null)) from e2 a cross join e2 b) -- 10,000 rows

  • wow. super coding! Thanks!

  • Hello ,

    you can also try below

    ;WITH CTE AS

    (

    SELECT docid,pages FROM #x

    UNION ALL

    SELECT C.docid,C.pages-1

    FROM #x X INNER JOIN CTE C

    ON X.docid = C.docid

    AND C.pages-1 >0

    )

    SELECT * FROM CTE ORDER BY docid,Pages

  • Megha P (3/22/2013)


    Hello ,

    you can also try below

    ;WITH CTE AS

    (

    SELECT docid,pages FROM #x

    UNION ALL

    SELECT C.docid,C.pages-1

    FROM #x X INNER JOIN CTE C

    ON X.docid = C.docid

    AND C.pages-1 >0

    )

    SELECT * FROM CTE ORDER BY docid,Pages

    Your recursive CTE will be slower and won't scale as well as the straight tally method.

Viewing 15 posts - 1 through 15 (of 16 total)

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