SQL 服务器:更新替换语句 - 代码失败或错误?
SQL Server : update replace statement - code fail or bug?
我正在尝试用 "L" 替换字符串中的所有字母,并在 SQL Server 2014 中用字母 "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(第 1 列)= abc(第 2 列)
如果我只查询一个提交,例如update my_table set column2 = replace(column1, 'a', 'L');
然后它工作正常,它将所有 A 替换为 L。
我尝试用 Sqlite 执行这个查询并用较小的数据库测试它,它工作得很好,但我真的需要在 mssql 中完成这个工作。
非常感谢对这个问题的任何支持。
我刚开始使用 SQL 服务器,我仍在努力适应变化。
p.s。 column2 varchar(64)
我认为这就是您的代码中发生的情况。将 column2
视为 '123456'
,将 column1
视为 'ab1'
。那么你运行第一个更新:
update my_table set column2 = replace(column1, 'a', 'L');
column1 = ab1
column2 = Lb1
第二次更新:
update my_table set column2 = replace(column1, 'b', 'L');
column1 = ab1
column2 = aL1
第三次更新:
update my_table set column2 = replace(column1, '1', 'N');
column1 = ab1
column2 = abN
因此,因为您从不更改 column1
,所以您将始终采用 "latest version" 并更新它。那么如何解决这个问题。一种不太好的方式是这样的:
update my_table set column2 =
replace(
replace(
replace(column1, 'a', 'L'),
'b', 'L'),
'1', 'N');
column1 = ab1
column2 = LLN
我不知道你的 column_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
我正在尝试用 "L" 替换字符串中的所有字母,并在 SQL Server 2014 中用字母 "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(第 1 列)= abc(第 2 列)
如果我只查询一个提交,例如update my_table set column2 = replace(column1, 'a', 'L');
然后它工作正常,它将所有 A 替换为 L。
我尝试用 Sqlite 执行这个查询并用较小的数据库测试它,它工作得很好,但我真的需要在 mssql 中完成这个工作。
非常感谢对这个问题的任何支持。
我刚开始使用 SQL 服务器,我仍在努力适应变化。
p.s。 column2 varchar(64)
我认为这就是您的代码中发生的情况。将 column2
视为 '123456'
,将 column1
视为 'ab1'
。那么你运行第一个更新:
update my_table set column2 = replace(column1, 'a', 'L');
column1 = ab1
column2 = Lb1
第二次更新:
update my_table set column2 = replace(column1, 'b', 'L');
column1 = ab1
column2 = aL1
第三次更新:
update my_table set column2 = replace(column1, '1', 'N');
column1 = ab1
column2 = abN
因此,因为您从不更改 column1
,所以您将始终采用 "latest version" 并更新它。那么如何解决这个问题。一种不太好的方式是这样的:
update my_table set column2 =
replace(
replace(
replace(column1, 'a', 'L'),
'b', 'L'),
'1', 'N');
column1 = ab1
column2 = LLN
我不知道你的 column_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