rageit
rageit

Reputation: 3601

Using patterns in REPLACE

I need to find and replace an expression within a dynamic query. I have a subset of a where condition in string type like

'fieldA=23 OR field_1=300 OR fieldB=4'

What I need is to find a way to detect expression field_1=300 within the string and replace it while retaining the expression field_1=300.

I can do the detection part using CHARINDEX or PATINDEX but I'm not able to figure out how to use the patterns in the REPLACE function and how to get the value of the field_1 parameter.

Thanks in advance.

Upvotes: 0

Views: 129

Answers (1)

DBDave
DBDave

Reputation: 186

I'm not entirely clear on what you're trying to acheieve (e.g. what are you wanting to replace "field_1=300" with, and is it the exact string "field_1=300" that you're looking for, or just the field name, i.e. "field_1"?).

Also, could you paste in the code you've written so far?

Here's a simple script which will extract the current value of a given field name:

DECLARE @str VARCHAR(100),
        @str_tmp VARCHAR(100),
        @field_pattern VARCHAR(10),
        @field_val INT;

SET @str = 'fieldA=23 OR field_1=300 OR fieldB=4';
SET @field_pattern = 'field_1='

-- This part will extract the current value assigned to the "@field_pattern" field
IF CHARINDEX(@field_pattern, @str) > 0
BEGIN
    SELECT @str_tmp = SUBSTRING(@str, 
                        CHARINDEX(@field_pattern, @str) + LEN(@field_pattern),
                        LEN(@str)
                        );

    SELECT @field_val = CAST(SUBSTRING(@str_tmp, 1, CHARINDEX(' ', @str_tmp)-1) AS INT);
END

PRINT @field_val

If you want to replace the value itself (e.g. replacing "300" in this case with "600"), then you could add something like this:

DECLARE @new_val INT;
SET @new_val = 600;
SET @str = REPLACE(@str, (@field_pattern+CAST(@field_val AS VARCHAR)), (@field_pattern+CAST(@new_val AS VARCHAR)));
PRINT @str;

Which would give you "fieldA=23 OR field_1=600 OR fieldB=4".

Cheers, Dave

Upvotes: 1

Related Questions