How to replace all column in the string
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 '' ))
'
in above example I have to search for column abc and xyz in @sqlText and replace them all with 1=1
so the final output should look like
((1 = 1) OR (1 = 1)) OR
(pqr = ''vb'') AND ( 1 != 1)
OR ((hht = ''asd asd'') AND ( 1 = 1 ))
I tried to do in this way but it seems like replace function is not working with patterns, also it will do for only first finding. There may be possibility that column abc and xyz may appear multiple times in a statement.
SELECT CASE WHEN PATINDEX('%abc% ''%',@sqltext) > 0
THEN REPLACE (@sqlText,'%abc% ''%', '1=1')
END
Any help
Edit
I tried this, but it is not giving me proper result
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