I'm looking to export the result set of a SQL query into a CSV by using Python, the code below works for a small query but when trying on a larger query (sample below) it gives the following error:
TypeError: 'NoneType' object is not iterable
SQL Query - Example code (Very close to actual code but with sensitive info removed):
DECLARE @Chosen_Month DATE
SET @Chosen_Month = '2021-01-01';
IF OBJECT_ID('tempdb..#Base_Data') IS NOT NULL
DROP TABLE #Base_Data;
SELECT
a.region
,a.customer_name
,SUM(b.transactions) AS transactions
,SUM(b.turnover) AS turnover
,SUM(b.revenue) AS revenue
INTO
#Base_Data
FROM
customer_table AS a
INNER JOIN transaction_table AS b ON a.company_id = b.company_id
WHERE
b.trans_date = @Chosen_Month
GROUP BY
a.region
,a.customer_name
IF OBJECT_ID('tempdb..#Ranked_Data') IS NOT NULL
DROP TABLE #Ranked_Data;
SELECT
*
,ROW_NUMBER() OVER(ORDER BY transactions DESC) AS trans_rank
,ROW_NUMBER() OVER(ORDER BY turnover DESC) AS turnover_rank
,ROW_NUMBER() OVER(ORDER BY revenue DESC) AS revenue_rank
FROM
#Base_Data
SELECT
*
FROM
#Ranked_Data
WHERE
revenue_rank <= 50
ORDER BY
revenue_rank ASC
I tried looking around to maybe split the SQL query into multiple executes and avoid running these null outputs but couldn't get to a working stage. How can I account for large queries that have objects like scalar variables running throughout as well? I'm fairly new to Python and would appreciate any help on this! Python code below:
import pyodbc
import csv
new_file_path = r'S:\Andy\Python\testdump.csv'
query_path = r'S:\Andy\Python\testquery.sql'
def read(conn):
cursor = conn.cursor()
with open(query_path, 'r') as sql_query_file:
raw_data = cursor.execute(sql_query_file.read())
with open(new_file_path, 'w', newline='') as csv_file:
csv_out = csv.writer(csv_file)
csv_out.writerow([i[0] for i in raw_data.description])
for row in raw_data:
csv_out.writerow(row)
print("Finished export")
conn = pyodbc.connect(
"Driver={Driver_name_here};"
"Server=server_name_here;"
"Database=database_name_here;"
"Trusted_Connection=yes;"
)
read(conn)
conn.close()
cursor.executeisn't returning any results for at least one of those statements (which is why theforloop fails). Can you provide a minimal reproducible example?cursor.executedoes not return anything: Return values are not defined. So it is not iterable. But in pyodbc doc it is described as it returns the same cursor itself, so it may be confusing. You needfetchmanycalls to get the data in chunks and write that chuncks into file.