SQLServer 替换,删除某些字符后的所有内容

我的数据看起来

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

如何更新 MyText,删除分号后面的所有内容,包括分号,所以我留下了以下内容:

ID    MyText
1     some text
2     text again

我已经看了 替换 SQLServer,但是想不出一个可行的方法来检查“ ;

277799 次浏览

使用 CHARINDEX查找“ ;”,然后使用 SUBSTRING返回“ ;”之前的部分。

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

使用结合 CHARINDEX 的左边:

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

请注意,WHERE 子句跳过更新没有分号的行。

下面是一些验证 SQL 的代码:

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

我得到了以下结果:

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)

对于某些字段有“ ;”而某些字段没有的情况,也可以向字段添加分号,并使用所述相同的方法。

SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)

可以使用 CASE WHEN让那些没有“ ;”的人独处。

    SELECT
CASE WHEN CHARINDEX(';', MyText) > 0 THEN
LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
MyText END
FROM MyTable

对于需要替换或匹配(查找)字符串的情况,我更喜欢使用正则表达式。

由于 T-SQL不完全支持正则表达式,所以可以使用 CLR函数实现它们。此外,您根本不需要任何 C#CLR知识,因为您所需要的全部知识已经在 MSDN字符串实用程序函数示例中可用。

在您的例子中,使用正则表达式的解决方案是:

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

但是在数据库中实现这样的功能将帮助您解决更复杂的问题。


下面的例子展示了如何只部署 [dbo].[RegexReplace]函数,但是我建议您部署整个 String Utility类。

  1. 启用 CLR 集成。执行以下 Transact-SQL 命令:

    sp_configure 'clr enabled', 1
    GO
    RECONFIGURE
    GO
    
  2. Bulding the code (or creating the .dll). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.

    • create new class library project:

      enter image description here

    • copy and paste the following code in the Class1.cs file:

      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);
      }
      }
      
    • build the solution and get the path to the created .dll file:

      enter image description here

    • replace the path to the .dll file in the following T-SQL statements and execute them:

      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
      
    • That's it. Test your function:

      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
      

SQL 服务器 经过一段时间后移除一切

UPDATE table_name
SET col_name = LEFT(col_name, CHARINDEX('.', col_name) - 1)
WHERE col_name LIKE '%.%'