SQL Server reemplazar, eliminar todo después de cierto carácter


Mis datos parecen

ID    MyText
1     some text; some more text
2     text again; even more text

¿Cómo puedo actualizar MyText para soltar todo después del punto y coma e incluyendo el punto y coma, así que me quedo con lo siguiente:

ID    MyText
1     some text
2     text again

He mirado SQL Server Replace , pero no puedo pensar en una forma viable de comprobar el"; "

Author: OMG Ponies, 2009-11-03

6 answers

Use la IZQUIERDA combinada con CHARINDEX:

UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

Tenga en cuenta que la cláusula WHERE omite actualizar filas en las que no hay punto y coma.

Aquí hay un código para verificar que el SQL anterior funciona:

declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself    

UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0

select * from @MyTable

Obtengo los siguientes resultados:

id MyText
-- -------------------------
1  some text
2  text again
3  text without a semicolon
4  NULL
5        (empty string)
6  test 3 semicolons
7        (empty string)
 86
Author: Paul Williams,
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-12 12:59:34

Para los momentos en que algunos campos tienen un ";" y otros no, también puede agregar un punto y coma al campo y usar el mismo método descrito.

SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)
 16
Author: Rashlien,
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
2010-12-07 23:14:31

Podría usar CASE WHEN para dejar a los que no tienen ';' solos.

    SELECT
    CASE WHEN CHARINDEX(';', MyText) > 0 THEN
    LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
    MyText END
    FROM MyTable
 9
Author: Rookie,
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-06-17 10:21:19

Use CHARINDEX para encontrar el ";". Luego use SUBSTRING para devolver la parte antes de";".

 3
Author: David,
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-06-17 10:21:01
UPDATE MyTable
   SET MyText = SUBSTRING(MyText, 1, CHARINDEX(';', MyText) - 1)
 WHERE CHARINDEX(';', MyText) > 0 
 2
Author: manji,
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
2009-11-03 15:54:34

Para situaciones en las que necesito reemplazar o hacer coincidir(encontrar) algo con una cadena, prefiero usar expresiones regulares.

Dado que las expresiones regulares no están completamente soportadas en T-SQL puede implementarlas usando las funciones CLR. Además, no necesita ningún conocimiento C# o CLR, ya que todo lo que necesita ya está disponible en el Ejemplo de Funciones de Utilidad de cadena de MSDN .

En su caso, la solución que utiliza expresiones regulares es:

SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]

Pero implementar tal función en su base de datos le ayudará a resolver problemas más complejos.


El siguiente ejemplo muestra cómo implementar solo la función [dbo].[RegexReplace], pero le recomendaré implementar toda la clase String Utility.

  1. Habilitando la integración CLR. Ejecute los siguientes comandos Transact-SQL:

    sp_configure 'clr enabled', 1
    GO
    RECONFIGURE
    GO  
    
  2. Construyendo el código (o creando el .dll). Generraly, puede hacer esto usando el comando Visual Studio o. NET Framework prompt (como se muestra en el artículo), pero prefiero usar visual studio.

    • Crear un nuevo proyecto de biblioteca de clases:

      introduzca la descripción de la imagen aquí

    • Copie y pegue el siguiente código en el archivo Class1.cs:

      using System;
      using System.IO;
      using System.Data.SqlTypes;
      using System.Text.RegularExpressions;
      using Microsoft.SqlServer.Server;
      
      public sealed class RegularExpression
      {
          public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
          {
              string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
              string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
              string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
              return Regex.Replace(input, pattern, replacement);
          }
      }
      
    • Construya la solución y obtenga la ruta al archivo .dll creado:

      introduzca la descripción de la imagen aquí

    • Reemplace la ruta al archivo .dll en las siguientes instrucciones T-SQL y ejecute {[17]]}

      IF OBJECT_ID(N'RegexReplace', N'FS') is not null
      DROP Function RegexReplace;
      GO
      
      IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
      DROP ASSEMBLY StringUtils;
      GO
      
      DECLARE @SamplePath nvarchar(1024)
      -- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
      Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
      CREATE ASSEMBLY [StringUtils] 
      FROM @SamplePath + 'StringUtils.dll'
      WITH permission_set = Safe;
      GO
      
      
      CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
      RETURNS nvarchar(max)
      AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
      GO
      
    • Eso es todo. Prueba tu función:

      declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
      insert into @MyTable ([id], MyText)
      select 1, 'some text; some more text'
      union all select 2, 'text again; even more text'
      union all select 3, 'text without a semicolon'
      union all select 4, null -- test NULLs
      union all select 5, '' -- test empty string
      union all select 6, 'test 3 semicolons; second part; third part'
      union all select 7, ';' -- test semicolon by itself    
      
      SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
      FROM @MyTable
      
      select * from @MyTable
      
 1
Author: gotqn,
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-01 10:55:48