使用STUFF替换SQL中的字符串,其字符串小于要替换的字符串

时间:2017-01-23 19:22:21

标签: sql-server string

我需要在URL中间替换SQL中的字符串,该URL是具有另一个文件夹路径的文件夹路径。要替换的文件夹路径将更小,更大或与要替换的文件夹大小相同。我正在尝试使用xmlns:custom="http://schemas.android.com/apk/res-auto" ,但它只替换了我插入的相同数量的字符。

如何更换不同的弦长? 这是我的SQL 在下面的示例中,我想将 UDS + Reports%2fDSParameterizedDynamicReports 替换为 UDSReports%2fPWReports

STUFF

1 个答案:

答案 0 :(得分:0)

原始尝试的一个问题是REVERSE(CHARINDEX('%2f', @NewFilePath))应该是CHARINDEX('f2%', reverse(@NewFilePath))

一旦您在字符串的反向查找模式,您还需要反转该模式,因此'%2f'变为'f2%'

另一个问题是charindex()返回模式的起始位置,所以使用3长度模式,您需要相应地调整输出。

以下是两个更正版本,一个使用东西,另一个没有东西:

没有stuff():连接新中间的第一个字符串的开头和结尾

set @newfilepath = 
  left(@newfilepath,charindex('%2f',@newfilepath)+2)
  +@reportfilepath
  +right(@newfilepath,charindex('f2%',reverse(@newfilepath))+2)   

stuff()

set @newfilepath = stuff(
    @newfilepath
  , (charindex('%2f',@newfilepath)+3)
  , len(@newfilepath)
    -(charindex('%2f',@newfilepath)+2)
    -(charindex('f2%',reverse(@newfilepath))+2)
  , @reportfilepath 
  )

rextester:http://rextester.com/GDFFV41538

declare @startposition int, @stringlength int, @parameterlist varchar(max)

declare @newfilepath varchar(max) = 'http://servername/ReportServer?%2fUDS+Reports%2fDSParameterizedDynamicReports%2fPatientsbyCode'
declare @reportfilepath varchar(200) = 'UDSReports/PWReports'
select @reportfilepath = replace(replace(@reportfilepath, ' ', '+'), '/', '%2f')

;with cte as (
select  
    LeftPart=left(@newfilepath,charindex('%2f',@newfilepath)+2)
  , MiddlePart=@reportfilepath
  , RightPart=right(@newfilepath,charindex('f2%',reverse(@newfilepath))+2)
  , woStuff=
      left(@newfilepath,charindex('%2f',@newfilepath)+2)
      +@reportfilepath
      +right(@newfilepath,charindex('f2%',reverse(@newfilepath))+2)   
  , wStuff = stuff(
        @newfilepath
      , (charindex('%2f',@newfilepath)+3)
      , len(@newfilepath)
          -(charindex('%2f',@newfilepath)+2)
          -(charindex('f2%',reverse(@newfilepath))+2)
      ,@reportfilepath 
      )

)
select 
    wostuff =replace(wostuff,'%2f','/')
  , wstuff  =replace(wstuff,'%2f','/')
  , samesame=case when wStuff=woStuff then 'true' else 'false' end
from cte