How to save output of SQL Server stored procedure with multiple result sets into each dataframe in pandas

若如初见. 提交于 2019-12-12 19:13:06

问题


I have a SQL Server stored procedure that returns 3 separate tables.

How can I store each of this table in different data-frame using pandas?

Something like:

  • df1 - first table
  • df2 - second table
  • df3 - third table

Where should I start looking at?

Thank you

import pandas as pd 
import pyodbc 
from datetime import datetime


param = datetime(year=2019,month=7,day=31)
query = """EXECUTE [dbo].PythonTest_USIC_TreatyYear_ReportingPackage  @AsOFDate = '{0}'""".format(param)
conn = pyodbc.connect('DRIVER={SQL Server};server=myserver;DATABASE=mydatabase;Trusted_Connection=yes;')
df = pd.read_sql_query(query, conn)
print(df.head())

回答1:


You should be able to just iterate through the result sets, convert them to DataFrames, and append those DataFrames to a list. For example, given the stored procedure

CREATE PROCEDURE dbo.MultiResultSP 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT 1 AS [UserID], N'Gord' AS [UserName]
    UNION ALL
    SELECT 2 AS [UserID], N'Elaine' AS [UserName];

    SELECT N'pi' AS [Constant], 3.14 AS [Value]
    UNION ALL
    SELECT N'sqrt_2' AS [Constant], 1.41 AS [Value]
END

the Python code would look something like this:

data_frames = []
crsr = cnxn.cursor()
crsr.execute("EXEC dbo.MultiResultSP")
result = crsr.fetchall()
while result:
    col_names = [x[0] for x in crsr.description]
    data = [tuple(x) for x in result]  # convert pyodbc.Row objects to tuples
    data_frames.append(pd.DataFrame(data, columns=col_names))
    if crsr.nextset():
        result = crsr.fetchall()
    else:
        result = None

# check results
for df in data_frames:
    print(df)
    print()
""" console output:

   UserID UserName
0       1     Gord
1       2   Elaine

  Constant Value
0       pi  3.14
1   sqrt_2  1.41

"""


来源:https://stackoverflow.com/questions/58107697/how-to-save-output-of-sql-server-stored-procedure-with-multiple-result-sets-into

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!