Tag: T-SQL Tuesday

  • T-SQL Tuesday #37 – A Month of Joins

    tsqltuesdayIt’s time once again for T-SQL Tuesday, and this month is hosted by SQLity.net, Sebastian Meine.

    If you want to know more or participate, read the invitation and write your own blog post.

    The topic this month is joins, in honor of Sebastian’s a-join-a-day series. He’s writing about various aspects of joins, and invites us all to do the same thing on this Tuesday.

    Writing Better Joins

    I’m not a T-SQL expert. I can write code, and understand many type of queries, but I’m not one to dazzle others with their code, like Jeff Moden can. Instead, I want to talk about how I’ve learned to ensure that my code makes sense, is understandable, and most importantly, easy to find the mistakes inside.

    I mainly do this by paying attention to the formatting of the code. I would say that once I started to get away from writing code like this, I found bugs easier, and understood the code better:

    WITH [EMP_cte]([BusinessEntityID], [OrganizationNode], [FirstName], [LastName], [RecursionLevel]) -- CTE name and columns
    AS (
    SELECT e.[BusinessEntityID], e.[OrganizationNode], p.[FirstName], p.[LastName], 0 -- Get the initial list of Employees for Manager n
    FROM [HumanResources].[Employee] e INNER JOIN [Person].[Person] p ON p.[BusinessEntityID] = e.[BusinessEntityID]
    WHERE e.[BusinessEntityID] = @BusinessEntityID
    UNION ALL SELECT e.[BusinessEntityID], e.[OrganizationNode], p.[FirstName], p.[LastName], [RecursionLevel] + 1 -- Join recursive member to anchor
    FROM [HumanResources].[Employee] e INNER JOIN [EMP_cte] ON e.[OrganizationNode].GetAncestor(1) = [EMP_cte].[OrganizationNode]
    INNER JOIN [Person].[Person] p ON p.[BusinessEntityID] = e.[BusinessEntityID]
    )
    SELECT [EMP_cte].[RecursionLevel], [EMP_cte].[OrganizationNode].ToString() as [OrganizationNode], p.[FirstName] AS 'ManagerFirstName', p.[LastName] AS 'ManagerLastName',
    [EMP_cte].[BusinessEntityID], [EMP_cte].[FirstName], [EMP_cte].[LastName] -- Outer select from the CTE
    FROM [EMP_cte] INNER JOIN [HumanResources].[Employee] e ON [EMP_cte].[OrganizationNode].GetAncestor(1) = e.[OrganizationNode]
    INNER JOIN [Person].[Person] p ON p.[BusinessEntityID] = e.[BusinessEntityID]
    ORDER BY [RecursionLevel], [EMP_cte].[OrganizationNode].ToString()
    OPTION (MAXRECURSION 25) 

    I often find code in forums, or sent to me and I need to reformat it so that it looks better. I prefer something like this:

    WITH    [EMP_cte] ( [BusinessEntityID], [OrganizationNode], [FirstName], [LastName], [RecursionLevel] )
              -- CTE name and columns
              AS (
                   SELECT
                    e.[BusinessEntityID]
                   ,e.[OrganizationNode]
                   ,p.[FirstName]
                   ,p.[LastName]
                   ,0 -- Get the initial list of Employees for Manager n
                   FROM
                    [HumanResources].[Employee] e
                    INNER JOIN [Person].[Person] p
                        ON p.[BusinessEntityID] = e.[BusinessEntityID]
                   WHERE
                    e.[BusinessEntityID] = @BusinessEntityID
                   UNION ALL
                   SELECT
                    e.[BusinessEntityID]
                   ,e.[OrganizationNode]
                   ,p.[FirstName]
                   ,p.[LastName]
                   ,[RecursionLevel] + 1 -- Join recursive member to anchor
                   FROM
                    [HumanResources].[Employee] e
                    INNER JOIN [EMP_cte]
                        ON e.[OrganizationNode].GetAncestor(1) = [EMP_cte].[OrganizationNode]
                    INNER JOIN [Person].[Person] p
                        ON p.[BusinessEntityID] = e.[BusinessEntityID]
                 )
        SELECT
            [EMP_cte].[RecursionLevel]
        ,   [EMP_cte].[OrganizationNode].ToString() AS [OrganizationNode]
        ,   p.[FirstName] AS 'ManagerFirstName'
        ,   p.[LastName] AS 'ManagerLastName'
        ,   [EMP_cte].[BusinessEntityID]
        ,   [EMP_cte].[FirstName]
        ,   [EMP_cte].[LastName] -- Outer select from the CTE
        FROM
            [EMP_cte]
            INNER JOIN [HumanResources].[Employee] e
                ON [EMP_cte].[OrganizationNode].GetAncestor(1) = e.[OrganizationNode]
            INNER JOIN [Person].[Person] p
                ON p.[BusinessEntityID] = e.[BusinessEntityID]
        ORDER BY
            [RecursionLevel]
        ,   [EMP_cte].[OrganizationNode].ToString()
    OPTION
            ( MAXRECURSION 25 ) 

    That actually came from reformatting the code using SQL Prompt, a product from my employer, Red Gate Software. I’m lucky in that SQL Prompt formats things as I’d prefer them, indenting and getting the JOIN and ON clauses onto separate lines.

    Having code with structure, where you can clearly see the tables being joined, the clauses in use, and not miss any of the columns being selected at a glance is important. When you’re under stress and trying to debug or develop something, it’s easy to miss something that’s happening in the code if it’s not formatted correctly.

    Whether you like commas before or after columns, or you want things indented so that the names of objects line up doesn’t really matter. What’s important is that you and your team agree on a set of formatting, or have tools that reformat things for each developer in a consistent way. You’ll spend less time trying to understand the code and more time building or fixing it, if it has a consistent layout.

  • T-SQL Tuesday #36 – What Does Community Mean?

    tsqltuesdayIt’s T-SQL Tuesday time, this time it’s a non-technical topic, or at least not a directly technically related topic. The SQL Corner, from Chris Yates (b | t), is hosting and the topic this month is “What Does Community Mean To You?

    You can read the rules on Chris’ blog, and if you’re interesting in hosting, contact Adam Machanic (b | t).

    Community

    I run one of the largest SQL Server communities on the Internet. From the very beginning, Andy, Brian, and I were concerned about building a community. Our goal was to create something that reflected who we were, embodied our ideals, and would be the type of place that we would want to visit ourselves.

    In a little over a decade, it has grown to be an amazing place where people help each other out on a daily basis. Whether it’s with articles written that someone will read weeks in the future, or through near real time interactions in the forums, there are thousands of data professionals on a daily basis interacting with each other at SQLServerCentral.

    Community to me is more than SQLServerCentral, however. It’s more than a web site, or a SQL Saturday, or a group of people that perform the same jobs. Community is more than sharing your knowledge, or asking questions of others. Community includes the bonds of caring, of having each of the members matter to the others. It’s not perfect, and we have our share of disagreements, discontent, and even dislike among members.

    In that case, it’s like family. This SQL Server community reminds me of family: not always pretty or peaceful, but always something I am proud of being a member.

  • T-SQL Tuesday #35 – Soylent Green

    tsqltuesdayThis month’s host is Nick Haslam (b | t) and he bases his question on the movie Soylent Green, which I haven’t seen. This month he asks what the most horrifying thing you’ve seen in SQL Server. It’s been a long few weeks for me, so I‘ll keep this short.

    As an FYI, if you want to host or participate, contact Adam Machanic.

    Horrifying

    The thing that first comes to mind for me is my first job in Denver. I had interviewed with a small financial services firm looking for a DBA. We thought it was a good fit and I came out to start work in early 1999. Fortunately my wife stayed back in Virginia to sell our house and I was alone since I ended up working a lot.

    The first surprise I had when I arrived for work was that not only was I responsible for the databases (v6.5), but that I was also going to manage the network administrator. He wasn’t that experienced and needed some guidance because we were experiencing daily problems.

    The second surprise was that all of our applications used the sa account. We had 3 or 4 standalone workstations devoted to loading pricing and position information every morning from clients, all using SA. We also had a web application and a thick client application (VB6) that allowed clients to authenticate with a name and password (stored in plain text) in the database, but the connection to SQL Server as with sa.

    However the most horrifying thing was that all developers used the “sa” account to connect to our database servers, in development, QA, and production, with the same password.

    A scary situation.

    The daily issues actually helped here. I started to tackle our problems, requiring the developers to fix the applications one by one, using a normal user account. It required months just to convince our management that stability was compromised by developers making changes in production, but we were able to change the sa password in all environments and make it different. We then started to require applications to use difference accounts, and a year later, we had ad least provided more stability by removing the “quick fixes” made in production.

    All sorts of poor practices at that job, and when I left after almost two years, there were still numerous issues.

  • T-SQL Tuesday #34 – Help! I Need Somebody

    tsqltuesday

    I couldn’t resist, so here goes….

    Help, I need some data,
    Help, not just any data,
    Help, I was told you need a report, help.
    When I was younger, so much smarter than today,
    I never needed any query help in any way.
    But now these reports are long, I’m not working late nights,
    Now I find I’ve got to ask for help on window functions.
    Help me if you can, I need a rank 
    And I do appreciate the over clause.
    Help me, get my report back to the client,
    Won’t you please, please help me.
    And now T-SQL has changed in oh so many ways,
    the over clause just seems to vanish in the haze.
    But every now and then I feel I know row_number,
    I know I need a lag or lead just not sure which to use.
    Help me if you can, I’m feeling slow
    And I do appreciate returning more rows.
    Help me, get my query back to the client,
    Won’t you please, please help me, help me, help me, oh.

    The Rules

    T-SQL Tuesday is a monthly blog party hosted by a different blogger every month. This month is hosted by Rob Volk with the theme of “Help, I Need Somebody”.

    If you’re like to participate, just write a post, publish it on the appropriate day and link to the host’s post. If you want to host, contact the founder, Adam Machanic (b|t).