MAK
MAK

Reputation: 7270

SQL Server 2008 R2: Select statement within REPLACE()

I have two tables as shown below:

Table1 : Test1

Create table Test1
(
  name varchar(50) 
);

Insertion:

insert into Test1 values('a$xyz');  
insert into Test1 values('xyz$a');

Table2 : Test2

create table Test2
(
  pattern varchar(50)
);

Insertion:

insert into Test2 values('a$');
insert into Test2 values('$a');

Now I want to update the table Test1. Specifically I want to update the name in the table by replacing the pattern of table Test2.

Like:

update Test2
set name = replace(name,'a$','');

How can I get the string_to_replace from the table Test2? As per my knowledge we can't use SELECT within REPLACE function.

Upvotes: 1

Views: 291

Answers (4)

t-clausen.dk
t-clausen.dk

Reputation: 44336

This script will only update each row once.

Create this function:

CREATE FUNCTION f_test
(
   @a varchar(50)
) 
returns varchar(50)
AS
BEGIN
  SELECT @a = replace(@a, pattern, '') 
  FROM test2
  RETURN @a
END

Call it like this:

UPDATE test1
SET name = dbo.f_test(name)

EDIT:

Instead of updating all rows, this may be more effective since it only updates the relevant rows:

;WITH CTE as
(
  SELECT name, dbo.f_test(name) namenew
  FROM test1
)
UPDATE CTE
SET name = namenew
WHERE name <> namenew

Upvotes: 2

Carsten Massmann
Carsten Massmann

Reputation: 28236

Or, using a cursor to run through all the replaces multiple times:

DECLARE @pat varchar(8)
DECLARE patc CURSOR FOR SELECT pattern FROM test2
OPEN patc
FETCH NEXT FROM patc INTO @pat
WHILE @@FETCH_STATUS = 0
BEGIN
 UPDATE test1 SET name=REPLACE(name,@pat,'')
 FETCH NEXT FROM patc INTO @pat 
END

SELECT * FROM test1

Maybe a bit "much" code, but it works, see here: http://www.sqlfiddle.com/#!3/7289c/2

The previous solutions by Deepanshu Kalra and Mukund do work fine for your given example, as at most one of the patterns is found in each case. For the more general case where several patterns might be found (and applied) to a single word the cursor approach is the more general solution.

Upvotes: 1

Mukund
Mukund

Reputation: 1689

I think this is what you are looking for.

Update t1
set t1.name = replace(name,t2.pattern,'')
from Test1 t1 , Test2 t2
where t1.name like '%'+t2.pattern+'%'

select * from Test1

check sqlfiddle : http://www.sqlfiddle.com/#!3/eda97/6

Upvotes: 1

Deep Kalra
Deep Kalra

Reputation: 1428

WHILE ( 1 = 1 ) 
  BEGIN 
      UPDATE Test1 
      SET    Test1.NAME = Replace(Test1.NAME, Test2.pattern, '') 
      FROM   Test1, 
             Test2 
      WHERE  ( Test1.NAME LIKE '%' + Test2.pattern + '%' ) 

      IF @@rowcount = 0 
        BREAK 
  END 

SELECT * 
FROM   Test1 

SQL Fiddle

Upvotes: 2

Related Questions