SQL Server 替换,删除特定字符后的所有字符

SQL Server replace, remove all after certain character(SQL Server 替换,删除特定字符后的所有字符)
本文介绍了SQL Server 替换,删除特定字符后的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据看起来像

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

如何更新 MyText 以删除分号之后的所有内容并包括分号,所以我只剩下以下内容:

How can I update MyText to drop everything after the semi-colon and including the semi colon, so I'm left with the following:

ID    MyText
1     some text
2     text again

我查看了 SQL Server Replace,但不能'没有想到检查;"的可行方法

I've looked at SQL Server Replace, but can't think of a viable way of checking for the ";"

推荐答案

使用 LEFT 与 CHARINDEX 结合:

Use LEFT combined with CHARINDEX:

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

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

Note that the WHERE clause skips updating rows in which there is no semicolon.

这里有一些代码来验证上面的 SQL 是否有效:

Here is some code to verify the SQL above works:

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)

这篇关于SQL Server 替换,删除特定字符后的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)