Let us first understand in detail about these operators.
LEN() Function :
This function is a pre defined function in SQL Server. This function is used to calculate the length of the expression passed as input to the function excluding the trailing spaces.
Syntax
Let us use this function to see how it works. We have passed an input expression having the character length of 14. Let us see what output we get by executing the following script.
- DECLARE @input varchar(20)
-
- SET @input ='DotnetSnippets'
-
- SELECTLEN(@input)asLength
We get the accurate output. Let us now add a trailing space to the input expression and see what the output is. Modify the script and execute.
- DECLARE @input varchar(20)
-
- SET @input ='DotnetSnippets '
-
- SELECTLEN(@input)asLength
We get the same output. So Len function only returns the exact character length and does not include the trailing spaces. Let us now have a look at DataLength function in SQL.
DataLength() Function :
This function returns the number of bytes used or occupied by the data. It includes the trailing spaces also. Let us see a practical demo for the same.
Syntax
- DATALENGTH(string_expression)
Let us use this function to see how it works. Execute the following script.
- DECLARE @input VARCHAR(20)
- DECLARE @INPUT1 VARCHAR(20)
- SET @input ='DotnetSnippets'
- SET @INPUT1 ='DotnetSnippets '
- SELECTDATALENGTH(@input)asLength
- SELECTDATALENGTH(@INPUT1)as Length1
Let us see the output of the preceding script.
We can we have two input strings. The first string has the expression without any trailing space. So it is equivalent to Len() function in this scenario. But when we add a trailing space to the input function it counts the space as well. So we get 15 as the count in case of DataLength() function.