How to Convert Int to Varchar in SQL Server

Do you want to use the convert function on the SQL Server? Follow this tutorial to see how to use the convert function to change from integer into varchar in SQL Server.

Converting integers into variable characters in SQL Server is a simple operation. SQL Server provides different methods to transform functions. In this tutorial, I will explain all the possible ways to do this. Let’s get started.

How to Convert int to Varchar in SQL Server

Method -1 Using the CAST Function

We can use the CAST standard SQL function to convert from one data type to another. To convert an integer into a varchar data type in SQL Server, follow the syntax below.


SELECT CAST(Hospitalid AS VARCHAR(10)) AS Hospitalid_varchar
FROM  HospitalInfo ;

Below, you can see the output.

Convert int into varchar SQL

Using this CAST method, we can convert int into a varchar data type in the SQL Server.

Method -2 Using Convert Function

Although it can also be used for basic type conversions, the SQL Server-specific CONVERT function provides more flexibility with style parameters for date and time conversions. Below is the syntax

SELECT CONVERT(VARCHAR(length), your_int_column) AS your_varchar_column
FROM your_table;

Here, for my table, the syntax is given below,

  • Varchar(20)- This is the targetted data type we want to convert.
  • Hospitalid – Column where I should convert.
  • AS Varchar – Resulted data type.
SELECT CONVERT(VARCHAR(20), Hospitalid) AS varchar
FROM HospitalInfo; 
SQL Int to string

Note

  • While specifying the length of the varchar, ensure the length is capable enough to hold the integer values. By default, the length will be taken as 30 if you do not specify the length, which is enough for most of the time, but sometimes it may cause a shortened.
  • If your integer column contains null values, these functions will return null for the particular rows.

Conclusion

I hope this tutorial helps you convert int into varchar in SQL Server. Use this simple syntax to convert one data type to another.

You may like the following sql server tutorials:

Top 200 SQL Server Interview Questions and Answers

Free PDF On Top 200 SQL Server Interview Questions And Answers

Download A 40 pages PDF And Learn Now.