【问题标题】:Update or insert data from a table to another while the column name retrieved from other table当从另一个表中检索到列名时,将数据从一个表更新或插入到另一个表
【发布时间】:2021-05-11 04:11:36
【问题描述】:

我要实现的内容如下:具有 my_index(主键)、updated_time、my_col_1、my_col_2 列的表目标,数据应如下所示,每当一个值进入表源时,表目标中的相应行应该被更新,并且 updated_time 也是如此。这些列将只是表 def 的子集。所以我认为一旦从调用者那里收到列,就需要创建表目标。

target:

my_index | updated_time            | ABC | DEF | GHI
---------+-------------------------+-----+-----+------
12       | 2021-05-11 01:01:01.000 | 1.0 | 2.0 | 3.0

source 具有列id(自动增量主键)、my_index、my_id、my_value,数据应如下所示:

id | my_index | my_id | my_value
---+----------+-------+---------
1  | 12       | 3     | 1.0
2  | 12       | 4     | 2.0
3  | 12       | 5     | 3.0
4  | 11       | 6     | 4.0

虽然表目标中的列来自另一个表 def,列 my_id(主键)、my_col,但数据应如下所示:

my_id | my_col
------+--------
3     | ABC
4     | DEF
5     | GHI
6     | JKL

我不确定如何实现 SQL 命令以从表源获取数据,然后更新或插入表目标。

有人可以帮忙吗?欣赏它。

【问题讨论】:

  • 如果您真的不知道从哪里开始,那么 SO 不是寻求帮助的正确位置。您确实需要某种教程网站。 SO 是针对所面临的特定技术问题。
  • 您必须将source 表与another 表连接起来,然后将abcdefghi 行转为列,然后插入表target .您可以编写一个透视所有列的单个查询(视图),但要执行插入,您需要每个目标表或动态 sql 的查询。用前端语言完成大部分操作可能会更容易,但如果您只使用 SQLS,如果您有多个目标表,则可能在存储过程中完成整个操作
  • @CaiusJard,感谢您的帮助。我正在考虑创建一个触发器,以便每当将任何数据插入表源时,都应该更新表目标。我不确定这是否正确。
  • 这个target 表的目的是什么?是为了审计追踪吗?
  • 同意松鼠的观点;你所做的只是反过来存储相同的数据,这可能有点毫无意义。也许决定哪种方式最适合您的 99% 用例,然后每次从查询您的 1% 时反过来生成它

标签: sql sql-server tsql


【解决方案1】:

这实际上不是一个很好的数据模型 - 将列名存储在一个表中以便在另一个表中进行更新是很棘手的。 SQL 不能很好地处理变量列名。

您可以做任何您想做的事,但您必须明确列出列。这个想法是汇总源表以获取每个潜在列的值。然后,当源列中有值时,设置目标列中的值:

update t
    set abc = (case when s.abc is not null then s.abc else t.abc end),
        def = (case when s.def is not null then s.def else t.def end),
        ghi = (case when s.ghi is not null then s.ghi else t.ghi end)        
    from target t join
         (select s.my_index,
                 max(case when d.my_col = 'ABC' then s.my_value end) as abc,
                 max(case when d.my_col = 'DEF' then s.my_value end) as def,
                 max(case when d.my_col = 'GHI' then s.my_value end) as ghi
          from source s join
               def d
               on s.my_id = d.my_id
          group by s.my_index
         ) s
         on s.my_index = t.my_index

【讨论】:

  • 感谢您的帮助。由于交付压力大,我选择通过c#实现逻辑,但是我相信性能可能比直接使用sql差。完成 c# impl 后,我会尽快回来尝试您的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
相关资源
最近更新 更多