Cómo eliminar caracteres de espacio en blanco de una cadena en SQL Server


Estoy tratando de eliminar los espacios en blanco de una cadena en SQL pero LTRIM y RTRIM las funciones no parecen funcionar?

Columna:

[ProductAlternateKey] [nvarchar](25) COLLATE Latin1_General_CS_AS NULL

Consulta:

select REPLACE(ProductAlternateKey, ' ', '@'),
       LEN(ProductAlternateKey),
       LTRIM(RTRIM(ProductAlternateKey))      AS LRTrim,
       LEN(LTRIM(RTRIM(ProductAlternateKey))) AS LRLen,
       ASCII(RIGHT(ProductAlternateKey, 1))   AS ASCIIR,
       ASCII(LEFT(ProductAlternateKey, 1))    AS ASCIIL,
       ProductAlternateKey
from DimProducts
where ProductAlternateKey  like '46783815%'

Resultado:

|  COLUMN_0 | COLUMN_1 | LRTrim | LRLen | ASCIIR | ASCIIL | PRODUCTALTERNATEKEY |
---------------------------------------------------------------------------------
|  46783815 |        8 | 46783815|     8|   53   |   52   |            46783815 |
| 46783815  |        10|46783815  |   10|   10   |   52   |           46783815  |

¿Pueden ser otros símbolos si LTRIM y RTRIM no funcionan, como "Enter"?

Author: DMK, 2013-01-08

6 answers

Usando ASCII(RIGHT(ProductAlternateKey, 1)) puede ver que el carácter más a la derecha en la fila 2 es un Feed de línea o el Carácter Ascii 10.

Esto no se puede eliminar usando el estándar LTrim RTrim funciones.

Sin embargo, podría usar (REPLACE(ProductAlternateKey, CHAR(10), '')

Es posible que también desee tener en cuenta los retornos de carro y las pestañas. Estos tres (feeds de línea, retornos de carro y pestañas) son los culpables habituales y se pueden eliminar con lo siguiente:

LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))

Si encuentra más caracteres de "espacio en blanco" que no se puede eliminar con lo anterior, luego intente uno o todos los siguientes:

--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');

Esta lista de posibles caracteres de espacio en blanco podría usarse para crear una función como :

Create Function [dbo].[CleanAndTrimString] 
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
    --NULL
    Set @MyString = Replace(@MyString,CHAR(0),'');
    --Horizontal Tab
    Set @MyString = Replace(@MyString,CHAR(9),'');
    --Line Feed
    Set @MyString = Replace(@MyString,CHAR(10),'');
    --Vertical Tab
    Set @MyString = Replace(@MyString,CHAR(11),'');
    --Form Feed
    Set @MyString = Replace(@MyString,CHAR(12),'');
    --Carriage Return
    Set @MyString = Replace(@MyString,CHAR(13),'');
    --Column Break
    Set @MyString = Replace(@MyString,CHAR(14),'');
    --Non-breaking space
    Set @MyString = Replace(@MyString,CHAR(160),'');

    Set @MyString = LTRIM(RTRIM(@MyString));
    Return @MyString
End
Go

Que luego podrías usar de la siguiente manera:

Select 
    dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts
 62
Author: DMK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-25 09:34:52

En ese caso, no es el espacio el que está en prefijo/sufijo.
La primera fila se ve bien. Haga lo siguiente para el contenido de la 2a fila.

ASCII(RIGHT(ProductAlternateKey, 1))

Y

ASCII(LEFT(ProductAlternateKey, 1))
 4
Author: shahkalpesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-08 09:00:13

Puede haber 2 espacios después del texto, por favor confirme. Puede utilizar LTRIM y RTRIM funciones también la derecha?

LTRIM(RTRIM(ProductAlternateKey))

Tal vez el espacio extra no es espacios ordinarios (ASCII 32, espacio blando)? Tal vez son "espacio duro", ASCII 160?

ltrim(rtrim(replace(ProductAlternateKey, char(160), char(32))))
 3
Author: TechDo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-08 09:37:46

¿Qué tal esto?

CASE WHEN ProductAlternateKey is NOT NULL THEN
CONVERT(NVARCHAR(25), LTRIM(RTRIM(ProductAlternateKey))) 
FROM DimProducts
where ProductAlternateKey  like '46783815%'
 0
Author: mr_eclair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-08 09:22:08

Parece el personaje invisible -

ALT+255

Prueba esto

select REPLACE(ProductAlternateKey, ' ', '@')
--type ALT+255 instead of space for the second expression in REPLACE 
from DimProducts
where ProductAlternateKey  like '46783815%'

Raj

Editar: Basado en los resultados ASCII (), intente ALT+10 - use el teclado numérico

 0
Author: Raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-08 09:37:27

Eliminar nuevos caracteres de línea con datos de columna SQL

Update a set  a.CityName=Rtrim(Ltrim(REPLACE(REPLACE(a.CityName,CHAR(10),' '),CHAR(13),' ')))
,a.postalZone=Rtrim(Ltrim(REPLACE(REPLACE(a.postalZone,CHAR(10),' '),CHAR(13),' ')))  
From tAddress a 
inner Join  tEmployees p  on a.AddressId =p.addressId 
Where p.MigratedID is not null and p.AddressId is not null AND
(REPLACE(REPLACE(a.postalZone,CHAR(10),'Y'),CHAR(13),'X') Like 'Y%' OR REPLACE(REPLACE(a.CityName,CHAR(10),'Y'),CHAR(13),'X') Like 'Y%')
 -2
Author: malinda sanjaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-23 18:10:09