Replace SQL SERVER between columns

Asked

Viewed 516 times

0

How to replace between columns in SQL SERVER. For example, given the table below:

COLUNA_A | COLUNA B | COLUNA_C
A          123        casa

I tried to run the query:

SELECT REPLACE(COLUNA_C, COLUNA_A, COLUNA_B ) FROM TABELA

To try to get the result:

COLUNA_A | COLUNA B | COLUNA_C
A          123        c123s123

But it didn’t work. How can I do this replace using column values?

If you do so:

SELECT REPLACE(COLUNA_C, 'a', COLUNA_B ) FROM TABELA

works normally. Even I tried to use a cast or Convert in COLUNA_A E COLUNA_B, inside replace, also unsuccessfully.

  • What does "didn’t work"? How are the columns declared? What is their COLLATE?

  • @Josédiz Latin1_general_ci_as

  • @Josédiz does not change anything. The query executes, and with replace shows the same thing without replace. The return looks like this: COLUNA_A | COLUMN B | COLUNA_C (replace) A 123 house

  • 1

    (1) We need to analyze the individual COLLATE of each column. The database can be in one COLLATE, the instance in another COLLATE and each column in other COLLATE... (2) It is certain that in the column coluna_A is there only one character? Beware of spaces and not visible characters.

  • It wasn’t the collate, but it was the invisible spaces and characters. Then just went to do REPLACE(COLUNA_C, LTRIM(RTRIM(COLUNA_A), COLUNA_B) and problem was solved.

  • Bloody spaces... ;)

Show 1 more comment

1 answer

1


The construction with the REPLACE() function is correct. If it did not work, one hypothesis is that the columns are defined with grouping case sensitive. If that is the case, A is different from a.

To assess whether the reason is grouping case sensitive, try it:

-- código #1 v2
IF Object_ID('TABELA','U') is not null
  DROP TABLE dbo.TABELA;
go

CREATE TABLE dbo.TABELA (
     coluna_A varchar(20) collate Latin1_General_CS_AS, 
     coluna_B varchar(20) collate Latin1_General_CS_AS, 
     coluna_C varchar(20) collate Latin1_General_CS_AS
);

INSERT into dbo.TABELA (coluna_A, coluna_B, coluna_C) values
  ('A', '123', 'casa_X'),
  ('a', '123', 'casa_Y');

SELECT replace (coluna_C, coluna_A, coluna_B)
  from dbo.TABELA;

SELECT replace (coluna_C collate Latin1_General_CI_AS, coluna_A, coluna_B)
  from dbo.TABELA;

I did not test code #1 after modification. May contain error(s).

  • I tried your solution with no result. Thank you very much. It is not case sensitive.

  • I know it is not case sensitive, because I made a test query here as the same values in both columns, but replace does not perform as expected. Only executes if I put a manual string (for example: 'A' or 'a') in the second parameter, but I wanted the change to be dynamic.

  • Pose being the size of the "a" column is different from 'a ' .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.