Logo of Microsoft SQL Server

SQL Server - Cast and Convert

Usage of Cast and Convert with an example

With SQL Server, you can convert one type to another, for example an INT to VARCHAR using either the CAST or CONVERT function.

Here are both options in action:

Using CAST

1
SELECT CAST(123 AS VARCHAR(10)) AS ConvertedValue;

Using CONVERT

1
SELECT CONVERT(VARCHAR(10), 123) AS ConvertedValue;

Key points

Always specify the length for VARCHAR (e.g., VARCHAR(10)), otherwise SQL Server uses a default length of 30.

If you omit the length, it might cause truncation or unexpected results in some contexts.

Documentation

Reference: Microsoft Learn.

Follow me

Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.

Credits: Image from Microsoft Server

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy