Trimming empty string or spaces in SQL - sql

What happens when you try and trim an empty string or a bunch of spaces in SQL Server? Does it become null or ''?

trimming will only leave you with a blank space.
ltrim(rtrim(' '))
but
nullif(ltrim(rtrim(' ')),'') will give you null

Here's an easy way to test string manipulations, manually throw some strings together and find out:
;with cte as (SELECT ' 0 ' AS col
UNION SELECT ' ' AS col
)
SELECT LTRIM(RTRIM(col)) as col
FROM cte
Which returns a zero and a blank string. To get a NULL you'd have to use NULLIF()

I run this command while updating all row.
Revise your need.
For example:
UPDATE TableName SET ColumnName = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(ColumnName, CHAR(10), CHAR(32)), CHAR(13), CHAR(32)), CHAR(160), CHAR(32)),CHAR(9),CHAR(32))))

Related

In SQL Server, how can I search for column with 1 or 2 whitespace characters?

So I need to filter column which contains either one, two or three whitespace character.
CREATE TABLE a
(
[col] [char](3) NULL,
)
and some inserts like
INSERT INTO a VALUES (' ',' ', ' ')
How do I get only the row with one white space?
Simply writing
SELECT *
FROM a
WHERE column = ' '
returns all rows irrespective of one or more whitespace character.
Is there a way to escape the space? Or search for specific number of whitespaces in column? Regex?
Use like clause - eg where column like '%[ ]%'
the brackets are important, like clauses provide a very limited version of regex. If its not enough, you can add a regex function written in C# to the DB and use that to check each row, but it won't be indexed and thus will be very slow.
The other alternative, if you need speed, is to look into full text search indexes.
Here is one approach you can take:
DECLARE #data table ( txt varchar(50), val varchar(50) );
INSERT INTO #data VALUES ( 'One Space', ' ' ), ( 'Two Spaces', ' ' ), ( 'Three Spaces', ' ' );
;WITH cte AS (
SELECT
txt,
DATALENGTH ( val ) - ( DATALENGTH ( REPLACE ( val, ' ', '' ) ) ) AS CharCount
FROM #data
)
SELECT * FROM cte WHERE CharCount = 1;
RETURNS
+-----------+-----------+
| txt | CharCount |
+-----------+-----------+
| One Space | 1 |
+-----------+-----------+
You need to use DATALENGTH as LEN ignores trailing blank spaces, but this is a method I have used before.
NOTE:
This example assumes the use of a varchar column.
Trailing spaces are often ignored in string comparisons in SQL Server. They are treated as significant on the LHS of the LIKE though.
To search for values that are exactly one space you can use
select *
from a
where ' ' LIKE col AND col = ' '
/*The second predicate is required in case col contains % or _ and for index seek*/
Note with your example table all the values will be padded out to three characters with trailing spaces anyway though. You would need a variable length datatype (varchar/nvarchar) to avoid this.
The advantage this has over checking value + DATALENGTH is that it is agnostic to how many bytes per character the string is using (dependant on datatype and collation)
DB Fiddle
How to get only rows with one space?
SELECT *
FROM a
WHERE col LIKE SPACE(1) AND col NOT LIKE SPACE(2)
;
Though this will only work for variable length datatypes.
Thanks guys for answering.
So I converted the char(3) column to varchar(3).
This seemed to work for me. It seems sql server has ansi padding that puts three while space in char(3) column for any empty or single space input. So any search or len or replace will take the padded value.

Removing trailing spaces and whitespaces from SQL Server column

I have a column in my SQL Server database and it has white spaces from left and right site of the record. Basically it's a nvarchar(250) column.
I have tried removing white spaces completely like this:
UPDATE MyTable
SET whitespacecolumn = LTRIM(RTRIM(whitespacecolumn))
But this didn't work out at all, the whitespace is still there. What am I doing wrong here?
Check the below;
Find any special characters like char(10), char(13) etc in the field value.
Check the status of ANSI_PADDING ON. Refer this MSDN article.
I think replace is the way as you are looking to update
UPDATE MyTable SET whitespacecolumn = Replace(whitespacecolumn, ' ', '')
you can try doing select first and then prefer to update
SELECT *, Replace(whitespacecolumn, ' ', '') from MyTable
LTRIM, RTRIM will remove spaces in front and rear of column. In 2016 you can use TRIM function as below to trim special characters as well:
SELECT TRIM( '.,! ' FROM '# test .') AS Result;
Output:
# test

How could I remove unnecessary characters in SQL

I need a query that could remove unnecessary characters (a not-so-needed trailing comma as an example) from the string stored in my database table.
So that
EMAIL_ADD
abc#gmail.com,
abc#yahoo.com,def#example.org,
abs-def#ac.uk,
would update it into something like this:
EMAIL_ADD
abc#gmail.com
abc#yahoo.com,def#example.org
abs-def#ac.uk
Using TRIM() function with TRAILING option removes a specific unwanted character from end of string , in your case being a comma present at end.
UPDATE tableName
SET EMAIL_ADD = TRIM(TRAILING ',' FROM EMAIL_ADD)
See documentation here TRIM()
If you have a specific list of characters to filter out at the start and end use trim functions:
select ltrim(ltrim(rtrim(rtrim(email_add, ','), ' '), ','), ' ')
from tableX
Here I nested ltrim and rtrim to remove leading and trailing , and .
Or using trim:
select trim(trim(both ',' from email_add))
from tableX
if you only whant to remove the last character of a string you can use
update mytable set my_column = substr(my_column ,0,len(trim(my_column)-1) where mycolumn like '%,'
It is an untested example.

What is the most efficient way to RTRIM a STRING without using RTRIM in SQL Server 2005?

In a single-select-statement, I have the need to RTRIM a string in a SQL Server 2005 environment.
What is, in your opinion, the most efficient technique to achieve this?
Examples:
'ALPHA ' ==> 'ALPHA' (the blanks at the end are removed)
' BETA ' ==> ' BETA' (the blank in first position remains, the two blanks at the end are removed)
' GAMMA' ==> ' GAMMA' (the blank in first position remains)
Thank you in advance for your kind help.
EDIT: I am not authorized to use RTRIM!!
Try this
Declare #str Varchar(50) = ' GAMMA '
;With Cte As
(
Select Data = Substring(#str,Number,1)
From master.dbo.spt_values
where Number Between 1 And Len(#str) And Type='P'
)
Select Data = Replace(Bar,' ',' ')
From (Select Cast(Data As Varchar(Max)) From Cte For Xml Path(''))Foo(Bar)
Result
Data
GAMMA
One way as LEN(CHAR_FIELD_OR_VAR) ignores trailing spaces;
left(fld, len(fld))
or
select left(fld, (len(fld + '.')-1)-patindex('%[^ ]%', reverse(fld))+1)
Select rtrim(ltrim(col)) from....
That will trim both sides of the column
I think your answer is in the title:
SELECT Columm1
, RTRIM(Column1) as Column1Trimmed
FROM Table1
RTRIM is the most efficient method of Right TRIMming.
Without RTRIM:
select '* *'
, REPLACE('* *',' ','')

How can I remove leading and trailing quotes in SQL Server?

I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.
For example:
"this is a test message"
should become
this is a test message
I know of the LTRIM and RTRIM functions but these workl only for spaces. Any suggestions on which functions I can use to achieve this.
I have just tested this code in MS SQL 2008 and validated it.
Remove left-most quote:
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
WHERE LEFT(FieldName, 1) = '"'
Remove right-most quote: (Revised to avoid error from implicit type conversion to int)
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
WHERE RIGHT(FieldName, 1) = '"'
I thought this is a simpler script if you want to remove all quotes
UPDATE Table_Name
SET col_name = REPLACE(col_name, '"', '')
You can simply use the "Replace" function in SQL Server.
like this ::
select REPLACE('this is a test message','"','')
note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.
Very simple and easy to execute !
My solution is to use the difference in the the column values length compared the same column length but with the double quotes replaced with spaces and trimmed in order to calculate the start and length values as parameters in a SUBSTRING function.
The advantage of doing it this way is that you can remove any leading or trailing character even if it occurs multiple times whilst leaving any characters that are contained within the text.
Here is my answer with some test data:
SELECT
x AS before
,SUBSTRING(x
,LEN(x) - (LEN(LTRIM(REPLACE(x, '"', ' ')) + '|') - 1) + 1 --start_pos
,LEN(LTRIM(REPLACE(x, '"', ' '))) --length
) AS after
FROM
(
SELECT 'test' AS x UNION ALL
SELECT '"' AS x UNION ALL
SELECT '"test' AS x UNION ALL
SELECT 'test"' AS x UNION ALL
SELECT '"test"' AS x UNION ALL
SELECT '""test' AS x UNION ALL
SELECT 'test""' AS x UNION ALL
SELECT '""test""' AS x UNION ALL
SELECT '"te"st"' AS x UNION ALL
SELECT 'te"st' AS x
) a
Which produces the following results:
before after
-----------------
test test
"
"test test
test" test
"test" test
""test test
test"" test
""test"" test
"te"st" te"st
te"st te"st
One thing to note that when getting the length I only need to use LTRIM and not LTRIM and RTRIM combined, this is because the LEN function does not count trailing spaces.
I know this is an older question post, but my daughter came to me with the question, and referenced this page as having possible answers. Given that she's hunting an answer for this, it's a safe assumption others might still be as well.
All are great approaches, and as with everything there's about as many way to skin a cat as there are cats to skin.
If you're looking for a left trim and a right trim of a character or string, and your trailing character/string is uniform in length, here's my suggestion:
SELECT SUBSTRING(ColName,VAR, LEN(ColName)-VAR)
Or in this question...
SELECT SUBSTRING('"this is a test message"',2, LEN('"this is a test message"')-2)
With this, you simply adjust the SUBSTRING starting point (2), and LEN position (-2) to whatever value you need to remove from your string.
It's non-iterative and doesn't require explicit case testing and above all it's inline all of which make for a cleaner execution plan.
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
You can use following query which worked for me-
For updating-
UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...
For selecting-
SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName
you could replace the quotes with an empty string...
SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
LeadingAndTrailingRemoved = CASE
WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
ELSE MyTest
END
FROM MyTable
Some UDFs for re-usability.
Left Trimming by character (any number)
CREATE FUNCTION [dbo].[LTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Right Trimming by character (any number)
CREATE FUNCTION [dbo].[RTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).
To remove both quotes you could do this
SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
you can either assign or project the resulting value
You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test
CREATE FUNCTION dbo.TRIM(#String VARCHAR(MAX), #Char varchar(5))
RETURNS VARCHAR(MAX)
BEGIN
RETURN SUBSTRING(#String,PATINDEX('%[^' + #Char + ' ]%',#String)
,(DATALENGTH(#String)+2 - (PATINDEX('%[^' + #Char + ' ]%'
,REVERSE(#String)) + PATINDEX('%[^' + #Char + ' ]%',#String)
)))
END
GO
Select dbo.TRIM('"this is a test message"','"')
Reference : http://raresql.com/2013/05/20/sql-server-trim-how-to-remove-leading-and-trailing-charactersspaces-from-string/
I use this:
UPDATE DataImport
SET PRIO =
CASE WHEN LEN(PRIO) < 2
THEN
(CASE PRIO WHEN '""' THEN '' ELSE PRIO END)
ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"',
SUBSTRING(PRIO, 2, LEN(PRIO) - 2))
END
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName