Working with data types is a fundamental skill for any database developer or administrator. In SQL Server, the ability to transform non-character data—such as integers, decimals, dates, or binary values—into character strings is essential for reporting, concatenation, dynamic SQL construction, and data export operations. Mastering the functions available for this transformation ensures your queries are not only functional but also performant and resilient to formatting errors.
Understanding the Core Functions: CAST vs. CONVERT
SQL Server provides two primary functions for data type conversion: CAST and CONVERT. While both achieve the goal of turning a value into a VARCHAR, NVARCHAR, CHAR, or NCHAR string, they differ significantly in syntax, flexibility, and adherence to standards.
The ANSI Standard: CAST
CAST is the ANSI SQL standard function. Because it is part of the SQL specification, code written using CAST is more portable across different database platforms like PostgreSQL, MySQL, or Oracle. The syntax is straightforward:
CAST ( expression AS data_type [ ( length ) ] )
Example:
SELECT CAST(12345 AS VARCHAR(10)) AS StringValue;
-- Result: '12345'
When to use CAST:
- You are writing cross-platform SQL scripts.
- You do not need specific formatting for dates or numbers.
- You prefer a cleaner, more readable syntax for simple conversions.
The SQL Server Specialist: CONVERT
CONVERT is specific to SQL Server (and Sybase). Its superpower lies in the optional style parameter, which allows precise control over the output format, particularly for date/time and money data types. The syntax is:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
Example (Date Formatting):
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS ISO_Date; -- '2023-10-25'
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS US_Date; -- '10/25/2023'
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS UK_Date; -- '25/10/2023'
When to use CONVERT:
- You need specific date/time formatting (the style codes are invaluable here).
- You are formatting monetary values with specific comma/decimal placements.
- You are working exclusively within the SQL Server ecosystem.
The Modern Alternative: TRY_CAST and TRY_CONVERT
Introduced in SQL Server 2012, TRY_CAST and TRY_CONVERT are critical for writing solid, error-proof code. Standard CAST and CONVERT will throw a runtime error and halt the batch if the conversion fails (e.g., trying to convert the string 'abc' to an integer, or an overflow error) Worth knowing..
The TRY_ versions return NULL instead of raising an error if the conversion fails. This allows the query to continue processing other rows Small thing, real impact..
Syntax:
TRY_CAST ( expression AS data_type [ ( length ) ] )
TRY_CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
Practical Scenario:
Imagine a staging table RawData with a DirtyValue column (VARCHAR) that should contain integers but has some garbage entries.
-- This FAILS the whole batch if one row has 'N/A'
SELECT CAST(DirtyValue AS INT) FROM RawData;
-- This SUCCEEDS, returning NULL for 'N/A' and the integer for valid rows
SELECT TRY_CAST(DirtyValue AS INT) AS CleanInt FROM RawData;
Best Practice: Always default to TRY_CAST or TRY_CONVERT when dealing with untrusted data sources, ETL processes, or user-generated input. Use the standard versions only when you are certain the data is clean or when you want the query to fail explicitly as a data quality check.
Deep Dive: Converting Specific Data Types to String
The complexity of conversion usually depends on the source data type. Here is how to handle the most common scenarios Small thing, real impact..
1. Numeric Types (INT, BIGINT, DECIMAL, FLOAT, MONEY)
Converting numbers to strings is generally implicit-safe, but explicit conversion is required for concatenation But it adds up..
Simple Conversion:
DECLARE @Price DECIMAL(10, 2) = 1234.56;
SELECT CAST(@Price AS VARCHAR(20)); -- '1234.56'
Formatting Numbers (The "Thousands Separator" Problem):
SQL Server does not have a built-in FORMAT_NUMBER function like some other languages. To get 1,234.56 from 1234.56, you have two main options:
-
Option A:
CONVERTwith Style 1 (Money only) This works only forMONEYorSMALLMONEYtypes.SELECT CONVERT(VARCHAR(20), CAST(1234567.89 AS MONEY), 1); -- Result: '1,234,567.89' -
Option B:
FORMATFunction (SQL Server 2012+) This uses .NET formatting strings. It is extremely flexible but slower thanCONVERTdue to CLR overhead. Avoid in high-volumeWHEREclauses or massive result sets.SELECT FORMAT(1234567.89, 'N', 'en-US'); -- '1,234,567.89' SELECT FORMAT(1234567.89, '#,##0.00'); -- Custom pattern -
Option C: String Manipulation (High Performance) For massive datasets where
FORMATis too slow, developers often write custom logic usingREVERSE,STUFF, andSUBSTRINGto inject commas, though this adds code complexity.
2. Date and Time Types (DATETIME, DATE, DATETIME2, SMALLDATETIME)
This is where CONVERT shines. The Style parameter dictates the exact output pattern. There are dozens of styles; here are the most critical ones to memorize or bookmark Which is the point..
| Style Code | Standard | Output Example | Description |
|---|---|---|---|
| 101 | US | 10/25/2023 |
mm/dd/yyyy |
| 103 | British/French | 25/10/2023 |
dd/mm/yyyy |
| 112 | ISO | 20231025 |
yyyymmdd (Safe for sorting/filenames) |
| 120 | ODBC Canonical | 2023-10-25 14:30:00 |
yyyy-mm-dd hh:mi:ss (24h) |
| 121 | ODBC Canonical (ms) | 2023-10-25 14:30:00.000 |
Honestly, this part trips people up more than it should Most people skip this — try not to..
121 – ODBC Canonical (ms) 2023-10-25 14:30:00.000
The 121 style returns a full datetime with three‑digit milliseconds, which is handy when you need sub‑second precision in logs or audit trails.
122 – ODBC Canonical (US) 2023-10-25 14:30:00.000
If you prefer the US‑style date first, style 122 mirrors 121 but uses the American month‑day order.
126 – ISO 8601 2023-10-25T14:30:00
Style 126 drops the space between date and time and omits the milliseconds. It is the de‑facto standard for interchange formats such as JSON, XML, and CSV files that must be sorted lexicographically Which is the point..
127 – ISO 8601 with timezone 2023-10-25T14:30:00.000+00:00
For global applications, style 127 adds an offset (or Z for UTC). This eliminates ambiguity when data originates from multiple time zones And it works..
23 – Short date 25‑Oct‑2023
When a compact, locale‑aware representation is required (e.g., UI tooltips), style 23 yields a three‑letter month abbreviation in the current language.
25 – Un‑ambiguous date 2023‑10‑25
Style 25 is the ISO‑like date without time, ideal for primary keys or file names where sorting order must match chronological order.
26 – Time 14:30:00.000
If only the time portion is needed, style 26 returns a 24‑hour clock with milliseconds, useful for scheduling or duration calculations.
27 – Time with timezone 14:30:00.000+00:00
Style 27 extends 26 to include the zone offset, mirroring 127’s behavior for time‑only scenarios Simple, but easy to overlook..
28 – Date with time 2023‑10‑25 14:30:00.000
Style 28 combines the date and time components while preserving the three‑digit millisecond fraction, offering a balance between readability and precision.
Converting Dates to Strings in Practice
1. When to Choose CONVERT Over FORMAT
- Performance‑critical code –
CONVERT(orCAST) is a native T‑SQL operation; it avoids the CLR overhead ofFORMAT. In a stored procedure that returns millions of rows, the difference can be orders of magnitude. - Simple, fixed patterns – If you only need a handful of formats (e.g.,
YYYYMMDDfor filenames), style 112 or 25 is faster than anyFORMATcall. - Explicit failure – Using
TRY_CAST/TRY_CONVERTlets the query continue when a row contains an invalid
Continuing the “Converting Dates to Strings in Practice” Section
2. Why Use TRY_CAST / TRY_CONVERT?
In many reporting pipelines the source column may contain values ranging from valid calendar dates to placeholders (NULL, empty strings, or malformed entries). Plus, a naïve CAST(... AS VARCHAR(...)) would throw an error on the offending rows and halt the entire result set It's one of those things that adds up..
- **Row‑level