考虑这个字符串:
http://kliks.affiliate4you.nl/?adv=17847&web=1426&subid=4083&url=http%3A%2F%2Fwww.bartsmit.com%2Fshop%2Fnl%2Fbsnl%2Fpaw-patrol%2Fpaw-patrol-racers-pup-zuma**%3Fchannel_code%3D83%26product_code%3D94193039%26referer%3Da4you&linkinfo=czA4YBartSmit**
%3Fchannel_code
czA4YBartSmit
我想做的事情如下:update table set string =(string,但没有以%3Fchannel_code
开头并以czA4YBartSmit
结尾的部分)
答案 0 :(得分:2)
您可以使用CHARINDEX
的组合来更新表中的行以查找起始位置,并LEFT
来截断字符串。
您可以使用'3Fchannel_code'和'czA4YBartSmit'作为过滤条件,将更新限制为仅包含的字符串,并分别以这些字词结尾。此外,与%
一起使用时,LIKE
将用作通配符,因此需要使用[%]
进行转义。
BEGIN TRAN;
UPDATE MyTable
SET [string] =
LEFT([string], charindex('%3Fchannel_code', [string]) - 1)
FROM MyTable
WHERE [string] like '%[%]3Fchannel_code%czA4YBartSmit'
-- Check the update with a SELECT
-- If you are Happy, COMMIT, otherwise ROLLBACK
上使用LEFT, RIGHT and CHARINDEX
进行字符串操作有一个很好的概述
警告:在以这种方式更新数据之前,建议您在事务中包装更新,以防万一。
答案 1 :(得分:1)
使用replace
,substring
,charindex
,即使删除的字符串不在最后或开始时,这也适用:
update table
set string =
replace(string ,
substring(
string ,charindex('%3Fchannel_code',string ),charindex('czA4YBartSmit',string ))
,'')
sqmple:
declare @str varchar(500)='http://kliks.affiliate4you.nl/?adv=17847&web=1426&subid=4083&url=http%3A%2F%2Fwww.bartsmit.com%2Fshop%2Fnl%2Fbsnl%2Fpaw-patrol%2Fpaw-patrol-racers-pup-zuma%3Fchannel_code%3D83%26product_code%3D94193039%26referer%3Da4you&linkinfo=czA4YBartSmit'
select replace(@str,
substring(@str,charindex('%3Fchannel_code',@str),charindex('czA4YBartSmit',@str))
,'')
输出:
http://kliks.affiliate4you.nl/?adv=17847&web=1426&subid=4083&url=http%3A%2F%2Fwww.bartsmit.com%2Fshop%2Fnl%2Fbsnl%2Fpaw-patrol%2Fpaw-patrol-racers-pup-zuma