Sql 如何在没有字符串最后一部分的情况下更新

Sql 如何在没有字符串最后一部分的情况下更新,sql,sql-server,tsql,Sql,Sql Server,Tsql,考虑以下字符串: http://kliks.affiliate4you.nl/?adv=17847&web=1426&subid=4083&url=http%3A%2F%2Fwww.bartsmit.com%2Fshop%2Fnl%2Fbsnl%2Fpaw-巡逻%2Paw patrol racers pup zuma**%3F频道代码%3D83%26产品代码%3D94193039%26参考者%3Da4you&linkinfo=czA4YBartSmit** 我在数据库字段中有数千个这样的字符串

考虑以下字符串:

http://kliks.affiliate4you.nl/?adv=17847&web=1426&subid=4083&url=http%3A%2F%2Fwww.bartsmit.com%2Fshop%2Fnl%2Fbsnl%2Fpaw-巡逻%2Paw patrol racers pup zuma**%3F频道代码%3D83%26产品代码%3D94193039%26参考者%3Da4you&linkinfo=czA4YBartSmit**

  • 我在数据库字段中有数千个这样的字符串
  • 我想删除字符串的粗体部分
  • 我知道它以
    %3fcchannel\u code
  • 我知道它以czA4YBartSmit结尾
  • 在这两者之间,每个记录都是不同的

我想做一些类似的事情:updatetable set string=(string,但不包括以
%3Fchannel\u code
开头并以
czA4YBartSmit
结尾的部分)

您可以使用以下组合来更新表中的行:定位开始位置,使用
LEFT
来截断字符串

您可以使用“3Fchannel_code”和“czA4YBartSmit”作为筛选条件,将更新限制为仅包含这些术语并分别以这些术语结尾的字符串。另外,
%
类似时用作通配符,因此需要使用
[%]
进行转义

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和CHARINDEX
进行字符串操作有一个很好的概述


警告:在以这种方式更新数据之前,建议您在事务中包装更新,以防万一。

使用
替换
子字符串
charindex
即使删除的字符串不在末尾或开头,此操作也适用:

update table 
set string = 
replace(string ,
substring(
string ,charindex('%3Fchannel_code',string ),charindex('czA4YBartSmit',string ))
       ,'')
SQPLE:

输出:


效果很好。最终使用LEFT(kado_url,charindex('3fcchannel_code',kado_url)-2)来避免%的问题。我还将charindex('3fcchannel_code',kado_url)>0添加到我的where子句中,这很好用。@str将被数据库字段名替换,然后不使用declare。我还将charindex('3fcchannel_code',kado_url)>0添加到我的where子句中以确保这一点。
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