在Python中的另一个SQL查询中使用一个SQL查询的输出

时间:2018-07-24 13:00:31

标签: python sql-server jupyter-notebook

我正在使用Python上的SQL数据库。建立连接后,我想在另一个查询中使用一个查询的输出。

示例:query1为我提供了模式中所有表的列表。我想在查询2中使用查询1中的每个表名。

$z = range(0,20000);

$start = time();
$values = array_values($z);
$count = count($values);
for ($i = 0; $i < $count - 1; $i++) {
    for ($j = $i + 1; $j < $count; $j++) {
    }
}

$end = time();                  
$elapsedTimeA = $end - $start;

// Case A, elapsed time in seconds: 17
echo 'Case A, elapsed time in seconds: ' . $elapsedTimeA;


$start = time();
$x = array_values($z);
foreach($x as $key1 => $item){
  foreach($x as $key2 => $item2){

    if($key2 <= $key1){
        continue;
    }

    if($item == $item2){
        continue;
    }
  }
}
$end = time();                   
$elapsedTimeB = $end - $start;

// Case B, elapsed time in seconds: 103
echo 'Case B, elapsed time in seconds: ' . $elapsedTimeB; 

我想对query1输出中的每个表使用此查询。 有人可以为我提供Python代码吗?

1 个答案:

答案 0 :(得分:0)

这是一个有关如何做您想做的事的有效示例。我没有查找表列表的方案,但是您可以简单地用SQL代码代替。我只是通过合并2个表的语句来“伪造”它。关于该SQL代码,还有很多其他答案,但我不想使这个答案混乱: How do I get list of all tables in a database using TSQL?

您似乎可能缺少的关键部分是构建第二条SQL语句的join步骤。这应该足以作为您精确寻找所需内容的起点。

import pypyodbc

def main():
    table_list = get_table_list()
    for table in table_list:
        print_table(table)

def print_table(table):
    thesql = " ".join(["SELECT TOP 10 businessentityid FROM", table])
    connection = get_connection()
    cursor = connection.cursor()
    cursor.execute(thesql)
    for row in cursor:
        print (row["businessentityid"])
    cursor.close()
    connection.close()

def get_table_list():
    table_list = []
    thesql = ("""
    SELECT 'Sales.SalesPerson' AS thetable
    UNION
    SELECT 'Person.BusinessEntity' thetable
    """)
    connection = get_connection()
    cursor = connection.cursor()
    cursor.execute(thesql)
    for row in cursor:
        table_list.append(row["thetable"])
    cursor.close()
    connection.close()
    return table_list


def get_connection():
    '''setup connection depending on which db we are going to write to in which environment'''
    connection = pypyodbc.connect(
        "Driver={SQL Server};"
        "Server=YOURSERVER;"
        "Database=AdventureWorks2014;"
        "Trusted_Connection=yes"
        )
    return connection

main ()