0

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?

2 Answers 2

2

Add a space after each ".

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.