In this article I provide a quick overview of how to use the right and left functions in SQL Server. In this article you will see some examples related to the left and right functions. So let's have a look at a practical example of how to use the right and left functions in SQL Server. The examples are developed in SQL Server 2012 using the SQL Server Management Studio.
The following are the queries to add the first and after number in a string.
Using the SQL Left Function
The Left string function takes two arguments. The first argument is a string value and the second argument is an integer value specifying the length. It returns the first characters of the specified length starting from the left side of the string entered as the first argument.
Syntax
The syntax of the LEFT() function is as follows:
LEFT(String, NumberOfCharacters) RETURNS varchar;
Example1
Declare @Name varchar(20)-- Declare a char Variable
Set @Name='Rohatash'
selectLeft(@Name,3)
Output
The example below defines Number before the String using the left function.
Example2
In this example we take a string and a number. Using the left function a number will be added to the left of the string.
Declare @Name varchar(20)-- Declare a char Variable
Set @Name='Rohatash' -- Name
Declare @Number int -- Declare a int Variable
set @Number=123 -- Number to add in String
selectleft(@Number,3)+ @Name -- Using left Function
Output
Using the SQL Right Function
The Right string function takes two arguments. The first argument is a string value and the second argument is an integer value specifying the length. It returns the last characters of the specified length starting from the right side of the string entered as the first argument.
Syntax
The syntax of RIGHT() function is as follows :
RIGHT(String, NumberOfCharacters) RETURNS varchar
Example1
Declare @Name varchar(20)-- Declare a char Variable
Set @Name='Rohatash'
selectRight(@Name,3)
Output
The example below defines Number before the String using the left function.
Example2
In this example we take a string and number. Using the left function the number will be added to the left of the string.
Declare @Name varchar(20)-- Declare a char Variable
Set @Name='Rohatash' -- Name
Declare @Number int -- Declare a int Variable
set @Number=123 -- Number to add in String
select @Name + Right(@Number,3) -- Using right Function
Output