首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果值为true,则更新某些列,如果不更新,则更新其他列。

如果值为true,则更新某些列,如果不更新,则更新其他列。
EN

Stack Overflow用户
提问于 2018-01-22 19:33:36
回答 1查看 46关注 0票数 1

我会尽力解释我的“问题”

我有两张桌子

代码语言:javascript
运行
复制
Table1
id      parent_id     name                  active
2008    10          name0                      Y
200801  2008        child of name0             Y
200802  2008        child of name0             Y
201102  10434344    child of name0             Y

Table2
old_id  new_id     name                active     id_father_new
2008    10         name0                  N           0
200801  202101    child of name0          N          2021
200802  202102    child of name0          N          2021
2011    10        new name0               Y           0
201101  201101    child of new name0      Y          2011
201102  10434344  child of name0          Y          2011
201102  201103  child of new name0        Y          2011

如何看,第一个表有一些id、id_parent和active字段。另一个在table1中有相同的列、新的信息和新的记录。

table2中的所有新记录都用左联接插入到table1中,现在我需要用table2中的信息在table1中进行更新,但只有当table2中的 active 字段为Y更新id、id_parent和active字段时,如果table2中的活动字段为N,则只需在table1中更新活动字段

所以,table1应该是这样的:

代码语言:javascript
运行
复制
Table1
    id        parent_id     name             active
    2008         10         name0                 N
    200801      2008        child of name0        N
    200802      2008        child of name0        N
    201102      2011        child of name0        Y
    10434344    2011        child of name0        Y
    2011        10          new name0             Y           
    201101      2011        child of new name0    Y
    201103      2011        child of new name0    Y          

在前三个记录中,只将活动字段更改为N,因为在table2中它们是active =N

如果我这么做:

代码语言:javascript
运行
复制
update u
        set u.id = s.new_id,
            u.parent_id = s.new_father_id,
            u.active = s.active
        from table1 u
        inner join table2 s on u.new_id = s.old_id
        where s.active like 'Y'

显然,只有使用active = Y更新行,并且保留三个第一列,它们的值相同,因此它必须对字段active进行另一次更新:

代码语言:javascript
运行
复制
update u
        set u.active = s.active
        from table1 u
        inner join table2 s on u.new_id = s.old_id

最大的问题是,是否有可能只使用一个更新?成批的案例陈述?或者只有两个在sql良好实践中可以接受的更新。

耽误您时间,实在对不起

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-22 19:37:38

您可以使用IIF案例语句,如果条件不是true,则重新分配旧值。

代码语言:javascript
运行
复制
update u
set u.id = IIF(s.active like 'Y', s.new_id, u.id),
    u.parent_id = IIF(s.active like 'Y', s.new_father_id, u.parent_id),
    u.active = s.active
from table1 u
inner join table2 s on u.new_id = s.old_id
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48388990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档