简体   繁体   English

动态循环 SQL 列

[英]Loop through SQL columns Dynamically

I'm trying to update table1 from a copy, table2 given a list of columns.我正在尝试从给定列列表的副本 table2 更新 table1。

How do I write a sql command to dynamically update all columns in table1 from table2 given a list of column names?.在给定列名列表的情况下,如何编写 sql 命令从 table2 动态更新 table1 中的所有列?

I'm trying to avoid hardcoding column1, column2 in the sql query.我试图避免在 sql 查询中对 column1、column2 进行硬编码。

column_names = ['column1', 'column2'] 
# Want to make query below work automatically
# if I add another column name to `column_names`
sql_cmd = ("""
        UPDATE table1
        SET 
        table1.column1 = table2.column1,
        table1.column2 = table2.column2
        FROM table2
        WHERE table1.id = table2.id""")

You can try this option:您可以尝试此选项:

column_names = ['column1', 'column2']

sql_cmd = (""" UPDATE table1 SET table1.{} = table2.{}, 
                                 table1.{} = table2.{}
                FROM table2 WHERE table1.id = table2.id""").format(column_names[0], column_names[0], column_names[1], column_names[1])

print(sql_cmd)

Sample Jinja2 Code using Macro:示例 Jinja2 使用宏的代码:

{% macro macro_join_condition(tab_prefix_1, tab_prefix_2, columns) %}
  {% for col in columns %}
    {% if loop.first %}
      {{ tab_prefix_1 }}{{ col }} = {{ tab_prefix_2 }}{{ col }}
    {% else %}
      and {{ tab_prefix_1 }}{{ col }} = {{ tab_prefix_2 }}{{ col }}
    {% endif %}
  {% endfor %}
{% endmacro %}

select *
from source_data sd right join target_data td on {{ macro_join_condition('td.','sd.', params.primaryKeyList) }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM