Monday, April 26, 2010

Find the LENGTH of a string without using LEN Function in Sql Server

This user-defined function will give you the length of the string.

CREATE FUNCTION dbo.GetLength(@InputString VARCHAR(8000))
RETURNS INT
AS
/* -- Comments --
Created By: Alwyn Duraisingh.M
Created on: April 26 2010 10:10 PM
Purpose: To find the length of the string without using LEN() function
*/
BEGIN
DECLARE @Count INT, @Index INT, @Flag INT
SELECT @InputString = REPLACE(@InputString, ' ','*'),
@Count = 0, @Index = 1, @Flag = 1
--Looping through each and every character and count one by one
WHILE ( @Flag = 1 )
BEGIN
IF ((SELECT SUBSTRING(@InputString,@Index,1)) <> '')
BEGIN
SET @Count = @Count + 1
END
ELSE
BEGIN
SET @Flag = 0
END
SET @Index = @Index + 1
END
RETURN @Count
END



You can call the function like

SELECT dbo.GetLength('God is only one') AS LENGTH

RESULT:
*******
LENGTH
*******
15

No comments:

Post a Comment