如何根据旧值使用新值更新 table 中的记录列表
how can I update a list of records in a table with the new value depending on the old value
我有一个名为 acc1152 的 table,字段为 accno。根据该字段的值,我需要用新值替换它。这些是我需要更新的值
old value new value
7007 4007
7008 4008
4008 7
7009 4009
7011 4011
4011 ' '
7010 4010
4010 1
7016 4016
4016 1
4506 4006
4512 4012
如果记录在其 accno 字段中具有上述旧值,则需要用新值替换该 accno
如何编写一个查询来完成此任务?
以下应该适用于任何数据库(它是 ANSI 标准 SQL):
update acc1152 t
set accno = (select r.newvalue from replacements r where r.oldvalue = t. acc1152)
where exists (select 1 from replacements where r.oldvalue = t. acc1152);
根据数据库的不同,还有其他方法。
这假设您的替换值在 table 中,我称之为 replacements
。
您可以在更新语句中使用 case
语句,如下所示:
update acc1152
set [columnName] =
case [columnName]
when '7007' then '4007'
when '7008' then '4008'
-- etc
when '4512' then '4012'
else
[columnName] end
或者更好的方法 (IMO) 是使用 temp/variable table 来跟踪您的 old/new 映射
declare @someTable table (oldValue varchar(50), newValue varchar(50))
insert into @someTable (oldValue, newValue)
select '7007','4007'
union all select '7008','4008'
-- etc
union all select '4512','4012'
update acc1152
set [columnName] = st.newValue
from acc1152 a
inner join @someTable st on a.[columnName] = st.oldValue
我有一个名为 acc1152 的 table,字段为 accno。根据该字段的值,我需要用新值替换它。这些是我需要更新的值
old value new value
7007 4007
7008 4008
4008 7
7009 4009
7011 4011
4011 ' '
7010 4010
4010 1
7016 4016
4016 1
4506 4006
4512 4012
如果记录在其 accno 字段中具有上述旧值,则需要用新值替换该 accno
如何编写一个查询来完成此任务?
以下应该适用于任何数据库(它是 ANSI 标准 SQL):
update acc1152 t
set accno = (select r.newvalue from replacements r where r.oldvalue = t. acc1152)
where exists (select 1 from replacements where r.oldvalue = t. acc1152);
根据数据库的不同,还有其他方法。
这假设您的替换值在 table 中,我称之为 replacements
。
您可以在更新语句中使用 case
语句,如下所示:
update acc1152
set [columnName] =
case [columnName]
when '7007' then '4007'
when '7008' then '4008'
-- etc
when '4512' then '4012'
else
[columnName] end
或者更好的方法 (IMO) 是使用 temp/variable table 来跟踪您的 old/new 映射
declare @someTable table (oldValue varchar(50), newValue varchar(50))
insert into @someTable (oldValue, newValue)
select '7007','4007'
union all select '7008','4008'
-- etc
union all select '4512','4012'
update acc1152
set [columnName] = st.newValue
from acc1152 a
inner join @someTable st on a.[columnName] = st.oldValue