Home > Net >  SQL SELECT WHERE Col value is = string
SQL SELECT WHERE Col value is = string

Time:10-07

I currently have the following T-SQL statement in my python code:

otherExpense ='SELECT Master_Sub_Account, Debit, Credit FROM [dbo].[PostGL] as gl'\
         'INNER JOIN Accounts  '\
         'ON Accounts.AccountLink = genLedger.AccountLink '\
         'INNER JOIN _etblGLAccountTypes as AccountTypes '\
         'ON Accounts.iAccountType = AccountTypes.idGLAccountType '\
         'WHERE cAccountTypeDescription IS Other Expenses '\
         'AND genLedger.TxDate >  ? '\

    cursor = cnxn.cursor();
    cursor.execute(otherExpense ,[one_yrs_ago]);
    xAllOtherExpense = cursor.fetchall()
    cursor.close()
    otherExpenseX = []

    for row in xAllOtherExpense:
        rdict = {}
        rdict["Account"] = row[0]
        rdict["Debit"] = row[1]
        rdict["Credit"] = row[2]
        otherExpenseX.append(rdict)

I have tried this code and I get an error

Incorrect syntax near 'Other'

I have also tried to give the "Other Expenses" value as a parameter, like so:

 'WHERE cAccountTypeDescription = ? '\

 cursor.execute(otherExpense ,['Other Expenses'] , [one_yrs_ago]);

And that is not working, I have also tried a normal equal sign, like so:

 'WHERE cAccountTypeDescription = Other Expenses '\

 cursor.execute(otherExpense  , [one_yrs_ago]);

I don't know why none of these work, is there a specific way to call string values in SQL statements?

CodePudding user response:

String constants always have to be quoted, with single quotes. That means you should use double quotes for your Python string:

"WHERE cAccountTypeDescription = 'Other Expenses' "

The parameterized one should have been like this; the parameters are passed in a single list:

cursor.execute( otherExpense, ['Other Expenses', one_yrs_ago] )
  • Related