Search code examples
pythonsql-serverpymssql

How can I get the query result which includes IF ELSE when using pymssql on SQL Server?


I am using pymssql in python application to connect to SQL Server database. I have a query statement defined as below:

DECLARE @type int
SELECT @type = type FROM myTable WHERE id = 1000

IF @type >= 700
    SELECT 1
ELSE
    SELECT 0

when I run the above sql in SQL Server, I can get output either 1 or 0 which depends on the type value of the row. But when I run the code in python it always returns None:

cursor.execute(sql)  # sql is the above select statement
cursor.fetchone()  # this line return None

What I am expecting is to get the value 1 or 0, how can I achieve it in pymssql?


Solution

  • Update your code to this. type is a reserved keyword in sql server. Added TOP 1 to make sure we will only get 1 result for [type].

    DECLARE @type int
    SET @type = 0
    SELECT TOP 1 @type = [type] FROM myTable WHERE id = 1000
    
    IF @type >= 700
        SELECT 1
    ELSE
        SELECT 0