Eliminar todos los espacios de una cadena en SQL Server


¿Cuál es la mejor manera de eliminar todos los espacios de una cadena en SQL Server 2008?

LTRIM(RTRIM(' a b ')) eliminaría todos los espacios a la derecha e izquierda de la cadena, pero también necesito eliminar el espacio en el medio.

Author: Brien Foss, 2012-05-03

19 answers

Simplemente reemplácelo;

SELECT REPLACE(fld_or_variable, ' ', '')

Editar Solo para aclarar; es un reemplazo global, no hay necesidad de trim() o preocuparse por múltiples espacios:

create table #t (c char(8), v varchar(8))
insert #t (c, v) values 
    ('a a'    , 'a a'    ),
    ('a a  '  , 'a a  '  ),
    ('  a a'  , '  a a'  ),
    ('  a a  ', '  a a  ')

select
    '''' + c + '''' [IN], '''' + replace(c, ' ', '') + '''' [OUT]
from #t  
union all select
    '''' + v + '''', '''' + replace(v, ' ', '') + ''''
from #t 

IN            OUT
'a a     '   'aa'
'a a     '   'aa'
'  a a   '   'aa'
'  a a   '   'aa'
'a a'        'aa'
'a a  '      'aa'
'  a a'      'aa'
'  a a  '    'aa'
 274
Author: Alex K.,
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-04-30 15:04:53

Usaría un REEMPLAZO

select REPLACE (' Hello , How Are You ?', ' ', '' )

SUSTITÚYASE

 30
Author: Eduardo Crimi,
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
2012-05-03 13:12:15

Si se trata de una actualización en una tabla, todo lo que tiene que hacer es ejecutar esta actualización varias veces hasta que afecte a 0 filas.

update tableName
set colName = REPLACE(LTRIM(RTRIM(colName)), '  ', ' ')
where colName like '%  %'
 18
Author: SQL_King,
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-05-25 05:21:07

REPLACE() función :

REPLACE(field, ' ', '')
 11
Author: Kaii,
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
2012-05-03 13:13:29

T-sql replace http://msdn.microsoft.com/en-us/library/ms186862.aspx

Sustitúyase (val,'',")

 7
Author: marko,
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
2012-05-03 13:12:54

Referencia tomada de este blog:

Primero, Cree una tabla de muestra y datos:

CREATE TABLE tbl_RemoveExtraSpaces
(
     Rno INT
     ,Name VARCHAR(100)
)
GO

INSERT INTO tbl_RemoveExtraSpaces VALUES (1,'I    am     Anvesh   Patel')
INSERT INTO tbl_RemoveExtraSpaces VALUES (2,'Database   Research and     Development  ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (3,'Database    Administrator     ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (4,'Learning    BIGDATA    and       NOSQL ')
GO

Script para SELECCIONAR cadena sin Espacios Adicionales:

SELECT
     [Rno]
    ,[Name] AS StringWithSpace
    ,LTRIM(RTRIM(REPLACE(REPLACE(REPLACE([Name],CHAR(32),'()'),')(',''),'()',CHAR(32)))) AS StringWithoutSpace
FROM tbl_RemoveExtraSpaces

Resultado:

Rno         StringWithSpace                                 StringWithoutSpace
----------- -----------------------------------------  ---------------------------------------------
1           I    am     Anvesh   Patel                      I am Anvesh Patel
2           Database   Research and     Development         Database Research and Development
3           Database    Administrator                       Database Administrator
4           Learning    BIGDATA    and       NOSQL          Learning BIGDATA and NOSQL
 7
Author: Anvesh,
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-05-23 19:08:05

Si hay varios espacios en blanco en una cadena, entonces reemplazar puede no funcionar correctamente. Para ello, se debe utilizar la siguiente función.

CREATE FUNCTION RemoveAllSpaces
(
    @InputStr varchar(8000)
)
RETURNS varchar(8000)
AS
BEGIN
declare @ResultStr varchar(8000)
set @ResultStr = @InputStr
while charindex(' ', @ResultStr) > 0
    set @ResultStr = replace(@InputStr, ' ', '')

return @ResultStr
END

Ejemplo:

select dbo.RemoveAllSpaces('aa  aaa       aa aa                 a')

Salida:

aaaaaaaaaa
 5
Author: Farhan,
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
2012-07-20 15:39:39

100% de trabajo

UPDATE table_name SET  "column_name"=replace("column_name", ' ', ''); //Remove white space

UPDATE table_name SET  "column_name"=replace("column_name", '\n', ''); //Remove newline

UPDATE table_name SET  "column_name"=replace("column_name", '\t', ''); //Remove all tab

Puedes usar "column_name" o column_name

Gracias

Subroto

 5
Author: Subroto Biswas,
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
2018-02-19 07:05:59

Esto hace el truco de eliminar los espacios en las cadenas:

UPDATE
    tablename
SET
    columnname = replace(columnname, ' ', '');
 3
Author: Mario Rojas,
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
2018-09-21 16:29:46

En caso de que necesite recortar espacios en todas las columnas, puede usar este script para hacerlo dinámicamente:

--Just change table name
declare @MyTable varchar(100)
set @MyTable = 'MyTable'

--temp table to get column names and a row id
select column_name, ROW_NUMBER() OVER(ORDER BY column_name) as id into #tempcols from INFORMATION_SCHEMA.COLUMNS 
WHERE   DATA_TYPE IN ('varchar', 'nvarchar') and TABLE_NAME = @MyTable

declare @tri int
select @tri = count(*) from #tempcols
declare @i int
select @i = 0
declare @trimmer nvarchar(max)
declare @comma varchar(1)
set @comma = ', '

--Build Update query
select @trimmer = 'UPDATE [dbo].[' + @MyTable + '] SET '

WHILE @i <= @tri 
BEGIN

    IF (@i = @tri)
        BEGIN
        set @comma = ''
        END
    SELECT  @trimmer = @trimmer + CHAR(10)+ '[' + COLUMN_NAME + '] = LTRIM(RTRIM([' + COLUMN_NAME + ']))'+@comma
    FROM    #tempcols
    where id = @i

    select @i = @i+1
END

--execute the entire query
EXEC sp_executesql @trimmer

drop table #tempcols
 2
Author: Hiram,
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
2014-03-07 22:11:03

Si desea eliminar espacios, - y otro texto de la cadena, use lo siguiente:

Supongamos que tiene un número de teléfono móvil en su Mesa como '718-378-4957' o '7183784957' y desea reemplazar y obtener el número de teléfono móvil y luego usar el siguiente texto.

select replace(replace(replace(replace(MobileNo,'-',''),'(',''),')',''),' ','') from EmployeeContactNumber

Resultado: {7183784957

 2
Author: Jeetendra Negi,
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-03-20 20:47:13

Solo un consejo, en caso de que tenga problemas con la función reemplazar, es posible que tenga el tipo de datos establecido en nchar (en cuyo caso es una longitud fija y no funcionará).

 2
Author: starbyone,
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-12-20 20:08:18

Para completar todas las respuestas anteriores, hay publicaciones adicionales en StackOverflow sobre cómo tratar con TODOS los caracteres de espacio en blanco (consulte https://en.wikipedia.org/wiki/Whitespace_character para una lista completa de estos caracteres):

 2
Author: ZJA,
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
2017-11-29 21:50:52

Tuve este problema hoy y reemplazar / recortar hizo el truco..véase más adelante.

update table_foo 
set column_bar  = REPLACE(LTRIM(RTRIM(column_bar)), '  ', '')

Antes y después :

old-bad:  column_bar    |   New-fixed:   column_bar
       '  xyz  '        |                'xyz'   
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
 1
Author: zee,
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-07-19 14:40:56

Para eliminar los espacios en una cadena izquierda y derecha. Para eliminar espacio en el uso medio Replace.

Puede usar RTRIM() para eliminar espacios de la derecha y LTRIM() para eliminar espacios de la izquierda, por lo tanto, los espacios izquierdo y derecho se eliminan de la siguiente manera:

SELECT * FROM table WHERE LTRIM(RTRIM(username)) = LTRIM(RTRIM("Bob alias baby"))
 0
Author: NarayanaReddy,
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-08-13 05:32:48

Replace (replace(column_Name,CHAR(13),"),CHAR (10),")

 0
Author: Abdullah Yousuf,
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
2018-02-14 09:29:28

esto es útil para mí:

CREATE FUNCTION dbo.TRIM(@String VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
    RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@String,CHAR(10),'[]'),CHAR(13),'[]'),char(9),'[]'),CHAR(32),'[]'),'][',''),'[]',CHAR(32))));
END
GO

.

 0
Author: Checho Man,
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
2018-03-08 17:17:29

Sintaxis para reemplazar caracteres específicos:

REPLACE ( string_expression , string_pattern , string_replacement )  

Por ejemplo, en la cadena "HelloReplaceThingsGoing" Reemplazar palabra se sustituye por Cómo

SELECT REPLACE('HelloReplaceThingsGoing','Replace','How');
GO
 0
Author: Subash J,
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
2018-03-08 17:25:25

Una versión funcional (udf) que elimina espacios, cr, lf, tabs o configurable.

select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as S

Resultado: '234asdfwefwef3x'

alter function Common.RemoveWhitespace
(
    @pString nvarchar(max),
    @pWhitespaceCharsOpt nvarchar(max) = null -- default: tab, lf, cr, space 
)  
returns nvarchar(max) as
/*--------------------------------------------------------------------------------------------------
    Purpose:   Compress whitespace

    Example:  select Common.ufn_RemoveWhitespace(' 234   asdf   wefwef 3  x   ', default) as s 
              -- Result: 234asdfwefwef3x

    Modified    By          Description
    ----------  ----------- --------------------------------------------------------------------
    2018.07.24  crokusek    Initial Version 
  --------------------------------------------------------------------------------------------------*/ 
begin    
    declare 
        @maxLen bigint = 1073741823, -- (2^31 - 1) / 2 (https://stackoverflow.com/a/4270085/538763)
        @whitespaceChars nvarchar(30) = coalesce(
            @pWhitespaceCharsOpt, 
            char(9) + char(10) + char(13) + char(32));  -- tab, lf, cr, space

    declare
        @whitespacePattern nvarchar(30) = '%[' + @whitespaceChars + ']%',
        @nonWhitespacePattern nvarchar(30) = '%[^' + @whitespaceChars + ']%',
        @previousString nvarchar(max) = '';

    while (@pString != @previousString)
    begin
        set @previousString = @pString;

        declare
            @whiteIndex int = patindex(@whitespacePattern, @pString);

        if (@whiteIndex > 0)
        begin                   
            declare 
                @whitespaceLength int = nullif(patindex(@nonWhitespacePattern, substring(@pString, @whiteIndex, @maxLen)), 0) - 1;                

            set @pString = 
                substring(@pString, 1, @whiteIndex - 1) + 
                iif(@whiteSpaceLength > 0, substring(@pString, @whiteIndex + @whiteSpaceLength, @maxLen), '');
        end        
    end        
    return @pString;
end
go
 0
Author: crokusek,
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
2018-07-24 23:32:34