pythondjangodjango-databasedjango-mssql

How to execute raw sql statement for SQL server from django?


Original db query that works:

SELECT *
FROM [db_name].[dbo].[table]
WHERE name IN (
SELECT name
FROM [db_name].[dbo].[table]
WHERE active = 1
Group by name
Having count(*) > 1
)
order by name

and when I try to execute it from django as

from django.db import connection

def fetch_matching_pn_products():
    with connection.cursor() as cursor:
        cursor.execute("SELECT *"
                        "FROM db_name.dbo.table"
                        "WHERE name IN ("
                        "SELECT name"
                        "FROM db_name.dbo.table"
                        "WHERE active = 1"
                        "Group by name"
                        "Having count(*) > 1"
                        ")"
                        "order by name")
        data = cursor.fetchall()
    return data

returns this error

django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'IN'. (156) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '.'. (102)")

I have also tried changing db_name.dbo.table in django to [db_name].[dbo].[table] and table with no success. What needs to be changed so the raw query executes correctly?


Solution

  • Add a space after each ".

    Without a space the string contains SELECT nameFROM etc., which is incorrect, because FROM should be a separate word.