如何替换字符串中的所有列
DECLARE @invalidColumns varchar(200) = 'abc, xyz'
DECLARE @sqltext varchar(max) = '((abc = ''sometext'') OR (xyz = '' some more text'')) OR
(pqr = ''vb'') AND ( abc != '' text '')
OR ((hht = ''asd asd'') AND ( xyz = '' More text '' ))
'
在上面的示例中,我必须在 @sqlText 中搜索列 abc 和 xyz 并将它们全部替换为 1=1
所以最终输出应该看起来像
((1 = 1) OR (1 = 1)) OR
(pqr = ''vb'') AND ( 1 != 1)
OR ((hht = ''asd asd'') AND ( 1 = 1 ))
我试图这样做,但似乎替换功能不适用于模式,它也只能用于第一次查找。abc 和 xyz 列可能会在语句中出现多次。
SELECT CASE WHEN PATINDEX('%abc% ''%',@sqltext) > 0
THEN REPLACE (@sqlText,'%abc% ''%', '1=1')
END
任何帮助
编辑
我试过这个,但它没有给我正确的结果
DECLARE @len INT
DECLARE @initializor INT = 1
DECLARE @First INT
DECLARE @Result VARCHAR(max) SET @Result = ''
DECLARE @EndPattern INT
SET @len = LEN(@sqltext)
WHILE( @initializor <= @len)
BEGIN
SET @First = PATINDEX('%abc% ''%', SUBSTRING(@sqltext, @initializor, @Len))
SET @EndPattern = 1
WHILE PATINDEX('%abc% ''%', SUBSTRING(@sqltext, @initializor, @EndPattern)) = 0
SET @EndPattern = @EndPattern + 1
IF COALESCE(@First, 0) <> 0
BEGIN
SET @Result = @Result + SUBSTRING(@sqltext, @initializor, @First - 1)
SET @initializor = @initializor + @First - 1
SET @EndPattern = 1
WHILE PATINDEX('%abc% ''%', SUBSTRING(@sqltext, @initializor, @EndPattern)) = 0
SET @EndPattern = @EndPattern + 1
-- Find end of pattern range
WHILE PATINDEX('%abc% ''%', SUBSTRING(@sqltext, @initializor, @EndPattern)) > 0
AND @Len >= (@initializor + @EndPattern - 1)
SET @EndPattern = @EndPattern + 1
--Either at the end of the pattern or @Next + @EndPattern = @Len
SET @Result = @Result + '''1=1'''
SET @initializor = @initializor + @EndPattern - 1
END
SET @initializor = @initializor + 1;
END
SELECT @Result