簡體   English   中英

動態循環 SQL 列

[英]Loop through SQL columns Dynamically

我正在嘗試從給定列列表的副本 table2 更新 table1。

在給定列名列表的情況下,如何編寫 sql 命令從 table2 動態更新 table1 中的所有列?

我試圖避免在 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""")

您可以嘗試此選項:

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)

示例 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