Tag: T-SQL

  • Why Use TRY_PARSE(): #SQLNewBlogger

    Someone asked why I would use TRY_PARSE after I posted a question at SQL Server Central: Getting the Average. Isn’t is slower?

    A fair question. This quick post looks at why.

    Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

    A Quick Setup

    The question above has the setup code, but what if I add another row? For example, I’ll run this .

    insert dbo.commission
    (
        salesperson
      , commission
    )
    values
    (‘Steve’, ‘A’)

    Now, let’s look at the data and run the query from the question.

    2026-07_0371

    This works. However, let’s remove the (slow) TRY_PARSE() from the aggregate.

    2026-07_0372

    Error. Why? I can’t convert “A” in the AVG to a number. It fails.

    You might think, I’ll never get bad data like this. But you might? A user might enter something you don’t expect. An AI might model this as a string, which is bad, but it happens. If it’s an EAV type table, or there are other data  items and you’re trying to extract the numbers from here, TRY_PARSE is helpful.

    SQLNewBlogger

    I wrote a post last week and this is a followup that really just took less than 5 minutes to setup and run. Plus I responded for the user in the post.

    This showcases me thinking about a question and situation and really gives an interviewer something to ask me. This lets them dive into my thought process and gives them confidence I don’t just write code without thinking.

    Add to your blog with short posts like this (or drop on LinkedIn).

  • T-SQL Tuesday #201: Temp Tables

    This month we have a new host, which I am grateful for. So many people have stopped blogging that it’s a challenge to keep this going. Jeff Taylor has an invite asking us about a core T-SQL topic that can affect the performance of your app and your server: temp tables.

    This is an interesting one for me, as I’ve changed my mind on these over the years, especially as Microsoft has made improvements to the SQL Server storage engine and query processor that have helped tempdb to perform better.

    They’ve also added things that can impact and load tempdb.

    If you want to host a T-SQL Tuesday, ping me. I’m always looking for new (or returning) hosts.

    My Answer

    My answer to Jeff’s question of temp tables as friend or foe is yes.

    They are friends.

    They are foes.

    Most things that we struggle with in database work are tradeoffs. We have to balance the demands. It’s why we say “it depends” so often because we have to find a way to do more of one thing, while accepting less of another.

    If I use temp tables in a query, I can potentially run a query to get a smaller data set that I can query with to get the results I need. I can reduce the memory grant, which might be required if the initial query scans a lot of data.

    Suppose I have a 100mm row table. If I am doing a complex join of this data on unindexed columns with multiple other tables, perhaps I want to do something like this (delivereddate might not be indexed):

    select c.customerid, o.orderid, o.delivereddate, oho.shipperid, o.salespersonid, ,qty, oh.price
    into #limitedorders
    from orderheader oh inner join orderdetail od on oh.orderid = oh.orderid
    where customerid = 12

    This can get me a filtered list of things, which I can then join this temp table with the customer, shipper, salesperson, and other tables, which will be a smaller, quicker join.

    However, a temp table can be a problem as well. If you have a query that does something like this:

    select *
    into #orderlist
    from orderheader oh inner join orderdetails od
    on oh.orderid  = od.orderid
    where oh.orderdate > dateadd(year, –10, getdate()

    And then you have some sort of query that aggregates across the years.

    select c.customername, sum(t.qty * t.price)
    from #orderlist t
    inner join customer c
    on t.customerid = c.customerid
    where customerid = 12

    I’ve done a lot of work in the first query to gather data, allocate space in tempdb, copy this over, use memory, etc. Then I am going a simple query to aggregate things, and filtering it. In this case, the developer likely followed a pattern of gather data, then sum it from other queries. It might have worked for them, but if I have 1mm orders a year, this will suck up resources.

    My Advice

    My advice is like Jeff’s. In general, try to work with a query to solve your problem. Use joins, beware of views, and make sure you’ve indexed well. Use CTEs to break down your problem, and don’t use temp tables.

    If you struggle to get a single query, or you have poor performance because of memory grants or other issues, then think about shrinking your dataset down using a temp table and indexed columns. Then join this to get other data that you need.

  • Don’t Fight with AI

    I was recently trying to handle a simple task with a few AI tools to see how well things worked. I realized that AI isn’t great for everything and there are times you need your judgment to stop fighting AI and use other tools.

    Tl;dr choose the shortest path and know your tools. In this case, just copy paste a script and results (see the bottom).

    This is part of a series of experiments with AI systems.

    The Scenario

    I have a table with some data. I wanted to duplicate this table DDL and DML for another system. Here’s my table:

    2026-07_0152

    Simple thing, right? Lots of possible ways to do this, but understand, this wasn’t the task. I was doing something else, with another goal.

    This task was just in my way.

    First Try – Prompt AI

    I use SQL Prompt all the time, so I thought, hey, AI, script this.

    2026-07_0135

    Well, not quite what I wanted. This works cross database, or if I make a new table name by editing the script in two places. But not ideal.

    2026-07_0136

    OK, I asked for the data, and this works. A bit. I only get 10 rows. To be fair, the original select I started with was top 10.

    2026-07_0142

    I then ask for the other data, and I go backwards. I don’t know why a model would go in this way. This reminds me of working with a junior person half listening to me.

    2026-07_0140

    Grrrr.

    Claude CoWork

    This seems like a cowork task. I’m not saying this is the best thing, and since I didn’t have a repo, I decided this over code. In any case, I asked for a task. Quickly Claude gave me options for 1) PoSh, 2)T-SQL, 3) something else. I picked 2 and it took about 4 minutes or so, but I got this script.

    2026-07_0146

    I had to open in VSCode, connect to SQL, and then it didn’t work:

    2026-07_0147

    Paste back into Claude, get a quick fix, maybe 15s.

    2026-07_0148

    Copy/paste the script, which runs. Certainly I could have put this back in SSMS, but I’m not sure that’s easier/harder.

    2026-07_0149

    I copy the results, which is fairly easy here.

    2026-07_0150

    I have the script I need and can move on:

    2026-07_0151

    Redgate Assistant

    We’ve added a new Redgate Assistant panel to SQL Prompt. I tried this next, and got a few results. The DDL was first, which I could copy/paste into my new query window.

    The second was a script I pasted in and ran, which gave me insert statements. Taking these results gives me about what I have above from the Claude script.

    2026-07_0145

    This was significantly faster. From prompt to result was in the 10s range and then I could get the results in a few more seconds. That’s quick, and I didn’t lose my thought context.

    The Best Way – SQL Prompt

    I’m experimenting with, and it’s been a tool I reach for often, but as I was annoyed by Claude taking so long, I realized the best way was actually this. Run the query in SQL Prompt that’s at the top. Then select all the data in the results by clicking the top left box and right click. Select “script as insert”.

    2026-07_0153

    I can then easily search/replace or edit the name of the table.

    2026-07_0154

    Doing this, once I thought about it, was about 5 seconds of effort, no context switch. Just grab this, change the name and go on with my other work on another connection.

    Use All the Tools

    I do think AI is a great tool for me. I also think it can cause me to spend more time and effort (and sometimes $$$) on simple tasks. While I’m all for experimenting, I also want to be efficient and effective.

    Fortunately, I’m somewhat paid to try different things and report on them.

    In this case, the KISS solution is best. Use Prompt what what it does best, work with your schema, code, and (lightly) data. I know I could use an MCP server, or Claude Code at al with more guidance, or something else, but those start to feel like using AI for the sake of AI and burning tokens when there are better tools.

    Not everything is better with AI. The people who succeed and prosper in this crazy AI world will embrace it when it’s most helpful and ignore it when it’s not very useful.

  • TRY_PARSE Limitations: #SQLNewBlogger

    I got a notification from a question I’d posted at SQL Server Central: Getting the Average. A user had posted their repro didn’t work, with no real comment. As a SQLNewBlogger FYI, that type of post shows poor communication and a lack of communication. I see that a lot and it’s a challenge in the modern world.

    Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

    A Quick Setup

    This was what the user posted:

    declare @t table ( id int identity , i int ); insert @t select null; insert @t select 11; select avg(try_parse(i as int)) from @t group by id;

    This does return an error, as you can see below.

    2026-07_0373

    Why?

    Well, the TRY_PARSE() docs give part of an explanation. I highlighted this in Yellow, but the relevant text says “only for converting strings”.

    2026-07_0374

    Shouldn’t an int convert to a string? No, the precedence rules have int higher than char types. We convert lower to higher, not higher to lower.

    SQLNewBlogger

    I noticed something, thought for a second why this wouldn’t work, and then checked the docs. I decided to write this up and it was a 5-10 minute post for me. Easy to do and showcasing knowledge.

    It helps me remember, might teach someone something, and gives an interviewer something to ask me. Add to your blog with short posts like this (or drop on LinkedIn).