Server Interaction  «Prev  Next»
Lesson 4 Functions, part 2
Objective Understand how SQL-Server functions can be used

Transact-SQL Function Statements

The previous lesson covered how to call a function: parentheses, arguments, nesting. This lesson works through several common, concrete ways functions show up inside real Transact-SQL statements, not just in isolation, so you can recognize the pattern wherever it appears: a function wrapped around a column, a value fed to a function and tested, or a session-level function checked right after the statement it describes. The same handful of examples, built around a single dbo.clients table, run throughout this lesson so the differences between statements stand out rather than the differences between example schemas.

Text and Numeric Functions: SUBSTRING, UPPER, and TRY_CONVERT

Text and numeric functions: SUBSTRING, UPPER, and TRY_CONVERT examples against dbo.clients
Text and numeric functions: transforming values and testing conversion

SUBSTRING(expression, start, length) returns a specified number of characters from a string, starting at a given position. The statement below returns every column from dbo.clients, but only where the first character of the ClientType column is 'P':
SELECT *
FROM dbo.clients
WHERE SUBSTRING(ClientType, 1, 1) = 'P';

Positions start at 1, and the text comparison follows the database's collation. SUBSTRING is the general-purpose tool for pulling characters out of the middle, start, or end of a string. For the specific case of checking the first character, as above, LEFT(ClientType, 1) = 'P' is the more idiomatic modern equivalent, and SQL Server 2025's REGEXP_LIKE(ClientType, '^P') is a third option; SUBSTRING is shown here because it is the most general of the three and works for the middle of a string too, not just the start.

UPPER converts a string to uppercase, which is especially useful when the case of existing text is inconsistent or unknown. The statement below updates every row in the ClientName column of dbo.clients, with no WHERE clause, so every row changes:
UPDATE dbo.clients
SET ClientName = UPPER(ClientName);

Unlike the SELECT statement above, this is a function used inside an UPDATE, a reminder that functions are not limited to the column list of a query; they can transform a value anywhere an expression is expected, including on the right side of a SET clause.

TRY_CONVERT attempts a conversion and returns NULL instead of raising an error when the conversion fails, which makes it useful for validating data before committing to a stricter CONVERT or CAST:
DECLARE @val1 varchar(10) = 'C101';
IF TRY_CONVERT(decimal(10,2), @val1) IS NOT NULL
    SELECT 'Convertible' AS Result;
ELSE
    SELECT 'Not convertible' AS Result;

Here @val1 holds 'C101', which TRY_CONVERT cannot turn into a decimal(10,2), so the result is 'Not convertible'. A related caution: ISNUMERIC, SQL Server's older numeric-check function, is not a reliable digits-only test; it returns 1 for several values that are not plain numbers, such as currency symbols, a bare decimal point, or scientific notation, so testing conversion against the specific target type you actually need, with TRY_CONVERT, is the more dependable check.

Two more string functions round out this category, both useful for locating rather than extracting text. CHARINDEX returns the starting position of one string inside another, and PATINDEX does the same with a wildcard pattern instead of a literal substring:
SELECT ClientID, CHARINDEX('@', ContactEmail) AS AtSignPosition
FROM dbo.clients;

SELECT ClientID, PATINDEX('%[0-9]%', ClientName) AS FirstDigitPosition
FROM dbo.clients;

Both return 0, not an error, when the search text is not found, so a result needs to be checked against 0 rather than against NULL. SUBSTRING is often paired with one of these two: find a position first, then extract around it.

Session and Execution Status: @@FETCH_STATUS, @@SPID, and @@ROWCOUNT

Session and execution status: @@FETCH_STATUS, @@SPID, and @@ROWCOUNT examples against dbo.clients
Session and execution status: inspecting fetches, sessions, and affected rows

@@FETCH_STATUS reports whether the most recent FETCH against a cursor succeeded; 0 means it did. The example below loops through every row of dbo.clients one at a time:
DECLARE @val1 int;
DECLARE curTmp CURSOR LOCAL FAST_FORWARD FOR
    SELECT ClientID FROM dbo.clients;
OPEN curTmp;
FETCH NEXT FROM curTmp INTO @val1;
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @val1 AS ClientID;
    FETCH NEXT FROM curTmp INTO @val1;
END;
CLOSE curTmp;
DEALLOCATE curTmp;

@@FETCH_STATUS is connection-wide: if more than one cursor is open, a FETCH against either one changes the same status value, so check it immediately after the FETCH it is meant to describe. Each pass through the loop here also returns its own one-row result set rather than one combined result set; for a task this simple, a single SELECT ClientID FROM dbo.clients needs no cursor at all and returns everything at once in one result set.

@@SPID identifies the current SQL Server session, a session ID rather than an operating-system process ID:
SELECT @@SPID AS SessionID;

@@ROWCOUNT reports how many rows the previous statement affected, and is most useful captured into a variable immediately afterward, since a later statement resets it:
DECLARE @RowsAffected int;
UPDATE dbo.clients
SET ClientType = 'P'
WHERE ClientID = 103;
SET @RowsAffected = @@ROWCOUNT;
IF @RowsAffected = 0
    SELECT 'No rows were updated' AS Message;
ELSE
    SELECT @RowsAffected AS RowsAffected;

Two related points are worth keeping in mind alongside @@ROWCOUNT. First, SET NOCOUNT ON, often added to stored procedures to suppress the "(N rows affected)" message sent back to the client, does not change what @@ROWCOUNT itself reports; it only silences the separate message, so code that reads @@ROWCOUNT keeps working exactly the same whether NOCOUNT is on or off. Second, @@CURSOR_ROWS is a related session function worth knowing about alongside @@FETCH_STATUS: it reports the number of rows in the most recently opened cursor's result set, which is useful for sizing progress reporting around a long-running cursor loop like the one above.

Date and Time Functions

Date and time functions retrieve the system date and manipulate date and time values already stored in a table. A few of the most common, continuing the same dbo.clients/dbo.employees examples used throughout this lesson:
SELECT GETDATE() AS CurrentDateTime;

SELECT DATEADD(day, 30, OrderDate) AS DueDate
FROM dbo.orders;

SELECT DATEDIFF(day, HireDate, GETDATE()) AS DaysEmployed
FROM dbo.employees;

SELECT DATEPART(quarter, HireDate) AS HireQuarter, EOMONTH(HireDate) AS HireMonthEnd
FROM dbo.employees;

GETDATE retrieves the current date and time with no arguments, as covered in the previous lesson. DATEADD adds a specified interval, here 30 days, to a date value. DATEDIFF returns the difference between two dates in a specified unit, here the number of days since each employee's HireDate. DATEPART extracts a single component, such as the calendar quarter, from a date value, and EOMONTH returns the last day of the month containing a given date, useful for month-end reporting without manually working out how many days a given month has. All four follow the same calling conventions as the functions above: positional arguments, used inside an ordinary SELECT.

FORMAT is worth a separate mention because it behaves differently from the functions above: it converts a date, time, or number to a string using a specified .NET format string or a culture name, which gives it far more display flexibility than CONVERT's fixed style codes:
SELECT FORMAT(HireDate, 'MMMM d, yyyy', 'en-US') AS HireDateFormatted
FROM dbo.employees;

That flexibility has a real cost: FORMAT is noticeably slower than CONVERT or CAST for the same job, since it relies on the .NET formatting engine rather than SQL Server's own lighter-weight string conversion, so it is a better fit for a final display column in a report than for a value computed row by row across a very large table.

Identifying Functions in SQL Server Management Studio

SQL Server Management Studio (SSMS) color-codes Transact-SQL as you type it, which makes built-in functions easy to spot at a glance. In SSMS's default color scheme, built-in (system) functions appear in magenta, keywords in blue, and string literals in red. The following statement illustrates all three in one line:
DECLARE @val int;
SET @val = 5;
SELECT 'The value is ' + CAST(@val AS varchar);
Magenta marks built-in functions in SSMS's default color scheme

CAST is the function that would display in magenta here; DECLARE, SET, and SELECT are keywords, shown in blue; and 'The value is ' is a string literal, shown in red.

SSMS is not the only editor you might see this course's examples run in. Azure Data Studio was once presented as a lightweight, cross-platform alternative, but Microsoft retired it, with support ending February 28, 2026; Visual Studio Code with the MSSQL extension is the current lightweight alternative, alongside sqlcmd for the command line. Whichever editor you use, the color-coding categories described above are specific to SSMS's own default scheme and may differ elsewhere.

A Pitfall Worth Knowing: Functions Can Block Index Use

Every example above wraps a function around a value and gets back a useful result, but wrapping a function around an indexed column in a WHERE clause carries a cost worth knowing about. The SUBSTRING example earlier in this lesson,
WHERE SUBSTRING(ClientType, 1, 1) = 'P'

forces SQL Server to evaluate SUBSTRING against every row's ClientType value before it can compare the result to 'P', which means an index on ClientType cannot be used to seek directly to the matching rows; the optimizer has to scan the whole table or index instead. A predicate like this is called non-sargable, from "Search ARGument ABLE." Rewriting the same check as a pattern match lets SQL Server seek the index instead of scanning it:
WHERE ClientType LIKE 'P%'

Both statements return the same rows. The difference only shows up in execution plans and query cost on larger tables, which is exactly why it is easy to miss: the SUBSTRING version is not wrong, it simply gives up an optimization opportunity that a small rewrite would have kept. The general rule: when a predicate's whole purpose is filtering on a column, prefer a form that leaves the column itself unwrapped on at least one side of the comparison.

The distinction is specifically about which side of the comparison the function wraps. Wrapping the value you are comparing against, rather than the column, does not cause the same problem:
WHERE HireDate >= DATEADD(year, -1, GETDATE())

Here DATEADD and GETDATE compute a single value once, before the comparison runs against HireDate, which stays unwrapped and fully available to an index. The earlier SUBSTRING example is a problem precisely because it wraps ClientType, the column being searched, not a fixed value computed once. Checking an execution plan is the reliable way to confirm which case you are in: SSMS's "Include Actual Execution Plan" option shows whether a query against an indexed column produced an index seek or fell back to a scan, which is a more trustworthy signal than guessing from the statement's text alone.

Functions in Statements with SQL Server 2025's Newer Capabilities

The function-in-a-statement pattern covered throughout this lesson, a function wrapped around a value inside a SELECT, WHERE, or UPDATE, applies just as directly to SQL Server 2025's newer functions, continuing the same dbo.clients table used throughout this lesson.

REGEXP_LIKE filters rows with a pattern, used in a WHERE clause exactly like the SUBSTRING and LIKE examples above:
SELECT ClientID, ClientType
FROM dbo.clients
WHERE REGEXP_LIKE(ClientType, '^P');

JSON_VALUE reads a scalar value out of a JSON column inside the column list of a SELECT:
SELECT ClientID, JSON_VALUE(ClientPreferences, '$.contactMethod') AS PreferredContact
FROM dbo.clients;

VECTOR_DISTANCE slots into an ORDER BY clause the same way any other scalar function would, ranking rows by similarity instead of by an ordinary column:
SELECT ClientID, VECTOR_DISTANCE('cosine', @QueryVector, PreferenceEmbedding) AS Distance
FROM dbo.clients
ORDER BY Distance;

And a WITH common table expression can wrap any of the statements above, exactly as it can wrap a plain SELECT:
WITH PClients AS (
    SELECT ClientID, ClientName, ClientType
    FROM dbo.clients
    WHERE ClientType LIKE 'P%'
)
SELECT ClientID, UPPER(ClientName) AS ClientNameUpper
FROM PClients;

VECTOR_DISTANCE also combines naturally with a WHERE clause and an ORDER BY in the same statement, narrowing to genuinely close matches before ranking them:
SELECT ClientID, VECTOR_DISTANCE('cosine', @QueryVector, PreferenceEmbedding) AS Distance
FROM dbo.clients
WHERE VECTOR_DISTANCE('cosine', @QueryVector, PreferenceEmbedding) <= 0.3
ORDER BY Distance;

Each of these is the same lesson in a new wrapper: a function belongs anywhere a value is expected in a statement, old function or new, and the same sargability caution from the previous section applies to REGEXP_LIKE and JSON_VALUE just as it does to SUBSTRING, since both wrap the column they filter on.

A Few More Things to Watch For

A short list of habits worth building alongside the examples above:
  1. NULL propagates through most functions. UPPER(NULL) returns NULL, not an empty string; a row with a NULL in the column a function wraps will not match a comparison against a literal value unless you account for it separately, often with ISNULL or COALESCE.
  2. Nondeterministic functions complicate repeatable tests. A test that calls GETDATE() directly can pass today and fail tomorrow once enough time has passed; passing a fixed date variable into the function under test, rather than letting it call GETDATE() itself, keeps the test repeatable.
  3. A cursor is the right tool only when a statement genuinely cannot do the job. The @@FETCH_STATUS loop earlier in this lesson is a fair illustration of the mechanics, but a single set-based statement almost always outperforms a row-by-row cursor loop over the same data; reach for a cursor when each row needs a different action taken outside the database, not as a default way to process a table.
  4. A function's return type is not always what it looks like. DATEDIFF(day, HireDate, GETDATE()) returns an integer, not a date; a result that is later used as if it were still a date, without an explicit conversion, is a common source of implicit-conversion errors once a statement grows past its first version.

What's Ahead

In the next lesson, you will learn how to handle errors when they occur in your Transact-SQL code, using TRY...CATCH together with ERROR_NUMBER() and ERROR_MESSAGE(), the modern replacement for checking @@ERROR after every statement that this lesson's session functions touched on only briefly. Several of the patterns from this lesson carry forward directly: a TRY_CONVERT that returns NULL instead of erroring is a form of error avoidance worth contrasting with the structured error handling ahead, and @@ROWCOUNT, already shown here as a way to confirm an UPDATE did what was expected, is a common companion check inside a CATCH block as well.

SEMrush Software 4 SEMrush Banner 4