Sunday, August 11, 2013

TRIM()

TRIM() ?

One of my friends who love to work at ORACLE, ask me that the Function TRIM() is supported by any version of SQL Server.
Like ORACLE the SQL server does not have function which can trim leading or trailing spaces of any string at the same time.  
We can use LTRIM() and RTRIM() function together to get the output like TRIM() function in SQL Server.

Example
SELECT LTRIM(RTRIM(' Hello ')) AsResult


Result
------
Hello

However we can create an UDF function named TRIM to get the same functionality like ORCALE TRIM() Function.
IF OBJECT_ID (N'dbo.TRIM ') IS NOT NULL
   DROP FUNCTION dbo.TRIM
GO

CREATE FUNCTION dbo.TRIM
(
      @p_String VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
      BEGIN
            RETURN LTRIM(RTRIM(@p_String))
      END
GO

-- Testing
SELECT dbo.TRIM(' Hello ') As Result

Hope you like it.