Press "Enter" to skip to content

Category: T-SQL

Scripting SQL Agent Job Creation Scripts

Aaron Bertrand sees that it’s all funhouse mirrors:

On this site, we usually talk about SQL Server performance problems that involve execution plans, locking, indexes, and waits. But SQL Server Agent can determine when backups, maintenance, ETL, monitoring, and reporting all arrive at the instance. In a way, a job deployment script is part of your performance configuration: you can materially impact the workload if you accidentally share a schedule across too many jobs.

I often create jobs in test environments that will later get distributed to many servers, often in isolated environments that can’t see each other. Creating an idempotent script to create a job, but only if it doesn’t already exist, can be cumbersome to get right. Many will prefer to use DbaTools Copy-DbaAgentJob, and that can be a great option if your deployment mechanism is PowerShell, DbaTools is already entrenched in your environment, and you can run the script from a place that can see the other server. In our case, T-SQL scripts are often passed on to colleagues or automation to be run independently in a different environment. Apologies to friends of SSMS, but the default right-click > Script Job output leaves a lot to be desired:

Click through for a variety of problems that the scripting logic has, as well as the solution Aaron came up with.

Leave a Comment

Replacing REPLACE()s with TRANSLATE() in SQL Server

Greg Low makes use of an uncommon function:

If your T-SQL is buried under layers of nested REPLACE() calls just to swap out a few characters, there’s a simpler way. SQL Server’s TRANSLATE() function — introduced in 2017 but still rarely used — lets you replace multiple characters in a single string with one function call instead of stacking several REPLACE() functions inside each other.

This guide covers how TRANSLATE() works, how it compares to REPLACE(), and where it falls short compared to other SQL dialects like PostgreSQL and Oracle.

One important thing to remember with TRANSLATE() is that it’s a character-for-character replacement. In other words, if you TRANSLATE('ABCDEFG', 'x'), it will replace every instance of each of those characters with the letter “x.” It doesn’t replace a substring.

Leave a Comment

Taking Advantage of Newer Date Functions in SQL Server

Andy Brownsword gets beyond SQL Server 2000:

Date handling in SQL Server tends to accumulate tried and trusted combinations of DATEPART()DATEADD(), and DATEDIFF() – with nested variations. The challenge with these isn’t raw performance, but more with conveying intent and readability.

So let’s look at some simpler patterns to try and avoid some of these and be clearer with what we’re trying to achieve.

Click through for some functions that have been around since 2012, and others that just became available in 2022.

Leave a Comment

The Value of TRY_PARSE()

Steve Jones answers a question:


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.

I’d use TRY_CAST() or TRY_CONVERT() in this particular scenario. The main reason I’d use TRY_PARSE() would be if you need .NET-specific parsing functionality, such as parsing dates by a specific locale. The reason is that PARSE() and TRY_PARSE() are an order of magnitude slower than their CAST() and CONVERT() cousins.

That said, Steve’s example reminds me of a PolyBase demo I used to do, in which I took a CSV of North Carolina populations by county and read in the information. In that particular dataset, they would use the letter “A” to describe either “Not enough people to show an answer without potentially violating PII” or “We don’t know what the answer is.” So even though it was clearly a numeric attribute in “Population,” the output process overloaded the definition of that attribute and the only way you would know is to happen to see the three rows in ~1500 that happened to have an A in the column value.

Leave a Comment

Dealing with Catch-All Queries

Dualcore DBA handles an overly broad class of query:

We have a query that SELECTs from the Users table that takes multiple optional parameters and filters the output based on those.

Whilst fairly easy to read and write, queries written in this way often underperform.

This is a very generous understatement. Click through for two ways to improve the performance of such queries, as well as the pros and cons of each.

Leave a Comment

Implementing the Gauss Kronod Quadrature Formula in SQL Server

Sebastiao Pereira implements a formula:

Gauss-Kronrod quadrature is a numerical integration method that extends the Gaussian quadrature providing high accuracy and a built-in error estimation. It is based on the work of Carl Friedrich Gauss and Alexander Kronrod. The Kronrod method reuses all Gauss nodes adding extra points obtaining one integral estimate for Gauss and another for Kronrod and the differences gives the estimated error.

Click through to see how you can do this in T-SQL.

Leave a Comment

Simplifying Code via Computed Columns

Andy Brownsword moves an expression:

Computed columns allow us to bake logic into our schema. I find particular use for these when reviewing or optimising established solutions where you spot the quirky ways the data is being used.

Here I want to demonstrate 3 symptoms and show how different implementations of computed columns solve them.

Click through for the technique. It certainly won’t solve every performance problem relating to non-SARGable functions, but it does work pretty well on specific classes where you have limited control over the code.

Leave a Comment

How OR Predicates Affect Indexes

Dualcore DBA adds a clause:

We’ve created an index on both of the columns in the WHERE clause both of which are also in the SELECT list. As a reminder, non-clustered indexes implicitly include the clustered index key in the included columns even if we have not explicitly specified it and so with this in mind, our index fully covers our query. This index should be good for an index seek right? Let’s execute our query again:

This solution isn’t the only way to SQL Server to use a specific pair of indexes—you can also use the UNION operator to replace one OR, for example. And that usually resolves the issue without needing index hints.

Leave a Comment

Challenges with DATE_BUCKET()

Erik Darling has a new video:

But what’s also strange here, too, is that SQL Server estimates one row very reliably for a date bucket. So, you know, you might be careful about that as well, especially if you’re returning far more than one row. You might be unhappy with the one row estimate.

It might bring you back to the bad old days of table variables and off histogram values, stuff like that. But, yeah, anyway, I had a point with all that. Let’s do this.

Click through to learn Erik’s point.

Leave a Comment

Copy-Pasta’d Temp Tables and More Fun

Andy Levy shares some thoughts:

I’ve spent a lot of time over the past 8 or years trying to “right the ship.” Systems that have been built and evolved over 10-15 years and the cracks are starting to show. Yes, there’s always the hot spot code that desperately needs attention, the stored procedure that runs in 6 hours but could be 20 minutes with the right adjustments. But I’m looking at a macro level today, more “operational” than “surgical.” When I see __ in a chunk of code, it’s a signal to me that there are overarching problems in how the whole system I’m working on was built and it’s going to take me a good, long while to undo that to deliver constant performance as data grows or improve maintainability.

Andy’s main topic is pre-populated temp tables serving as lookup tables in queries. Though if Andy wants eldrich temp table horrors, I raise him global temp tables (##table) created from a separate session and a SQL Agent job that runs every minute to create it, with people ignoring the failures because “That’s how it’s supposed to work.”

I’ve never seen that in practice, but now I kind of want to do it.

Bonus comment: leading semi-colons for CTEs. I rarely do that, but when I do, it’s because a semi-colon on the same line as a batch separator doesn’t count. In other words,

GO;

WITH records as (...)

returns an error. There might be some workable variant, admittedly, but in those cases, I do put the semi-colon in front of the CTE. The rest of the time, when I know there isn’t a batch separator right before the common table expression, I of course don’t. Commas and semi-colons belong at the end, not the beginning.

Comments closed