Tags

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


SQL Server | Multiple ways to convert an Integer value to String

This question has been asked to one of my collegue in SQL SERVER interview. I know this is not a new way but have we explored any other option apart from cast and convert for this. Well, there are multiple ways to convert an integer value to a string value. Some of them are-

  • Method 1 | Using CAST function
  • Method 2 | Using Convert function
  • Method 3 | Using STR function
  • Method 4 | Using Implicit Conversion

Examples below-

--

/*
Method 1 | Using CAST function
It is one of the old methods to convert data from one datatype to another
*/
DECLARE @Int AS INT = 25
SELECT CAST (@Int AS VARCHAR(2)) String
GO

/*
Method 2 | Using Convert function
It is one of the old methods to convert data from one datatype 
to another
*/
DECLARE @Int AS INT = 25
SELECT CONVERT(VARCHAR(2),@Int) String
GO

/*
Method 3 | Using STR function
It is one of the lesser known fact. Str function returns character 
data converted from numeric data
*/
DECLARE @Int AS INT = 25
SELECT STR(25,2,1) String
GO

/*
Method 4 | Using Implicit conversion
Here we are taking a Varchar Variable and assigning the int varible 
to varchar variable
*/
DECLARE @Int AS INT = 25
DECLARE @Str AS VARCHAR(2) = ''
SET @Str = @Int
SELECT @Str String

--

Keep learning. If you have any other method in my please comment.

We all need to learn.

Pawan Kumar

http://MSBISkills.com

Advertisements