David Louda
David Louda

Reputation: 577

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?

Upvotes: 0

Views: 2080

Answers (2)

Why didnt you concatenate it, you can re-write to something like this, check below

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

refer to this: https://docs.djangoproject.com/en/4.1/topics/db/sql/

Upvotes: 0

pts
pts

Reputation: 87381

Add a space after each ".

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

Upvotes: 2

Related Questions