Introduction: In
this article i am going to explain how to remove all spaces that may be present
in the beginning(leading spaces) or at the last(trailing spaces) or in between(middle)
of the string.
In previous articles i explained Sql statement equivalent to ternary/conditional operator
and Using merge in sql to insert, update and delete in single statement and Using CTE to get all dates between two specified dates and Using CASE statement inside in clause (alternative) and Auto generate autoincremented alphanumeric sequential code in sql
Implementation: Let's take an example:
DECLARE
@String AS VARCHAR(100)=' Co m pu ter '
To remove spaces
from above string we need to use sql server’s inbuilt REPLACE function as:
SELECT REPLACE(@String, ' ', '')
Result will be “Computer”
i.e. with no spaces.
Now let's see how
to use this with the data stored in table column.
Let's create a
table with a column having dummy data with multiple spaces present at the
beginning, at the last or in between.
CREATE TABLE #tbData
(
Data
VARCHAR(100)
)
GO
INSERT INTO #tbData VALUES (' Computer')
INSERT INTO #tbData VALUES ('Computer ')
INSERT INTO #tbData VALUES (' Computer')
INSERT INTO #tbData VALUES ('Comp uter')
INSERT INTO #tbData VALUES ('Co mpu ter')
Check table data
GO
SELECT * FROM #tbData
Table data will
look like:
Data
|
Computer
|
Computer
|
Computer
|
Comp uter
|
Co mpu
ter
|
Now Let's write
the update query to remove spaces from the data.
UPDATE
#tbData SET Data =
REPLACE(Data, ' ', '');
Now check table data.
SELECT * FROM #tbData
Data
|
Computer
|
Computer
|
Computer
|
Computer
|
Computer
|
Note: All the
spaces are removed from the data.
Now drop temporary
table
drop table #tbData
Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..