sql - 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 脚本,使用变量执行这个查询。
解决方案
在这里,您可以在 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');
推荐阅读
- node.js - 在 Google Cloud Function 中延迟执行多个 HTTP 请求
- php - 不在不同服务器上渲染块(ACF + Gutenberg + Timber)
- c++ - #define 在这个实例中的作用是什么?
- postgresql - 输出中的 postgreSQL 增量号
- html - 组件内部的路由
- php - JSON PHP 检索此数据的正确 foreach 循环是什么
- c# - 在单元测试中使用 InlineData 的困难 - 参数是控制器
- node.js - 获取错误所需的参数 opts.to 丢失
- javascript - 如何使用 document.getElementsByClassName 添加 html
- python - GraphicsView 的 MousePressEvent 不起作用