19 April 2014

User Defined Trim Function in SQL Server



SQL Server has RTRIM() function that truncates all trailing blanks:

SELECT RTRIM('Hello world ') as Result;



There is also LTRIM() function that truncates all leading blanks:

SELECT LTRIM(' Hello world') as Result;



There is no TRIM() function that truncates all trailing and all leading blanks.
You can do that by combining RTRIM() and LTRIM() function in one query:

SELECT LTRIM(RTRIM(' Hello world ')) AS Result;



Or you can create a User Defined Function (UDF) that truncates all trailing and all leading blanks:

CREATE FUNCTION dbo.ufnTRIM(@string NVARCHAR(4000))
RETURNS NVARCHAR(4000)
BEGIN
RETURN LTRIM(RTRIM(@string))
END
GO

To run the new function:

SELECT dbo.ufnTRIM(' Hello world ') AS Result;

No comments:

Post a Comment