Category: Transact-SQL

This category contains useful information relating to Transact SQL (TSQL).

SQL: Median function for SQL Server

I have been using a Transact-SQL query (see Method 1 – Update entire table below) to get the Median “Order Value” for an entire list of Customers. However, due to the quantity of data, it was taking for ever.

Therefore, this morning I decided to write a SQL Server User Defined Function (see Method 2 – Function below) [1. Please ensure you test any script taken from my website on a test/development machine, before running on a production server.] to update the Median Order Value for a single Customer. I then used a UPDATE query to update all of the customers. This took a lot less time to process ­čÖé

SQL: REPLACE Multiple Spaces with One

I have just found a very useful article from, that goes through the process of┬áreplacing multiple spaces with one. “Replacing multiple spaces with a single space is an old problem that people use loops, functions, and/or Tally tables for. Here’s a set based method for replacing multiple spaces from MVP Jeff Moden”