Python从sql查询结果创建数据帧

2024-09-28 17:00:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个sql查询,其中包含多个临时表创建和一个最终select语句

让我们想象一下查询示例:

select 
        t1.Variable11,
        t1.Variable12,
        t2.Variable13
    into #R1
    from t1
    join t2
    on t1.Key1= t2.key1 and t1.Key2= t2.key2
    where t1.Variable1 > 100

select 
        t3.Variable21,
        t3.Variable22,
        t4.Variable23
    into #R2
    from t3
    join t4
    on t3.Key1= t4.key1 and t3.Key2= t4.key2
    where t3.Variable1 > 200


select 
        #R1.*,
        #R2.*
    from #R1
    join #R2
    on #R1.Variable11= #R2.Variable21

我使用pyodbc连接器连接到sql server:

connection = pyodbc.connect(driver='{SQL Server Native Client 11.0}', server=server_name,
                            database=db_name, trusted_connection='yes', MARS_Connection='yes')

我不想重新编写代码。 我只想写一个返回数据帧的函数。 当我尝试使用pandas.read_sql()函数时,收到错误:

TypeError: 'NoneType' object is not iterable

当我尝试使用pyodbs.execute()时,收到错误:

No results. Previous SQL was not a query.

如何处理包含多个临时表创建和最后一个select语句的sql脚本


Tags: fromsqlserveron语句selectt1t3