简体   繁体   中英

Passing Table Name as Parameter in User Defined Functions

I want to create a UDF that contains parameterized query. Since I want to reuse this function, I also want to parameterize the table name. Is this possible in Snowflake Data Warehouse(or Oracle since it's bit similar in terms of syntax)?

I don't think this can be done using only SQL. Any input on how it can be achieved using Python?

You can't use a table name as a bind variable in Oracle. The query is parsed at compile time, not run time. You have to use EXECUTE IMMEDIATE or dbms_sql .

This is a really basic programming question, and not really related to Snowflake. So you should have investigated more before asking here. But here's a sketch of an answer for you:

#!/usr/bin/env python

# Connect to Snowflake
# See https://docs.snowflake.net/manuals/user-guide/python-connector-example.html#connecting-
...
con = 
...

# Scan the file to build the table/column info
tables = {}
with open("zz.csv") as f:
    for l in f.readlines():
        tname, cname = l.split(",")
        tables.setdefault(tname.strip(), []).append(cname.strip())

# Run a query for each query
for tname, clist in tables.iteritems():
    query = """select {columns} from {table} 
               group by {columns} 
               having count(*) > 1
            """.format(columns=",".join(clist), table=tname)
    print("Running query: {0}".format(query))
    cur = con.cursor()
    cur.execute(query)
    for rec in cur:
        print("DUPLICATED RECORD: {0}".format(rec))

@MarcinZukowski Thanks for info. Yes I checked it and they are planning to launch it in June. I just have query to validate PK constraint in the UDF which doesn't need to be in UDF. My CSV looks like this which has table name and its primary keys:

|  Table Name  |  Primary Key  | 
|    Table 1   |     Col1      |  
|    Table 1   |     Col2      |
|    Table 1   |     Col3      | 
|    Table 2   |     Col11     | 
|    Table 2   |     Col12     |

I want to execute below query for every table from this CSV. Here table name can be single argument but column names will have to be varying since tables can 1 or more primary keys.

select Col1, Col2, Col3 from Table1
group by Col1, Col2, Col3
having count(*)>1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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