如何使用pymssql对先前查询的结果运行查询?
这是我尝试过的:
from os import getenv
import pymssql
import pandas as pd
import arcpy
import csv
from decimal import Decimal
from functools import partial
import time
from datetime import datetime
####### connect to DB #######
conServer = r"myserver\myserver"
condb = "some database"
conn = pymssql.connect(server=conServer, database=condb)
cursor = conn.cursor()
##### query 1 #####
query1 = "DECLARE
SOMETHING
SELECT
SOME FIELDS
FROM
dbo.SOMETABLE
WHERE
SOME CONDITIONS"
resQuery1 = cursor.execute(query1)
##### query 2 #####
query2 = """DECLARE @something TINYINT = 1
;WITH VARIABLE1 AS (
SELECT
SOME FIELDS
FROM
SOME TABLES WITH A BUNCH OF JOINS
WHERE
SOME CONDITIONS
GROUP BY
FIELD2
), FIELD3 AS (
SELECT
THIS,
Sum(THAT) as SUMTHAT
FROM %s
GROUP BY
FIELD2
)
SELECT
REST OF THE QUERY"""
cursor.execute(query2, (resQuery1))
试图通过%s无效。
我还尝试使用arcpy将查询结果保存在in_memory表中,因为最终必须使用以下代码在ArcGIS Server中运行该查询:
########## in memory table
gis_temp_loc_loss_adj = "temp_loc_loss_adj" + datestamp
query1Table = arcpy.CreateTable_management(r"in_memory", gis_temp_loc_loss_adj)
columnNames = tuple(map(str, [i[0] for i in cursor.description]))
addfield = partial(
arcpy.AddField_management,
query1Table
)
for field in columnNames:
addfield(field)
with arcpy.da.InsertCursor(query1Table, columnNames) as insCur:
for row in cursor:
insCur.insertRow(row)
但是我找不到一种方法来读取in_memory表的名称并将其包含在SQL查询中。
在cursor.execute中我做错了什么,因为它没有接听%s? 另外,如何将query1的结果保存在内存中并在query2中使用呢?
为澄清起见,我无法在sql服务器上进行写操作,因此无法在SQL DB中创建临时表