Sql server SQL Server:更新替换语句-代码失败还是错误?

Sql server SQL Server:更新替换语句-代码失败还是错误?,sql-server,replace,str-replace,Sql Server,Replace,Str Replace,在SQL Server 2014中,我尝试将字符串中的所有字母替换为“L”,将所有数字替换为字母“N” 我使用以下语句: update my_table set column2 = replace(column1, 'a', 'L'); update my_table set column2 = replace(column1, 'b', 'L'); update my_table set column2 = replace(column1, '1', 'N'); etc. etc.

在SQL Server 2014中,我尝试将字符串中的所有字母替换为“L”,将所有数字替换为字母“N”

我使用以下语句:

update my_table 
set column2 = replace(column1, 'a', 'L');

update my_table 
set column2 = replace(column1, 'b', 'L');

update my_table 
set column2 = replace(column1, '1', 'N');
etc. etc.
问题是,当我执行查询时,我得到的是column2=column1,例如abc(column1)=abc(column2)

如果我只查询一个提交,例如
更新我的表集合column2=replace(column1,'a','L')然后它工作正常,它替换了所有A到L

我试着用Sqlite执行这个查询,并用较小的数据库进行了测试,结果很好,但我真的需要在mssql中实现这个功能

我非常感谢大家对这个问题的支持

我刚刚开始使用SQL Server,我仍在努力适应变化


p、 s.
column2 varchar(64)

这就是我认为在您的代码中发生的情况。考虑<代码>栏2<代码>为<代码> 123456' < /COD>和<代码> Culn1<代码>为<代码> 'ab1’< /COD>。然后运行第一次更新:

update my_table set column2 = replace(column1, 'a', 'L');
第1列=ab1
第2列=Lb1

第二次更新:

update my_table set column2 = replace(column1, 'b', 'L');
第1列=ab1
第2列=aL1

第三次更新:

update my_table set column2 = replace(column1, '1', 'N');
第1列=ab1
第2列=abN

因此,由于您从不更改
第1列
,因此您将始终使用“最新版本”并进行更新。那么如何解决这个问题呢。一种不好的方式是:

update my_table set column2 = 
  replace(
          replace(
                replace(column1, 'a', 'L'),
          'b', 'L'), 
  '1', 'N');
第1列=ab1
第2列=LLN


我不知道列_1中是否有固定长度的数据,如果数据是固定的,可以使用以下方法:

declare @Index int=1

while(@Index<= your data length here)
begin
    update my_table 
    set column_2 = REPLACE(substring(column_1, @Index, 1),
                           case 
                              when ASCII(substring(column_1, @Index, 1)) between 48 and 57 
                                then 'N' 
                                else 'L' 
                           end)

    set @Index = @Index + 1
end
declare@Index int=1

while(@index谢谢你的回答。我会试试你的代码,看看它会返回什么:)需要区分第一次更新和其他更新,因为其他更新应该更新列_2而不是1