如何替换字符串中的所有列
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
答案 0 :(得分:1)
介绍有关替换文本的更多信息。这是一个很好的例子:
DECLARE @invalidColumns varchar(max) = replace('abc, xyz', ' ', '')
DECLARE @sqltext varchar(max) = ''
;WITH t1 as
(
SELECT '(*' pat, '(abc = ''sometext'')' txt, 'abc' col
UNION ALL SELECT 'OR *)' pat, 'OR (xyz = '' some more text'')' txt, 'xyz' col
UNION ALL SELECT 'OR *' pat, '(pqr = ''vb'')' txt, 'pqr' col
UNION ALL SELECT 'AND *' pat, 'abc != '' text ''' txt, 'abc' col
UNION ALL SELECT 'OR (*' pat, '(hht = ''asd asd'')' txt, 'hht' col
UNION ALL SELECT 'AND(*)' pat, 'xyz = ''''''' txt, 'xyz' col
), t2 as
(
SELECT t.c.value('.', 'VARCHAR(20)') col
FROM (
SELECT x = CAST('<t>' +
REPLACE(@invalidColumns, ',', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c)
)
SELECT @sqltext = @sqltext
+ replace(t1.pat, '*', case when t2.col is null then t1.txt else ' 1 = 1 ' end)
FROM t1
LEFT JOIN t2 on t1.col = t2.col
SELECT @sqltext