Sql-Server
用單個字元替換所有數值
我在 SQL 表中有一個值,如下所示:
80400365_SwapOpenTrd_20180831.csv
我想替換數值,因此返回如下:
%SwapOpenTrd%.csv
我嘗試了以下程式碼,但返回了多組 % 字元…
%%%%%%%%SwapOpenTrd%%%%%%%%%csv
我需要在此處更改什麼以獲得所需的結果?
http://sqlfiddle.com/#!18/9eecb/33261
DECLARE @Temp nvarchar(150) = '80400365_SwapOpenTrd_20180831.csv' Declare @KeepValues as varchar(50) Set @KeepValues = '%[^a-z_% ]%' -- keep underscore and space While PatIndex(@KeepValues, @Temp) > 0 Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '%') select @Temp
根據您的最新評論,我對您的原始範例進行了一些更改。以下邏輯防止重複
%
被填充。看看這是否適合你。
DECLARE @Temp NVARCHAR(150) = 'Numara_03_09_2018_07_41_04_OP_NIP_CSA_5739038.XLS' DECLARE @KeepValues AS VARCHAR(50) SET @KeepValues = '%[^a-z_%. ]%' -- keep underscore and space WHILE PatIndex(@KeepValues, @Temp) > 0 BEGIN SET @Temp = CASE WHEN substring(@temp, PatIndex(@KeepValues, @Temp) - 1, 1) = '%' THEN Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '') ELSE Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '%') END END SELECT @Temp
結果
Numara_%_%_%_%_%_%_OP_NIP_CSA_%.XLS