CAST Operator

Explicitly casts the given value to another type.

 

Syntax

 

CAST(value AS type)

 

The CAST operator has these parts:

 

Part

Description

value

The value of interest.

type

The target type.

Remarks

 

Use the CAST operator to explicitly cast a value to another type. For the list of supported types, see the Data Types topic.

 

The CAST operator works like CDbl, CInt, CStr and other similar functions but allows using the explicit name of the type.

 

Examples

 

This example uses the CAST operator to select the rounded price of each product:

 

SELECT [Product Name], CAST([Unit Price] AS INT) AS [Rounded Price] FROM [Products];

 

This example uses the CAST operator and the IS NULL operator to select all employees with numeric postal codes:

 

SELECT * FROM [Employees] WHERE CAST([Postal Code] AS INT) IS NOT NULL;

 

We might use the above example in situations where we would like to differentiate between employees with numeric postal codes (as in the case of ZIP codes in the US, which contain only numbers) and those with postal codes that use both letters and numbers (as in the case of Canadian or UK postal codes).