使用多行字符串执行查询

Execute query with multiline string

我尝试直接访问数据库并在我的网页上呈现数据。 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.

你的问题是 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,这让我的生活变得更加轻松;只需要一点时间来学习。祝你好运!