RTRIM does not remove spaces at the end? - sql-server

I have used the Query:
update Table
set Seg = RTRIM(Seg)
This still doesn't remove the extra spaces at the end? I really need to remove this as I am doing vlookups in Excel and it is causing problems.
The datatype of Seg column is (nchar(10), null)
Any help is appreciated.

You can right-trim an NCHAR(X) column all you want, values will always be the same length. Namely: X. The value will always be padded with spaces, so RTRIM is basically a no-op on a fixed width character column.
Also note that in string comparisons, trailing spaces are ignored.

To trim spaces from the end you should use
UPDATE
TableName
SET
ColumnName = RTRIM(ColumnName)
if you want to trim all spaces then use this
UPDATE
TableName
SET
ColumnName = LTRIM(RTRIM(ColumnName))

Related

SQL Server : RTRIM not working to remove empty spaces

One of the column values in my tables have empty space at the end of each string.
In my select query, I am trying to trim the empty space at the end of string but the value is not getting trimmed.
SELECT
EmpId, RTRIM(Designation) AS Designation, City
FROM
tblEmployee
This is not trimming the empty space, not just this even the LTRIM(RTRIM(Designation) AS Designation is not working.
I also tried
CONVERT(VARCHAR(56), LTRIM(RTRIM(Designation))) AS [Designation]
Nothing is trimming the empty space at the end of the string...
Any help appreciated
EDIT
Thanks to suggestions in the comments, I checked what the last value was in the column using ASCII(). It is 160 is a non-breaking space.
How can I remove this non-breaking space?
How can I remove this non-breaking space?
Just replace it with '' and use CHAR() function as
SELECT REPLACE(YourColumn, CHAR(160), '')
FROM YourTable;
Since the value can contain non-breaking spaces you need to replace those with regular spaces before doing the trim:
SELECT
EmpId, RTRIM(REPLACE(Designation,char(160),' ')) AS Designation, City
FROM
tblEmployee
I faced the similar problem, Use below script to remove the space in case trim function not work -
SELECT LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE([ColumnName], CHAR(10),
CHAR(32)),CHAR(13), CHAR(32)),CHAR(160), CHAR(32)),CHAR(9),CHAR(32))))
FROM [TableName]
For more info visit this page - http://www.ashishblog.com/trim-not-removing-spaces-in-sql/

FOR XML PATH always adds trailing space to value

Using the FOR XML PATH structure to create a list of values,
I find that (annoyingly) it always adds a trailing space to selected values.
This ruins my attempts at providing my own delimiters - the trailing space is added after the column and delimiters have been concatenated.
For example:
SELECT country + '-' FROM countryTable...
results in the following string:
china- france- england-
Has anyone else seen this, and is there a way to stop it?
I don't think TRIM() will work, as that would be applied before the extra space is inserted...
I'm using SQL Server 2016.
Thanks
Ok, thanks to John C and his sample query I found the culprit.
I had a AS [data()] clause after the column name/delimiter.
Removing that removed the trailing space.
I don't know how/why but it did...
I suspect the data inside the country column, What if each value in Country column is having leading space. For XML PATH does not add any space to the data
Try this
SELECT RTRIM(LTRIM(country)) + '-' FROM countryTable...
You may have leading/trailing spaces and/or CRLFs. Perhaps this will help
Declare #countryTable table (country varchar(100))
Insert Into #countryTable values
(' china'), -- leading space
(char(13)+'france'), -- leading char(13)
(char(10)+'england') -- leading char(10)
Select Value=Stuff((Select Distinct '-' + ltrim(rtrim(replace(replace(country,char(13),''),char(10),'')))
From #countryTable
Where 1=1
For XML Path ('')),1,1,'')
Returns
Value
china-england-france
FOR XML PATH ... AS [data()] add to this from MS Help
If the path specified as column name is data(), the value is treated as an atomic value in the generated XML. A space character is added to the XML if the next item in the serialization is also an atomic value. This is useful when you are creating list typed element and attribute values.
When you write here ... AS something. Then something is used as open/closing markup tag for each selected value.
Add 2. Is possible concate in select clausule more fileds from each row. For other types than string type, value must be converted into string type CAST AS

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

I'm in the process of trying to clear out leading and trailing spaces from an NVARCHAR(MAX) column that is filled with prices (using NVARCHAR due to data importing from multiple operating systems with odd characters).
At this point I have a t-sql command that can remove the leading/trailing spaces from static prices. However, when it comes to leveraging this same command to remove all prices, I'm stumped.
Here's the static script I used to remove a specific price:
UPDATE *tablename* set *columnname* = LTRIM(RTRIM(2.50)) WHERE cost = '2.50 ';
Here's what I've tried to remove all the trailing spaces:
UPDATE *tablename* set *columnname* LIKE LTRIM(RTRIM('[.]')) WHERE cost LIKE '[.] ';
I've also tried different varations of the % for random characters but at this point I'm spinning my wheels.
What I'm hoping to achieve is to run one simple command that takes off all the leading and trailing spaces in each cell of this column without modifying any of the actual column data.
To remove spaces from left/right, use LTRIM/RTRIM. What you had
UPDATE *tablename*
SET *columnname* = LTRIM(RTRIM(*columnname*));
would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been
UPDATE [tablename]
SET [columnname] = LTRIM(RTRIM([columnname]))
WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));
Note: 32 is the ascii code for the space character.
To remove spaces... please use LTRIM/RTRIM
LTRIM(String)
RTRIM(String)
The String parameter that is passed to the functions can be a column name, a variable, a literal string or the output of a user defined function or scalar query.
SELECT LTRIM(' spaces at start')
SELECT RTRIM(FirstName) FROM Customers
Read more: http://rockingshani.blogspot.com/p/sq.html#ixzz33SrLQ4Wi
LTrim function and RTrim function :
The LTrim function to remove leading spaces and the RTrim
function to remove trailing spaces from a string variable.
It uses the Trim function to remove both types of spaces.
select LTRIM(RTRIM(' SQL Server '))
output:
SQL Server
I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim directly as below:
UPDATE *tablename*
SET *columnname* = trim(*columnname*);
SELECT RTRIM(' Author ') AS Name;
Output will be without any trailing spaces.
Name
——————
‘ Author’
The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable.
It uses the Trim function to remove both types of spaces and means before and after spaces of string.
SELECT LTRIM(RTRIM(REVERSE(' NEXT LEVEL EMPLOYEE ')))

WHERE clause on VARCHAR column seems to operate as a LIKE

I've stumbled across a situation I've never seen before. I hope that someone can explain the following.
I've ran the following query, hoping to get only the results of columns whoes value is exactly equal to 1101
select '--' + MyColumn + '--' SeeSpaces, Len(MyColumn) as LengthOfColumn
from MyTable
where MyColumn = '1101'
However, I also see values where 1101 is followed by (what I believe are) spaces.
So SeeSpaces returns
--1101 --
And LengthOfColumn returns 4
MyColumn is a VARCHAR(8), NOT NULL column. Its values (including the spaces) are inserted through a separate workflow.
Why does this select not return only the exact results?
Thanks in advance
The reason is to do with the way that SQL server compares strings with trailing spaces, it follows the ANSI standard and so the strings '1101' and '1101 ' are equivalent.
See the following for more details:
INF: How SQL Server Compares Strings with Trailing Spaces
I think you have to use LTRIM() and RTRIM() function while comparing like :
LTRIM(RTRIM(MYCOLUMN))='1101'
Also LEN function does not count spaces, it only count characters in string. Please refere : http://msdn.microsoft.com/en-us/library/ms190329%28SQL.90%29.aspx

How can I make SQL Server return FALSE for comparing varchars with and without trailing spaces?

If I deliberately store trailing spaces in a VARCHAR column, how can I force SQL Server to see the data as mismatch?
SELECT 'foo' WHERE 'bar' = 'bar '
I have tried:
SELECT 'foo' WHERE LEN('bar') = LEN('bar ')
One method I've seen floated is to append a specific character to the end of every string then strip it back out for my presentation... but this seems pretty silly.
Is there a method I've overlooked?
I've noticed that it does not apply to leading spaces so perhaps I run a function which inverts the character order before the compare.... problem is that this makes the query unSARGable....
From the docs on LEN (Transact-SQL):
Returns the number of characters of the specified string expression, excluding trailing blanks. To return the number of bytes used to represent an expression, use the DATALENGTH function
Also, from the support page on How SQL Server Compares Strings with Trailing Spaces:
SQL Server follows the ANSI/ISO SQL-92 specification on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them.
Update: I deleted my code using LIKE (which does not pad spaces during comparison) and DATALENGTH() since they are not foolproof for comparing strings
This has also been asked in a lot of other places as well for other solutions:
SQL Server 2008 Empty String vs. Space
Is it good practice to trim whitespace (leading and trailing)
Why would SqlServer select statement select rows which match and rows which match and have trailing spaces
you could try somethign like this:
declare #a varchar(10), #b varchar(10)
set #a='foo'
set #b='foo '
select #a, #b, DATALENGTH(#a), DATALENGTH(#b)
Sometimes the dumbest solution is the best:
SELECT 'foo' WHERE 'bar' + 'x' = 'bar ' + 'x'
So basically append any character to both strings before making the comparison.
After some search the simplest solution i found was in Anthony Bloesch
WebLog.
Just add some text (a char is enough) to the end of the data (append)
SELECT 'foo' WHERE 'bar' + 'BOGUS_TXT' = 'bar ' + 'BOGUS_TXT'
Also works for 'WHERE IN'
SELECT <columnA>
FROM <tableA>
WHERE <columnA> + 'BOGUS_TXT' in ( SELECT <columnB> + 'BOGUS_TXT' FROM <tableB> )
The approach I’m planning to use is to use a normal comparison which should be index-keyable (“sargable”) supplemented by a DATALENGTH (because LEN ignores the whitespace). It would look like this:
DECLARE #testValue VARCHAR(MAX) = 'x';
SELECT t.Id, t.Value
FROM dbo.MyTable t
WHERE t.Value = #testValue AND DATALENGTH(t.Value) = DATALENGTH(#testValue)
It is up to the query optimizer to decide the order of filters, but it should choose to use an index for the data lookup if that makes sense for the table being tested and then further filter down the remaining result by length with the more expensive scalar operations. However, as another answer stated, it would be better to avoid these scalar operations altogether by using an indexed calculated column. The method presented here might make sense if you have no control over the schema , or if you want to avoid creating the calculated columns, or if creating and maintaining the calculated columns is considered more costly than the worse query performance.
I've only really got two suggestions. One would be to revisit the design that requires you to store trailing spaces - they're always a pain to deal with in SQL.
The second (given your SARG-able comments) would be to add acomputed column to the table that stores the length, and add this column to appropriate indexes. That way, at least, the length comparison should be SARG-able.

Resources