Skip to content

Clive Roberts

SQL Server DBA

Menu
  • Setup
  • Performance
  • Health Check
  • Troubleshooting
  • T-SQL
  • Patches
  • News
  • Audit
  • Projects

Category: T-SQL

Converting Money in T-SQL

November 29, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
Converting Money in T-SQL: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. Converting money in T-SQL comes up whenever amounts arrive as text, from a CSV, a spreadsheet export or a staging table where every column is varchar. The money data type is surprisingly forgiving about what it accepts, far more so than decimal, and that is both handy…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

RANK, DENSE_RANK and ROW_NUMBER

November 27, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
RANK, DENSE_RANK and ROW_NUMBER: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. RANK vs DENSE_RANK is one of those choices that looks cosmetic until a report goes out with the wrong number of rows on it. Both number rows in order and both give tied rows the same number. The difference is what happens to the number after a…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

Finding Special Characters with PATINDEX

November 24, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
Finding Special Characters with PATINDEX: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. Sooner or later every DBA gets asked to find special characters in a column: the stray tab that breaks an export, the apostrophe that upsets a downstream system, or the “space” that isn’t really a space. On SQL Server 2019 and 2022 the tool for the job…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

COUNT(*) vs COUNT(1) in SQL Server

November 23, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
COUNT(*) vs COUNT(1) in SQL Server: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. COUNT(*) vs COUNT(1) is one of the oldest arguments in SQL Server, and it still comes up in code reviews. The short answer is that they do exactly the same work. The question that actually matters is what you’re counting: rows, or non-NULL values in a column….

Read More »

Posted in Question of the Day, SQL Server, T-SQL

The T-SQL FORMAT Function

November 22, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
The T-SQL FORMAT Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The T-SQL FORMAT function turns a number or date into a string laid out the way a particular country expects. I mostly use it for one job: showing money with the right currency symbol, thousands separator and decimal mark in a report or an email, without writing…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

The Table Value Constructor in SQL Server

November 21, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
The Table Value Constructor in SQL Server: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The table value constructor is the VALUES clause that lets you write several rows in one statement: VALUES (1, ‘a’), (2, ‘b’), (3, ‘c’). Most people meet it as the multi-row INSERT, but it’s more general than that. It builds a small table on the fly, and…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

CREATE PROCEDURE in SQL Server

November 20, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
CREATE PROCEDURE in SQL Server: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. CREATE PROCEDURE is one of the first statements anyone learns in T-SQL, and most of us stop thinking about it after that. It’s worth a second look, because the rules about batches, parameters and name resolution catch out experienced people too. This is how I write procedures…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

The T-SQL AVG Function

November 19, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
The T-SQL AVG Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The T-SQL AVG function looks like the simplest aggregate there is: add the values up, divide by how many there are. Most of the time it is. But it has one habit that catches people out in reports again and again: when you average an integer column,…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

@@SERVICENAME and the SQL Server Service Name

November 17, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
@@SERVICENAME and the SQL Server Service Name: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. Every instance has a SQL Server service name, and @@SERVICENAME is the quick way to ask an instance what its name is from T-SQL. It’s a small function, but I use it in scripts that need to work the same way on default and named instances, and…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

The SQL Server bit Data Type

November 13, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
The SQL Server bit Data Type: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The SQL Server bit data type holds 1, 0 or NULL, and most of us use it for flags: IsActive, IsDeleted, HasShipped. It’s classed as an integer type, so it’s natural to assume you can add bits together or total them. You mostly can’t, and the places…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

ALTER SCHEMA TRANSFER

November 12, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
ALTER SCHEMA TRANSFER: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. ALTER SCHEMA TRANSFER moves a table, view, type or other schema-scoped object from one schema to another in the same database. It’s a metadata change, so it’s quick even on a huge table, and I use it a lot for reloads: build the new copy of a…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

The BIT_COUNT Function

November 9, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
The BIT_COUNT Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2022 and 2025. The BIT_COUNT function counts how many bits are set to 1 in an integer or binary value. It arrived in SQL Server 2022 with the other bit manipulation functions, and it replaces the loops and lookup tables we used to write to count flags packed into a bitmask….

Read More »

Posted in Question of the Day, SQL Server, T-SQL

The STRING_ESCAPE Function

November 7, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
The STRING_ESCAPE Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The STRING_ESCAPE function takes a piece of text and escapes the characters that would break it inside a JSON string: quotes, backslashes, forward slashes and control characters such as tabs and line breaks. It’s useful when you build JSON by hand, and easy to misuse when you…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

The T-SQL BETWEEN Operator

November 6, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
The T-SQL BETWEEN Operator: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The T-SQL BETWEEN operator tests whether a value falls inside a range, and it’s one of the first things most of us learn. It’s simple, but it has three habits worth knowing: both ends are included, the bounds must be in the right order, and it does…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

The T-SQL SQUARE Function

November 5, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
The T-SQL SQUARE Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The T-SQL SQUARE function does one small job: it multiplies a value by itself. I don’t reach for it often, but when I do it’s usually in a statistics query, a distance calculation or a quick sanity check on some reporting maths. It has one quirk worth…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

Using a Column Alias in ORDER BY

November 4, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
Using a Column Alias in ORDER BY: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. Using an ORDER BY alias is one of those things that feels inconsistent the first time you hit it. You give a calculated column a name in the SELECT list, sort by that name and it works. Try to filter on the same name in the WHERE…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

The T-SQL SIGN Function

November 2, 2026
| 2 Comments
| Question of the Day, SQL Server, T-SQL
The T-SQL SIGN Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. The T-SQL SIGN function tells you which side of zero a number sits on. It returns 1 for a positive value, 0 for zero and -1 for a negative value. It’s one of those small functions most people forget exists until they need to split a column…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 2 Comments

T-SQL Reserved Keywords

November 1, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
T-SQL Reserved Keywords: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. T-SQL reserved keywords are the words SQL Server needs for its own grammar: SELECT, ORDER, KEY, USER, PERCENT and about 180 others. You can still use one as a table or column name, but only if you delimit it every time you refer to it. I try…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

Adding a Column with a DEFAULT

October 31, 2026
| No Comments
| Question of the Day, SQL Server, T-SQL
Adding a Column with a DEFAULT: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. Getting an add column with default change right comes down to one word: NULL or NOT NULL. When you add a column with a default to a table that already has rows, that word decides what ends up in the existing rows. I’ve seen release scripts go…

Read More »

Posted in Question of the Day, SQL Server, T-SQL

Trailing Spaces in SQL Server

October 30, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
Trailing Spaces in SQL Server: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. SQL Server trailing spaces are one of those things that sit quietly in a table for years until a report shows two “identical” customers, or an import into another system fails on a value that looks fine on screen. They’re hard to spot because SQL Server goes…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

SQL Server Regex Functions

October 29, 2026
| 2 Comments
| Question of the Day, SQL Server, T-SQL
SQL Server Regex Functions: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2025 only. These functions don’t exist in SQL Server 2019 or 2022. For years, if you wanted proper pattern matching in T-SQL you either bent LIKE and PATINDEX out of shape or reached for a CLR assembly. SQL Server 2025 finally ships native SQL Server regex functions, built on Google’s RE2…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 2 Comments

Aggregates on Empty Sets in T-SQL

October 27, 2026
| 2 Comments
| Question of the Day, SQL Server, T-SQL
Aggregates on Empty Sets in T-SQL: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025. Aggregates on empty sets behave in a way that surprises people the first time they hit it in a report. Ask SQL Server to total an empty table and you don’t get zero rows back, and you don’t get zero either: you get one row containing NULL….

Read More »

Posted in Question of the Day, SQL Server, T-SQL 2 Comments

The SQL Server Vector Data Type

October 26, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
The SQL Server Vector Data Type: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2025 (and Azure SQL Database and Managed Instance). Not available in SQL Server 2019 or 2022. The SQL Server vector data type arrived in SQL Server 2025. It holds a fixed-length list of numbers, usually an embedding produced by an AI model, so you can find rows that are “similar” to…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

The T-SQL CHOOSE Function

October 25, 2026
| 1 Comment
| Question of the Day, SQL Server, T-SQL
The T-SQL CHOOSE Function: the T-SQL from this post in SQL Server Management Studio with its results

Applies to SQL Server 2019, 2022 and 2025 (and Azure SQL Database and Managed Instance). The T-SQL CHOOSE function returns one value from a list, picked by its position. It has been around since SQL Server 2012 and I mostly use it to turn a small number into a label: a month number into a…

Read More »

Posted in Question of the Day, SQL Server, T-SQL 1 Comment

T-SQL Performance Anti-Patterns

October 18, 2026
| 5 Comments
| T-SQL
T-SQL: T-SQL Performance Anti-Patterns

T-SQL performance anti-patterns are the code habits that stop SQL Server working in sets or using its indexes. Hardware and settings only go so far, and most slow systems have a few of these. These are the ones to look for, with what to use instead. Tested on SQL Server 2022 (Developer edition, single test…

Read More »

Posted in T-SQL 5 Comments

Read Consistency: Read Committed, RCSI and Snapshot Isolation

October 17, 2026
| No Comments
| T-SQL
T-SQL: Read Consistency: Read Committed, RCSI and Snapshot Isolation

Read consistency is about when the data you read was committed, not just whether it was. “Read committed” sounds safe: you only ever see committed data. But it says nothing about when the data was committed. A single query can read some rows before another transaction’s change and some rows after it. The row-versioning options…

Read More »

Posted in T-SQL

Error Handling in Transactions: TRY/CATCH, @@TRANCOUNT and XACT_STATE()

October 17, 2026
| 3 Comments
| T-SQL
T-SQL: Error Handling in Transactions: TRY/CATCH, @@TRANCOUNT and XACT_STATE()

Error handling in transactions decides what happens to half-finished work. Without it, a failed statement inside a transaction can leave the transaction open: the rest of the batch carries on, locks stay held, and the connection goes back to the pool with work half done. The pattern below is the one to use in every…

Read More »

Posted in T-SQL 3 Comments

Transaction Modes: Auto commit, Explicit and Implicit

October 17, 2026
| 3 Comments
| T-SQL
T-SQL: Transaction Modes: Auto commit, Explicit and Implicit

SQL Server has three transaction modes, and it runs every data change inside a transaction. The transaction mode decides who starts it and who ends it: SQL Server, your code, or the connection settings. Most surprises with “missing” changes or locks held for hours come from not knowing which mode a session is in. Tested…

Read More »

Posted in T-SQL 3 Comments

DDL and DML Audit Triggers

October 16, 2026
| 1 Comment
| T-SQL
T-SQL: DDL and DML Audit Triggers

Tested on SQL Server 2022 (Developer edition, single test instance). Triggers are the do-it-yourself way to record changes. A DDL trigger records schema changes (CREATE, ALTER, DROP); a DML trigger records data changes on one table. Prefer SQL Server Audit for who-did-what and temporal tables for row history. Use triggers when you need something those…

Read More »

Posted in T-SQL 1 Comment

Temporal Tables

October 16, 2026
| No Comments
| T-SQL
T-SQL: Temporal Tables

Tested on SQL Server 2022 (Developer edition, single test instance). A system-versioned temporal table (SQL Server 2016 onwards) keeps every previous version of each row in a history table, stamped with the time it was valid. You can query the table as it was at any moment. It answers “what did this row look like…

Read More »

Posted in T-SQL

Extended Events

October 16, 2026
| No Comments
| T-SQL
T-SQL: Extended Events

Tested on SQL Server 2022 (Developer edition, single test instance). Extended Events (XE) is the lightweight replacement for SQL Trace and SQL Profiler, which Microsoft has deprecated. Sessions are defined in T-SQL, filtered at source and written to a file, so they can run on busy production servers with little overhead. The system_health session SQL…

Read More »

Posted in T-SQL

Change Data Capture (CDC)

October 15, 2026
| No Comments
| T-SQL
T-SQL: Change Data Capture (CDC)

Tested on SQL Server 2022 (Developer edition, single test instance). Change Data Capture reads the transaction log and copies every insert, update and delete on a tracked table into a change table, with the old and new column values. Unlike Change Tracking, which only records which keys changed, CDC keeps the data itself, so it…

Read More »

Posted in T-SQL

Enabling and Resetting Service Broker

October 14, 2026
| No Comments
| T-SQL
T-SQL: Enabling and Resetting Service Broker

The SET ENABLE_BROKER statement is used in SQL Server to enable the Service Broker in a database. Service Broker is a feature for building asynchronous, message-based applications within the SQL Server database engine. When you enable Service Broker, it allows the database to send and receive messages, which can be useful for various tasks such…

Read More »

Posted in T-SQL

Service Broker in SQL Server

October 14, 2026
| No Comments
| T-SQL
T-SQL: Service Broker in SQL Server

A service broker is a framework that helps applications exchange messages containing the information required to complete the task. It was introduced in MSSQL 2005 and is used to implement native in-database asynchronous message processing functionalities. Service Broker introduces several new terminologies, which are as follows: Message: A piece of information exchanged between applications. Conversation:…

Read More »

Posted in T-SQL

OPENQUERY with Linked Servers

October 14, 2026
| No Comments
| T-SQL
T-SQL: OPENQUERY with Linked Servers

In SQL Server, linked servers allow you to connect to and run queries against external data sources (like another SQL Server, Oracle, MySQL, or even Excel) as if they were part of your local server. When you use open queries with linked servers, you’re using a specific method to send SQL statements directly to the…

Read More »

Posted in T-SQL

SET IDENTITY_INSERT

October 14, 2026
| No Comments
| T-SQL
T-SQL: SET IDENTITY_INSERT

The SET IDENTITY_INSERT statement in SQL Server allows explicit values to be inserted into the identity column of a table. This can be useful when you need to insert specific values into a column that is normally auto-incremented. Here is a brief overview of how it works: Syntax SET IDENTITY_INSERT [database_name].[schema_name].[table_name] { ON | OFF…

Read More »

Posted in T-SQL

Exporting Data to a File

October 14, 2026
| No Comments
| T-SQL
T-SQL: Exporting Data to a File

There’s more than one way to export data to a file from SQL Server. Which one I reach for depends on whether it’s a one-off or something that has to run every night. These are the ones I use: SQL Server Management Studio (SSMS): You can export query results to a file directly from SSMS….

Read More »

Posted in T-SQL

CROSS APPLY and OUTER APPLY

October 14, 2026
| No Comments
| T-SQL
T-SQL: CROSS APPLY and OUTER APPLY

The APPLY operator in SQL Server lets you join a table with a table-valued function or a correlated subquery. Key points and examples: CROSS APPLY: CROSS APPLY works like an INNER JOIN. It returns rows from the left table only if there is a matching row in the right table expression. Example: SELECT L.Name, R.Name…

Read More »

Posted in T-SQL

Common Table Expressions (CTEs)

October 14, 2026
| No Comments
| T-SQL
T-SQL: Common Table Expressions (CTEs)

Common Table Expressions (CTEs) let you to create a temporary result set that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement. The main points: Definition: A CTE is a named temporary result set that you define using a WITH clause. It can be referenced within the main query just like a regular…

Read More »

Posted in T-SQL

T-SQL Coding Conventions and Programming Guidelines

October 14, 2026
| 1 Comment
| T-SQL
T-SQL: T-SQL Coding Conventions and Programming Guidelines

Databases are the heart and soul of many enterprise applications, and it is very essential to pay special attention to database programming. I’ve seen in many occasions where database programming is overlooked, thinking that it’s something easy that be done by anyone. This is wrong. For a better performing database you need a real DBA…

Read More »

Posted in T-SQL 1 Comment

SQL Best Practices

October 13, 2026
| 3 Comments
| T-SQL
T-SQL: SQL Best Practices

My SQL programming guidelines, written with quality, performance and maintainability in mind. The list isn’t complete and I add to it as I go. Do not use SELECT * in your queries. Always use table aliases when your SQL statement involves more than one source. Use the more readable ANSI-Standard Join clauses instead of the…

Read More »

Posted in T-SQL 3 Comments

Database Engine Stored Procedures (Transact-SQL)

May 8, 2015
| No Comments
| SQL Server, T-SQL
T-SQL: Database Engine Stored Procedures (Transact-SQL)

Database Engine stored procedures are the system procedures SQL Server provides for general maintenance of an instance: configuring options, attaching and detaching databases, managing statistics, renaming objects and checking who is connected. Database Engine stored procedures I use most sp_configure: view and change instance settings, as in Database Mail Setup and Troubleshooting. sp_executesql: run parameterised…

Read More »

Posted in SQL Server, T-SQL

SET TRANSACTION ISOLATION LEVEL (Transact-SQL)

May 7, 2015
| No Comments
| SQL Server, T-SQL
T-SQL: SET TRANSACTION ISOLATION LEVEL (Transact-SQL)

READ UNCOMMITTED Specifies that statements can read rows that have been modified by other transactions but not yet committed. Transactions running at the READ UNCOMMITTED level do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would…

Read More »

Posted in SQL Server, T-SQL

CONCAT Function in SQL Server: Join Strings

May 1, 2015
| No Comments
| SQL Server, T-SQL
T-SQL: CONCAT Function in SQL Server: Join Strings

CONCAT Function Prior to SQL Server 2012, we used to use the “+” operator to combine or concatenate two or more string values but starting with SQL Server 2012, we can use CONCAT function to perform this type of operation more neatly. For example, the below script and screenshot shows usage of the “+” operator…

Read More »

Posted in SQL Server, T-SQL

STUFF Function in SQL Server: Insert or Replace Text

May 1, 2015
| No Comments
| SQL Server, T-SQL
T-SQL: STUFF Function in SQL Server: Insert or Replace Text

STUFF Function We looked at using the CONCAT function to concatenate or combine two or more string values. With this function, string values are appended at the end of the prior string but there are times when you want to insert a string value into another string value or replace a part of one string…

Read More »

Posted in SQL Server, T-SQL

SET XACT_ABORT ON: Stop Open Transactions After Timeouts

March 30, 2015
| No Comments
| SQL Server, T-SQL
T-SQL: SET XACT_ABORT ON: Stop Open Transactions After Timeouts

SET XACT_ABORT is helpful in many ways. example: suppose you are working on a stored procedure which is doing a complex data manipulation. You though this query will run with in 1 minute when you run it from .NET or other code , but some how it took quite long time and with in one…

Read More »

Posted in SQL Server, T-SQL

Locking hint

March 7, 2015
| No Comments
| SQL Server, T-SQL
T-SQL: Locking hint

Locking hint Description HOLDLOCK Hold a shared lock until completion of the transaction instead of releasing the lock as soon as the required table, row, or data page is no longer required. HOLDLOCK is equivalent to SERIALIZABLE. NOLOCK Do not issue shared locks and do not honor exclusive locks. When this option is in effect,…

Read More »

Posted in SQL Server, T-SQL

SQL Server PIVOT Example: Turn Rows into Columns

June 9, 2014
| No Comments
| SQL Server, T-SQL
T-SQL: SQL Server PIVOT Example: Turn Rows into Columns

select pvt.abc,pvt.def,pvt.ghi from ( SELECT ConnectionName, Connection.ConnectionString FROM dbo.Global_Applications_ConnectionString AS Connection ) AS SourceTable pivot ( min(ConnectionString) for ConnectionName in (abc,def,ghi) ) as pvt

Read More »

Posted in SQL Server, T-SQL

LAST_VALUE in SQL Server: Window Function Example

January 15, 2014
| No Comments
| SQL Server, T-SQL
T-SQL: LAST_VALUE in SQL Server: Window Function Example

SELECT CustomerID , SalesOrderID , CAST(OrderDate AS DATE) AS OrderDate , TotalDue , LAST_VALUE(TotalDue) OVER ( PARTITION BY CustomerID ORDER BY SalesOrderID ) AS TD FROM Sales.SalesOrderHeader ORDER BY CustomerID

Read More »

Posted in SQL Server, T-SQL

Parse XML into a Table in SQL Server (Stored Procedure)

December 15, 2013
| No Comments
| SQL Server, T-SQL
T-SQL: Parse XML into a Table in SQL Server (Stored Procedure)

CREATE PROCEDURE dbo.ParseXMLtoTable @strXML AS XML ,@rootnode NVARCHAR(255) AS BEGIN SET NOCOUNT ON DECLARE @strText AS NVARCHAR(MAX) ,@idoc INT ,@id INT ,@parentid INT IF OBJECT_ID(‘tempdb..#ChildList’) IS NOT NULL DROP TABLE #ChildList CREATE TABLE #ChildList ( [RowNum] INT IDENTITY(1,1) NOT NULL, [parentid] INT NULL, [id] INT NULL, PRIMARY KEY (RowNum)) IF OBJECT_ID(‘tempdb..#NodeList’) IS NOT NULL DROP…

Read More »

Posted in SQL Server, T-SQL

Count How Many Times a String Appears in Text (T-SQL)

November 15, 2013
| No Comments
| SQL Server, T-SQL
T-SQL: Count How Many Times a String Appears in Text (T-SQL)

IF EXISTS (SELECT * FROM sys.objects WHERE type = ‘P’ AND name = ‘Usp_findstring’) DROP PROCEDURE Usp_findstring GO CREATE PROC Usp_findstring (@INPUTSTRING VARCHAR(max), @SEARCHSTRING VARCHAR(500)) AS BEGIN DECLARE @OCCURENCES AS INT, @POSITION AS INT, @RETURNVALUE INT SET @OCCURENCES = 0 SET @POSITION = 0 WHILE @POSITION < Len(@INPUTSTRING) BEGIN IF Charindex(@SEARCHSTRING, @INPUTSTRING, @POSITION) > 0…

Read More »

Posted in SQL Server, T-SQL

Calculate the Duration Between Two DATETIMEs in SQL Server

March 15, 2013
| No Comments
| SQL Server, T-SQL
T-SQL: Calculate the Duration Between Two DATETIMEs in SQL Server

— “DT” is an abbreviation for “DATETIME”, not “DATE” DECLARE @StartDT DATETIME ,@EndDT DATETIME ; SELECT @StartDT = ‘2000-01-01 10:30:50.780’ ,@EndDT = ‘2000-01-02 12:34:56.789’ ; –===== Display the dates and the duration SELECT StartDT = @StartDT ,EndDT = @EndDT ,Duration = @EndDT-@StartDT ;

Read More »

Posted in SQL Server, T-SQL

Export Query Results to a File with bcp and xp_cmdshell

September 19, 2011
| No Comments
| SQL Server, T-SQL
T-SQL: Export Query Results to a File with bcp and xp_cmdshell

How to output a file from a stored procedures in MS SQL, this is how I did it a few years ago exec master..xp_cmdShell ‘bcp “SELECT url.loc, url.publication_date, url.keywords FROM ICONews..vw_googlenews url For XML Auto,Elements” queryout C:\Inetpub\wwwroot\website\SQL\google.xml -c -t, -T -S IP address’ Link: http://www.sqlteam.com/article/exporting-data-programatically-with-bcp-and-xp_cmdshell

Read More »

Posted in SQL Server, T-SQL

Get the First Day of the Month in SQL Server

March 2, 2010
| No Comments
| SQL Server, T-SQL
T-SQL: Get the First Day of the Month in SQL Server

MS SQL To find the start of the month This code: DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) was excuted on 2/3/2010 at 16:11 the result: 01/03/2010 00:00:00 DBA-sentinel

Read More »

Posted in SQL Server, T-SQL

SQL Server DBA Handbook

Setup, backup and high availability (37)
  • Backing Up and Restoring a Database
  • Restoring a Full Database Backup (SSMS)
  • Restoring a Database to a New Location
  • Backup and Restore with T-SQL
  • Disaster Recovery Planning
  • Basic vs Advanced High Availability
  • Adding a Database to an Availability Group
  • Suspending and Resuming Data Movement
  • Availability Group Health Troubleshooting
  • Quorum Failure
  • Log Shipping
  • Database Mail Setup and Troubleshooting
  • Moving TempDB
  • Database Snapshots
  • Server Build Checklist
  • Encryption
  • TDE: Backing Up the Certificate
  • Data Obfuscation and Masking
  • SQL Server Audit
  • FILESTREAM
  • Orphaned SQL Logins
  • Replicating SQL Server Logins with Their SIDs
  • Login Failures (Error 18456)
  • Random Password Generator
  • Generating the SPNs (Kerberos)
  • SQL Server Replication: Setup, Types and Pitfalls
  • Adding an Article to a Publication
  • Enabling Change Tracking: Good and Bad Points
  • Migrating a Reporting Services Installation (Native Mode)
  • Upgrading SSRS 2005 to 2012 (Quick and Dirty)
  • Azure SQL Options
  • Migrating SQL Server to Azure
  • Building an Availability Group
  • Failover Cluster Instances and Distributed Availability Groups
  • Backup to URL and Backup Encryption
  • PowerShell and dbatools
  • SQL Server Trace Flags
Performance (16)
  • Database Performance Tuning and Index Strategy
  • Data Compression
  • Forwarded Records
  • NUMA
  • Common Memory Issues
  • Average Write Performance
  • Stress Testing the I/O Subsystem with SQLIO
  • When the SQL Server Cache Needs to Be Cleared
  • Parameter Sniffing
  • Table Partitioning
  • Resource Governor
  • What Happens During a Data Change: Buffer Pool, Write-Ahead Log and Durability
  • Measuring Query Performance and Taking a Baseline
  • Reading Execution Plans
  • Plan Caching and Parameterization
  • Statistics Problem or Caching Problem?
Troubleshooting (21)
  • Database Suspect, Recovery Pending or Stuck Recovering
  • Shrinking Databases
  • Transaction Log Full
  • Data File Full and Disk Space (Error 1105)
  • Shrinking Transaction Logs
  • Stopping a Running Job in Job Activity Monitor
  • Failed SQL Agent Job Triage
  • Single-User Mode
  • Tempdb Full or Contention
  • Repairing the WMI Provider (mofcomp)
  • SQL Server Referencing the Wrong Disk Drives
  • Performance Troubleshooting Queries
  • High CPU Troubleshooting
  • SQL Locks
  • SQL Server Error Numbers
  • Monitoring Deadlocks
  • Sleeping Processes
  • DMVs and Session Monitoring
  • Collecting Data with Performance Monitor
  • Collecting a Trace with SQL Profiler
  • Schema Locks and Online Index Maintenance
T-SQL (17)
  • SQL Best Practices
  • T-SQL Coding Conventions and Programming Guidelines
  • Common Table Expressions (CTEs)
  • CROSS APPLY and OUTER APPLY
  • Exporting Data to a File
  • SET IDENTITY_INSERT
  • OPENQUERY with Linked Servers
  • Service Broker in SQL Server
  • Enabling and Resetting Service Broker
  • Change Data Capture (CDC)
  • Extended Events
  • Temporal Tables
  • DDL and DML Audit Triggers
  • Transaction Modes: Autocommit, Explicit and Implicit
  • Error Handling in Transactions: TRY/CATCH, @@TRANCOUNT and XACT_STATE()
  • Read Consistency: Read Committed, RCSI and Snapshot Isolation
  • T-SQL Performance Anti-Patterns

Question of the Day

Setup, backup and high availability (5)
  • Encrypting SQL Server Connections
  • SQL Server Certificate Expiry
  • Moving the SQL Server Error Log
  • Backing Up the Database Master Key
  • Fixed Server Roles in SQL Server
Performance (3)
  • Query Store Capture Mode
  • Rebuilding All Indexes on a Table
  • Disabled Indexes in SQL Server
Troubleshooting (3)
  • Running Scripts with the sqlcmd Utility
  • SQL Server Audit Failures
  • Starting SQL Server with Minimal Configuration
T-SQL (24)
  • Converting Money in T-SQL
  • RANK, DENSE_RANK and ROW_NUMBER
  • Finding Special Characters with PATINDEX
  • COUNT(*) vs COUNT(1) in SQL Server
  • The T-SQL FORMAT Function
  • The Table Value Constructor in SQL Server
  • CREATE PROCEDURE in SQL Server
  • The T-SQL AVG Function
  • @@SERVICENAME and the SQL Server Service Name
  • The SQL Server bit Data Type
  • ALTER SCHEMA TRANSFER
  • The BIT_COUNT Function
  • The STRING_ESCAPE Function
  • The T-SQL BETWEEN Operator
  • The T-SQL SQUARE Function
  • Using a Column Alias in ORDER BY
  • The T-SQL SIGN Function
  • T-SQL Reserved Keywords
  • Adding a Column with a DEFAULT
  • Trailing Spaces in SQL Server
  • SQL Server Regex Functions
  • Aggregates on Empty Sets in T-SQL
  • The SQL Server Vector Data Type
  • The T-SQL CHOOSE Function

All Question of the Day posts (35)

Categories

Sidebar

  • Handbook, news and patches (121)
  • Regain sysadmin access (1)
  • Kill SQL processes (1)
  • Configure MSDB (13)
  • TempDB in use (1)
  • Connected to SQL (1)
  • Move backups (2)
  • VLF details (1)
  • Config Manager error (1)
  • Fill factor (1)
  • Missing indexes (1)
  • Number of cores (1)
  • DBCC CHECKDB (1)
  • Wait times (7)
  • Tail-log backup (1)
  • STUFF function (6)
  • Blocking and deadlocks (2)
  • Locking hints (2)
  • Errors 823, 824, 825 (1)
  • DBCC commands (1)
  • Transaction counts (1)
  • Database details (1)
  • Replication (1)
  • Find jobs (1)
  • Backup progress (1)
  • Pivot table (1)
  • Replication objects (1)
  • Tables with no PK (1)
  • Who dropped the database (1)
  • last_value (1)
  • Parse XML (1)
  • Search a string (1)
  • DATETIME difference (1)
  • Error 3707 (1)
  • SHRINKDATABASE (1)
  • Express backup (1)
  • Enable xp_cmdshell (1)
  • Output a file (1)
  • Start of the month (1)

RSS feed: Clive Roberts Clive Roberts

  • RANK, DENSE_RANK and ROW_NUMBER
    Applies to SQL Server 2019, 2022 and 2025. RANK vs DENSE_RANK is one of those choices that looks cosmetic until a report goes out with the wrong number of rows on it. Both number rows in order and both give tied rows the same number. The difference is what happens to the number after a... […]

Recent Posts

  • Converting Money in T-SQL
  • Maintenance Scripts: Ola Hallengren’s Maintenance Solution 20261129_113033
  • RANK, DENSE_RANK and ROW_NUMBER
  • News: [Video] Office Hours: Reflecting on Microsoft Ignite from Cabo
  • Encrypting SQL Server Connections
  • News: Microsoft’s AI Skills Repo Has a Lot of Potential.
  • Running Scripts with the sqlcmd Utility
  • News: What to Do When the SQL Server Keeps Crashing
  • Finding Special Characters with PATINDEX
  • SQL Server Installs Tested Before and After with dbatools and Pester
  • COUNT(*) vs COUNT(1) in SQL Server
  • The T-SQL FORMAT Function
  • News: SQL Server 2022 SQLskills Blackbelt Credly badge now available
  • The Table Value Constructor in SQL Server
  • CREATE PROCEDURE in SQL Server
  • News: [Video] Office Hours: Back from the PASS Summit
  • The T-SQL AVG Function
  • News: Black Friday Sale – Blackbelt for $399!
  • Capacity Report: When Each Drive Will Be Full
  • SQL Server Security Report: Who Has sysadmin, and What Changed
  • SQL Server Patch Report: Every Instance Against Its Target Build
  • Windows Patch Report: Did This Month’s Updates Land?
  • Integrity Check Report: Proving CHECKDB Actually Ran
  • News: Modernize your apps with Azure SQL Database Hyperscale
  • News: Would Open-Sourcing Microsoft SQL Server Actually Fix Anything?
  • SQL Server Certificate Expiry
  • News: Make Your Nightly ETL Faster with TABLOCKX
  • @@SERVICENAME and the SQL Server Service Name
  • Moving the SQL Server Error Log
  • News: FGCB_ADD_REMOVE Latch Investigation Demo
  • Who Is Really a Sysadmin? Expanding AD Groups in SQL Server with xp_logininfo
  • SSIS Error Report: Finding the Package That Failed
  • Backup Report: Is Every Database Backed Up?
  • Database Inventory Report
  • SQL Server Inventory Report
  • Disk Space Alerts for SQL Server
  • Server Availability Report: Ping and Response Time
  • SQL Server Licensing Report
  • Query Store Capture Mode
  • SQL Server Audit Failures
  • News: [Video] Office Hours in the Backyard
  • The SQL Server bit Data Type
  • News: What Students are Saying About My Latest Classes
  • ALTER SCHEMA TRANSFER
  • News: How to Set Background Images & Movies in SSMS v22
  • Starting SQL Server with Minimal Configuration
  • News: Are Blogs Still Relevant? #tsql2sday
  • Backing Up the Database Master Key
  • News: Free Webcast: My Favorite Query Hints
  • News: Announcing Microsoft Database Hub: An Incredible Pace of Innovation
  • The BIT_COUNT Function
  • Rebuilding All Indexes on a Table
  • The STRING_ESCAPE Function
  • The T-SQL BETWEEN Operator
  • News: [Video] Office Hours: An AI Agent Stops In to Ask a Question
  • The T-SQL SQUARE Function
  • News: The Top 10 SQL Server Wait Types, Worldwide
  • Using a Column Alias in ORDER BY
  • Disabled Indexes in SQL Server
  • News: Who’s Hiring Database People? November 2026 Edition
  • The T-SQL SIGN Function
  • News: My Black Friday Sale on Training Classes is Open Now!
  • T-SQL Reserved Keywords
  • Patch: SQL Server 2022 CU28 (build 16.0.4325.4)
  • Patch: SQL Server 2025 CU11 (build 17.0.5065.9)
  • Patch: SQL Server 2017 CU31 + GDR (build 14.0.3570.2)
  • Patch: SQL Server 2017 GDR (build 14.0.2150.2)
  • Patch: SQL Server 2019 CU32 + GDR (build 15.0.4510.2)
  • Patch: SQL Server 2019 GDR (build 15.0.2210.4)
  • Patch: SQL Server 2022 CU27 + GDR (build 16.0.4315.2)
  • Patch: SQL Server 2022 GDR (build 16.0.1220.3)
  • Patch: SQL Server 2025 CU10 + GDR (build 17.0.5045.3)
  • Patch: SQL Server 2025 GDR (build 17.0.1155.3)
  • Adding a Column with a DEFAULT
  • News: [Video] Office Hours: 4 Great Questions Off Canada
  • Trailing Spaces in SQL Server
  • News: Meet Hugo Kornelis, Execution Plan Expert.
  • SQL Server Regex Functions
  • News: Why You Don’t Get Parallelism When You Ask for The Whole Table
  • Fixed Server Roles in SQL Server
  • News: New Stuff in the Mastering Server Tuning Class
  • Aggregates on Empty Sets in T-SQL
  • News: This Friday’s the Deadline for My Next Live Class Rotation.
  • The SQL Server Vector Data Type
  • The T-SQL CHOOSE Function
  • News: [Video] Talking Pronouns in Alaska
  • News: Why’s This Query So Slow in Prod? Check sp_BlitzPlanCompare.
  • News: AI Stories and Thoughts
  • News: I’m Probably Not Supposed To Show You Microsoft’s Auto-Indexing Tool.
  • SQL Server Trace Flags
  • Statistics Problem or Caching Problem?
  • Plan Caching and Parameterization
  • T-SQL Performance Anti-Patterns
  • Reading Execution Plans
  • Measuring Query Performance and Taking a Baseline
  • News: Thoughts on AI After My Panel Discussion
  • Read Consistency: Read Committed, RCSI and Snapshot Isolation
  • Schema Locks and Online Index Maintenance
  • What Happens During a Data Change: Buffer Pool, Write-Ahead Log and Durability
  • Error Handling in Transactions: TRY/CATCH, @@TRANCOUNT and XACT_STATE()
  • Transaction Modes: Auto commit, Explicit and Implicit
  • PowerShell and dbatools
  • Resource Governor
  • Table Partitioning
  • Backup to URL and Backup Encryption
  • Failover Cluster Instances and Distributed Availability Groups
  • Building an Availability Group
  • Parameter Sniffing
  • DDL and DML Audit Triggers
  • Temporal Tables
  • Extended Events
  • Change Data Capture (CDC)
  • Migrating SQL Server to Azure
  • Azure SQL Options
  • News: [Video] Office Hours on the Last Alaskan Cruise of the Season
  • Upgrading SSRS 2005 to 2012 (Quick and Dirty)
  • Migrating a Reporting Services Installation (Native Mode)
  • Health Check 00: is this SQL Server running well?
  • Health Check 01: server overview
  • Health Check 02: databases
  • Health Check 03: backups
  • Health Check 04: disks and files
  • Health Check 05: SQL Agent jobs
  • Health Check 06: wait statistics
  • Health Check 07: activity and blocking
  • Health Check 08: error log
  • Health Check 09: integrity checks
  • Health Check 10: memory and CPU
  • Health Check 11: tempdb
  • Health Check 12: high availability
  • Performance 01: top queries
  • Performance 02: Query Store regressions
  • Performance 03: missing indexes
  • Performance 04: unused indexes
  • Performance 05: statistics age
  • Performance 06: index fragmentation
  • Performance 07: cardinality estimate skew
  • Performance 08: filtered statistics candidates
  • Performance 09: duplicate and overlapping indexes
  • Performance 10: statistics health
  • Performance 11: cardinality estimator audit
  • Performance 12: implicit conversions
  • Enabling Change Tracking: Good and Bad Points
  • Adding an Article to a Publication
  • SQL Server Replication: Setup, Types and Pitfalls
  • Enabling and Resetting Service Broker
  • Service Broker in SQL Server
  • OPENQUERY with Linked Servers
  • News: Breaking News: Hold Off on SSMS 22.11.0
  • News: Fact-Checking Microsoft’s “PostgreSQL to SQL Field Notes: Connections”
  • SET IDENTITY_INSERT
  • Exporting Data to a File
  • CROSS APPLY and OUTER APPLY
  • Common Table Expressions (CTEs)
  • T-SQL Coding Conventions and Programming Guidelines
  • SQL Best Practices
  • Generating the SPNs (Kerberos)
  • Random Password Generator
  • News: Free Webcast: How to Think Like the SQL Server & Postgres Engines
  • Login Failures (Error 18456)
  • Replicating SQL Server Logins with Their SIDs
  • Orphaned SQL Logins
  • FILESTREAM
  • SQL Server Audit
  • Patch: SQL Server 2017 CU31 + GDR (build 14.0.3560.2)
  • Patch: SQL Server 2017 GDR (build 14.0.2140.2)
  • Patch: SQL Server 2019 CU32 + GDR (build 15.0.4500.2)
  • Patch: SQL Server 2019 GDR (build 15.0.2200.2)
  • Patch: SQL Server 2022 CU27 + GDR (build 16.0.4305.5)
  • Patch: SQL Server 2022 GDR (build 16.0.1210.3)
  • Patch: SQL Server 2025 CU9 + GDR (build 17.0.5015.4)
  • Patch: SQL Server 2025 GDR (build 17.0.1145.4)
  • Data Obfuscation and Masking
  • TDE: Backing Up the Certificate
  • Encryption
  • Collecting a Trace with SQL Profiler
  • Collecting Data with Performance Monitor
  • DMVs and Session Monitoring
  • Sleeping Processes
  • Monitoring Deadlocks
  • SQL Server Error Numbers
  • SQL Locks
  • High CPU Troubleshooting
  • Performance Troubleshooting Queries
  • When the SQL Server Cache Needs to Be Cleared
  • Stress Testing the I/O Subsystem with SQLIO
  • Average Write Performance
  • Common Memory Issues
  • NUMA
  • Forwarded Records
  • Data Compression
  • Database Performance Tuning and Index Strategy
  • Server Build Checklist
  • SQL Server Referencing the Wrong Disk Drives
  • Repairing the WMI Provider (mofcomp)
  • Database Snapshots
  • Tempdb Full or Contention
  • Moving TempDB
  • Single-User Mode
  • Database Mail Setup and Troubleshooting
  • Setup
  • Performance
  • Health Check
  • Troubleshooting
  • T-SQL
  • Patches
  • News
  • Audit
  • Projects

Precious Lite 2025 | All Rights Reserved. Precious Lite theme by Flythemes