Jim*_*mmy 50 sql t-sql sql-server replace
我的数据看起来像
ID MyText
1 some text; some more text
2 text again; even more text
Run Code Online (Sandbox Code Playgroud)
如何更新MyText以删除分号后的所有内容并包括半冒号,所以我留下以下内容:
ID MyText
1 some text
2 text again
Run Code Online (Sandbox Code Playgroud)
我看过SQL Server Replace,但想不出一种检查";"的可行方法.
Pau*_*ams 97
使用LEFT结合CHARINDEX:
UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
Run Code Online (Sandbox Code Playgroud)
请注意,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
Run Code Online (Sandbox Code Playgroud)
我得到以下结果:
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)
Run Code Online (Sandbox Code Playgroud)
Ras*_*ien 19
对于某些字段有";"的时间 有些不能你也可以在字段中添加一个分号并使用相同的方法描述.
SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)
Run Code Online (Sandbox Code Playgroud)
小智 11
可以CASE WHEN用来留下没有';'的人 单独.
SELECT
CASE WHEN CHARINDEX(';', MyText) > 0 THEN
LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
MyText END
FROM MyTable
Run Code Online (Sandbox Code Playgroud)