首页 > 解决方案 > SQL - 将 where 子句作为变量传递(Redshift)

问题描述

我有一个我使用的 SQL 查询,它只有 where 子句更改。我想将 SQL 查询存储为一个变量,并将每个 where 子句存储为单独的变量。

下面给出的是我正在使用的 SQL 查询:

查询一:

select a.prod_name,a.prod_cat,b.sale_date 
from products a 
   join sales b on a.id = b.sale_id and b.type=new

查询 2:

select a.prod_name,a.prod_cat,b.sale_date 
from products a 
  join sales b on a.id = b.sale_id and b.type=modify

我计划编写一个 Python 脚本,使用变量执行这个查询。

标签: sqlamazon-redshiftdynamic-sql

解决方案


在这里,您可以在 Python 的情况下传递变量。如果您很简单想使用python,但是如果您的情况如此简单,为什么还要引入python,简单的shell script应该适合您。无论如何,

import psycopg2


def redshift(type_var):


    conn = psycopg2.connect(dbname='*********', host='*********.redshift.amazonaws.com', port='5439', user='****', password='*******8')
    cur = conn.cursor();

    cur.execute("begin;")

    sql ="select a.prod_name,a.prod_cat,b.sale_date from products a   join sales b on a.id = b.sale_id and b.type='%s'" %(type_var)
    cur.execute(sql)
    results = cur.fetchall()
    print("Copy executed fine!"+results)




"""Call one with new"""
redshift('new');
"""Call two with modify"""
redshift('modify');

推荐阅读