Home > DeveloperSection > Blogs > Trim method in SQL Server

Trim method in SQL Server


Database Database 
Ratings:
0 Comment(s)
 1847  View(s)
Rate this:

Trim method in SQL Server

SQL server does not have Trim method, but for trimming blank spaces (leading and trailing) from string we have used LTRIM and RTRIM method in SQL Server. User can easily use LTRIM() and RTRIM() together and simulate TRIM() functionality. For example

Trim in Simple Query

SELECT RTRIM(LTRIM('      SQL Server Trim() Demo       ')) AS Trim_String;

It return ‘SQL Server Trim() Demo ’ string without white space.

Trim using function

CREATE FUNCTION dbo.TRIM(@string VARCHAR(MAX))

RETURNS VARCHAR(MAX)

BEGIN

RETURN LTRIM(RTRIM(@string))

END

SELECT dbo.TRIM('      SQL Server Demo       ') AS Trim_String;

Trim using function with table in 2008

-- Create Table

CREATE TABLE TrimDemo

(

ID TINYINT NOT NULL IDENTITY (1, 1),

StringCol VARCHAR(150) NOT NULL,

TrimmedCol AS LTRIM(RTRIM(StringCol))

) ON [PRIMARY]

GO

-- Insert data into table

INSERT INTO TrimDemo

([StringCol])

SELECT ' SQL Server'

UNION

SELECT 'SQL Server 2005    '

UNION

SELECT ' SQL Server 2008 '

UNION

SELECT 'SQL Server 2012'

GO

-- Select table

SELECT * FROM TrimDemo

GO

Note: If user inserts blank/white spaces between two strings then LTRIM and RTRIM not remove that, it’s removing only starting and ending blank/white spaces.


Don't want to miss updates? Please click the below button!

Follow MindStick