Results 1 to 5 of 5

Thread: [RESOLVED] Explain what is happening here... Please

  1. #1

    Thread Starter
    Don't Panic! Ecniv's Avatar
    Join Date
    Nov 2000
    Location
    Amsterdam...
    Posts
    5,343

    Resolved [RESOLVED] Explain what is happening here... Please

    Hi

    Finally, some (possibly silly) people have let me get my mits on MS Sql Server databases.
    Where, with only the experience of MS Access and examples (previously) from here and online, I get to wade in with big boots.

    Ok so the basics are the same for querying, table structures are a little different and sub queries tend not to do as I thought. However ...


    Yesterday I wanted to get a list of dates thirty (30) days in the past to now. But I don't want to create a table, at least not in the sense of writing; storing and populating it. So I searched online and found a chunk of code. After discussing here with a colleague I ended up with the SQL below.

    But how does it work.?
    I get the gist, start date, loop each day, it's just how it does it without an explicit loop...

    Could some one please answer this really easy question??


    Code:
    with T(day) as
    (
        select DATEADD(dd,-30,DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)) as day
            union all
        select day + 1
            from T
            where day < DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
    )
    select * from T

    BOFH Now, BOFH Past, Information on duplicates

    Feeling like a fly on the inside of a closed window (Thunk!)
    If I post a lot, it is because I am bored at work! ;D Or stuck...
    * Anything I post can be only my opinion. Advice etc is up to you to persue...

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Explain what is happening here... Please

    It is what's called a CTE - Computed Table Expression ... Additionally it is a recursive CTE. They are quite powerful. I use them to walk heirarchies and XML sometimes.

    You'll notice the "from T" inside of it ... that makes it recursive... the first part of the union marks the "anchor" the second part is the recursive part, it selects from the T table (which initially has 1 record, the anchor) and then adds to it, and around and around it goes until the end condition is met and the whole thing is returned.

    Google "MSDN recursive CTE" ... the MSDN entry on them should be the first link or two returned. It goes into a bit more (better) explanation.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  3. #3
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Explain what is happening here... Please

    The loop is standard T-SQL - from before CTE's.

    Here is an example - paste this into a QUERY window in SSMS and EXECUTE it...

    Code:
    Create Table #Test (TestField varchar(1))
    
    Insert into #Test values ('A')
    Insert into #Test values ('B')
    Insert into #Test values ('C')
    Insert into #Test values ('D')
    Insert into #Test values ('E')
    
    Declare @TestVbl varchar(100)
    
    Select @TestVbl=IsNull(@TestVbl+', ','')+TestField
    	From #Test
    	Order by TestField Desc
    
    Select @TestVbl
    This is the result of running the script

    Code:
    -------------------------
    E, D, C, B, A
    
    (1 row(s) affected)
    This SELECT is in affect a LOOP - "Select @TestVbl=IsNull(@TestVbl+', ','')+TestField..." - as it's going to run through all the rows in the table that match the criteria.

    If you are new to MS SQL one of the best things you will discover is STORED PROCEDURE's where you can have queries and variables and all kinds of IF/blocks and loops and do big stuff in one "function call" basically.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  4. #4
    Wall Poster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,969

    Re: Explain what is happening here... Please

    Quote Originally Posted by techgnome View Post
    It is what's called a CTE - Computed Table Expression ... Additionally it is a recursive CTE. They are quite powerful. I use them to walk heirarchies and XML sometimes.

    You'll notice the "from T" inside of it ... that makes it recursive... the first part of the union marks the "anchor" the second part is the recursive part, it selects from the T table (which initially has 1 record, the anchor) and then adds to it, and around and around it goes until the end condition is met and the whole thing is returned.

    Google "MSDN recursive CTE" ... the MSDN entry on them should be the first link or two returned. It goes into a bit more (better) explanation.

    -tg
    CTE
    A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.
    Please remember next time...elections matter!

  5. #5

    Thread Starter
    Don't Panic! Ecniv's Avatar
    Join Date
    Nov 2000
    Location
    Amsterdam...
    Posts
    5,343

    Re: [RESOLVED] Explain what is happening here... Please

    Excellent. Thank you all for the info!

    BOFH Now, BOFH Past, Information on duplicates

    Feeling like a fly on the inside of a closed window (Thunk!)
    If I post a lot, it is because I am bored at work! ;D Or stuck...
    * Anything I post can be only my opinion. Advice etc is up to you to persue...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width