2017-01-23 152 views
1

我需要使用另一個文件夾路徑替換位於具有文件夾路徑的URL中間的SQL中的字符串。要替換的文件夾路徑將會更小,更大或與正在替換的文件夾的大小相同。我正在嘗試使用STUFF,但它只替換了我插入的相同數量的字符。使用STUFF替換SQL中的字符串,並使用小於要替換的字符串的字符串

如何適應不同的字符串長度來替換? 這是我的SQL 在下面的例子我想與你原來的企圖取代UDS +報告%2fDSParameterizedDynamicReportsUDSReports%2fPWReports

DECLARE @StartPosition int, @StringLength int 
DECLARE @NewFilePath varchar(max) = 'http://servername/ReportServer?%2fUDS+Reports%2fDSParameterizedDynamicReports%2fPatientsbyCode' 
DECLARE @ReportFilePath varchar(200) = 'UDSReports/PWReports' 
SELECT @ReportFilePath = REPLACE(REPLACE(@ReportFilePath, ' ', '+'), '/', '%2f') 
SELECT @ReportFilePath 
DECLARE @StartPosition int, @StringLength int, @ParameterList varchar(max) 
SELECT @StartPosition = CHARINDEX('%2f', @NewFilePath) + 1 
SELECT @StartPosition 
     SELECT @StringLength = REVERSE(CHARINDEX('%2f', @NewFilePath)) - @StartPosition 
SELECT @StringLength 
     SELECT @NewFilePath = STUFF(@NewFilePath, @StartPosition, @StringLength, @ReportFilePath) 
SELECT @NewFilePath 
+0

請寫出所需的最終選擇輸出 – EoinS

+0

@GloriaSantin對此有何更新? – SqlZim

回答

0

一個問題是,REVERSE(CHARINDEX('%2f', @NewFilePath))應該已經CHARINDEX('f2%', reverse(@NewFilePath))

一旦你正在尋找一個字符串反轉的模式,你也需要反轉模式,所以'%2f'變成'f2%'

另一個問題是,charindex()返回模式的起始位置,所以對於3長度模式,您需要相應地調整輸出。

下面是使用的東西,一個沒有東西兩個經校正的版本之一:

沒有stuff():串聯的第一個字符串的新中間

set @newfilepath = 
    left(@newfilepath,charindex('%2f',@newfilepath)+2) 
    [email protected] 
    +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) 
    , [email protected] 
    , RightPart=right(@newfilepath,charindex('f2%',reverse(@newfilepath))+2) 
    , woStuff= 
     left(@newfilepath,charindex('%2f',@newfilepath)+2) 
     [email protected] 
     +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