用多行字符串执行查询

时间:2019-02-19 10:19:50

标签: python django django-pyodbc

我尝试直接访问数据库并在网页上呈现数据。 Evereything仅适用于一行SQL查询,但适用于多行查询。我的SQL查询包含许多联接并使用临时表!我尝试过

def merchant_ajax(request):
    data = dict()
    with connections['mssql'].cursor() as cursor:
        query_head = ' '.join((
            "DECLARE @Date_From datetime, @Date_To datetime",
            "SET @Date_From = DATEADD(mm, DATEDIFF(mm,0,GETDATE())-1, 0)",
            "SET @Date_To = dbo.dayEnd(GETDATE())",
            "SELECT mt.MarketTourID, sku.SKUPlanID AS SKUPlanID, IIF(InventoryStatus=1,1,0) AS InventoryStatus,mt.CreationDate",
            "INTO #MT FROM MTMerchandasingREF AS mt",
            "JOIN SKUMainREF AS sku ON sku.ID = SKUMainId",
            "WHERE mt.CreationDate BETWEEN @Date_From AND @Date_To",
            "SELECT mt.MarketTourID,skuP.Name AS PlanName,mt.InventoryStatus,mt.CreationDate",
            "FROM #MT AS mt",
            "JOIN SKUPlanREF AS skuP ON skuP.ID = mt.SKUPlanID",
            "WHERE skuP.MerchGroupID IS NOT NULL",                

        ))        
        cursor.execute(query_head)
        data['data'] = cursor.fetchall()
    return JsonResponse(data,safe=False)

我的查询在SQl Operations Studio上正常工作,但在Django上却无法实现。

我收到错误django.db.utils.ProgrammingError: No results. Previous SQL was not a query.

1 个答案:

答案 0 :(得分:0)

您的问题是pyodbc一次只能执行一个查询。您需要执行以下操作:

from django.db import connections

with connections['mssql'].cursor() as cursor:
    query = """
        DECLARE @Date_From datetime, @Date_To datetime;

        SET @Date_From = DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0);

        SET @Date_To = GETDATE();

        SELECT @Date_From AS date_from, @Date_To AS date_to
    """

    cursor.execute(query)
    result = cursor.fetchall()

    date_from = result[0][0]
    date_to = result[0][1]

    query = """
        SELECT %s AS date_from, %s AS date_to
        INTO #temptable
    """
    cursor.execute(query, (date_from, date_to))

    query = """
        SELECT * FROM #temptable
    """

    cursor.execute(query)
    result = cursor.fetchall()

但是,在这种情况下,创建存储过程并从Django调用存储过程可能会更容易。

过去,我已经重构了这样的流程,以使用Django ORM和Python而不是依赖T-SQL,这使我的生活变得更加轻松;学习只需要一点时间。祝你好运!