How to find values with Leading or Trailing Spaces in SQL Server Table - SQL Server: Tips and Tricks - 2 (2017)

SQL Server: Tips and Tricks - 2 (2017)

How to find values with Leading or Trailing Spaces in SQL Server Table

Scenario:

You are working as SQL Server Developer / TSQL Developer with Mortgage Company. You are preparing script for data cleaning. You need to find all the records with leading and trailing spaces. Once you found them then you need to write update statement to remove leading and trailing spaces.

Solution:

Let's create our test temp table with some test data. I have included leading and trailing space in 4 values.

--Create Test Table

Create table #Temp( Name VARCHAR(100))

Go

Insert into #Temp

Select 'NoSpace' AS NAme

Union

Select ' SingleSpaceAtStart' AS Name

Union

Select ' TwoSpacesAtStart' AS Name

Union

Select 'SingleSpaceAfter ' AS Name

Union

Select 'TwoSpacesAfter ' as Name

Let's go ahead and run our Select Query to find Leading and Trailing spaces in our data.

Select * from #Temp

where name like '% ' --Will provide us values with Trailing space/s

or name like ' %' --Will provide us values with leading Space/s

https://1.bp.blogspot.com/-f4DDKaUKE3s/VuLfcji6a0I/AAAAAAAAG3Q/cJy_-vcqPHsdhS8B3ZCvHaPppoTLb3UDQ/s400/Capture.PNG

Our query returned only 4 records, as there is no leading or trailing space for first record.

Let's use the update statement to update the records and remove the leading and trailing spaces.

--Update the records and remove leading and trailing spaces

Update #Temp

Set Name=LTRIM(RTRIM(Name))

where name like '% '

or name like ' %'

Four records will be updated. If I will run select query again to check the leading or trailing spaces in column, I will get no records as the spaces are removed and records are updated.

Go ahead and run just to confirm

Select * from #Temp

where name like '% ' --Will provide us values with Trailing space/s

or name like ' %' --Will provide us values with leading Space/s

https://2.bp.blogspot.com/-e-S2IP1_7Gg/VuLgY0ScEnI/AAAAAAAAG3c/Rd2bSkM6Ma4lUa_Qy-yHGrYnpDRrbPjSA/s640/Capture.PNG