我正在执行以下更新语句。此处仅列出了6行,但同样的逻辑应用于数百条记录。它确实有效,但是我没有像我那样重复更新语法,有没有办法输入更新并设置一次并以某种方式在所有行中迭代它?正如您所看到的,逻辑并不总是相同的。在这种情况下,我想添加_GRP,但原始字段值不一致,有时我想删除一些读取_2的额外文本。这是SQL Server 2012
UPDATE AOOBJECT SET NAME = 'abc_GRP' WHERE NAME = 'abc_2' AND ObjectDescription = 'Portfolio Group Description'
UPDATE AOOBJECT SET NAME = 'def_GRP' WHERE NAME = 'def' AND ObjectDescription = 'Portfolio Group Description'
UPDATE AOOBJECT SET NAME = 'ghi_GRP' WHERE NAME = 'ghi' AND ObjectDescription = 'Portfolio Group Description'
UPDATE AOOBJECT SET NAME = 'jkl_GRP' WHERE NAME = 'jkl_2' AND ObjectDescription = 'Portfolio Group Description'
UPDATE AOOBJECT SET NAME = 'mno_GRP' WHERE NAME = 'mno' AND ObjectDescription = 'Portfolio Group Description'
UPDATE AOOBJECT SET NAME = 'prq_GRP' WHERE NAME = 'prq' AND ObjectDescription = 'Portfolio Group Description'
答案 0 :(得分:7)
您需要CASE
和字符串函数RIGHT
,LEFT
和LEN
UPDATE AOOBJECT
SET NAME = CASE
WHEN RIGHT(NAME , 2) = '_2' THEN LEFT(NAME , LEN(NAME) - 2)
ELSE NAME
END + '_GRP'
WHERE ObjectDescription = 'Portfolio Group Description'
答案 1 :(得分:0)
你当然可以在一个声明中做到这一点:
update adoobject
set name=case when name='abc_2' then 'abc_GRP' when name='def' then 'def_GRP' when name='ghi' then 'ghi_GRP' end
where name in ('abc_2', 'def', 'ghi') -- etc
and objectdescription='Portfolio Group Description'
它很可能也会快得多,因为服务器不必在计划之后每次重新计算计划 - 尽管我怀疑你会注意到你只有6项要改变。