Home Forums SQL Server 2008 T-SQL (SS2K8) Replace Data in a String Based on Data in Table In line Query RE: Replace Data in a String Based on Data in Table In line Query

  • Below is the Query Solved the Problem:

    declare @string varchar(500)

    set @string = '-1 * [ALL_1] + [BAL] - [SAL]'

    declare @pos int

    declare @piece varchar(500)

    declare @EXIS_VALUE VARCHAR(100)

    declare @string_new varchar(500)

    --Need to tack a delimiter onto the end of the input string if one doesn’t exist

    if right(rtrim(@string),1) <> '['

    set @string_new = @string

    set @string = @string + '['

    Set @string = REPLACE(@string,' ','')

    set @pos = CHARINDEX('[' , @string)

    while @pos <> 0

    begin

    set @piece = left(@string, @pos - 1)

    SET @piece = REPLACE(@piece,']','')

    set @piece = REPLACE(@piece,'-','')

    set @piece = REPLACE(@piece,'+','')

    -- You have a piece of data, so insert it, print it, do whatever you want to with it.

    SELECT @EXIS_VALUE=PAYMENT_TYPE from TEST_DATA_SRC WHere PAYMENT_TYPE in (@piece);

    IF @EXIS_VALUE IS NULL

    set @string_new = REPLACE(@string_new,'['+@piece+']',0)

    -- SET @piece = 0

    print cast(@piece as varchar(500))

    Print cast(@string_new as varchar(500))

    set @string = stuff(@string, 1, @pos, '')

    set @pos = CHARINDEX('[' , @string)

    Set @EXIS_VALUE = NULL

    end

    print ''

    Print 'FINAL_STRING:'+cast(@string_new as varchar(500))