我的数据看起来像
ID MyText
1 some text; some more text
2 text again; even more text
我如何更新MyText以删除分号之后的所有内容,包括分号,所以我只剩下以下内容:
ID MyText
1 some text
2 text again
我看了SQL Server Replace个,但想不出一个可行的方法来判断";"
我的数据看起来像
ID MyText
1 some text; some more text
2 text again; even more text
我如何更新MyText以删除分号之后的所有内容,包括分号,所以我只剩下以下内容:
ID MyText
1 some text
2 text again
我看了SQL Server Replace个,但想不出一个可行的方法来判断";"
将LEFT与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)