0

I want to ask that if I can update the parameter in SQL query using python. I want to read a SQL query first, and process the SQL outputted data using python. However, I need to specify the data that I want to filter in SQL query, and I wonder if there is any way that I can update the parameter in python instead of updating the SQL query.

The SQL query is like the following:

set nocount on;

declare @pdate datetime
set @pdate = '2022-12-31'

select
  cast(L.Date as datetime) as Date
, Amount
, AccountNumber
, Property
, County
, ZipCode
, Price
, Owner

from Account.Detail L

inner join Owner.Detail M
    on L.Date = M.Date
    and L.Number = M.Number

inner join Purchase.Detail P
    on L.Date = P.Date
    and L.Purchase.Number = P.Purchase.Number

where L.Date = @pdate
    and Purchase.Number not in ('CL1', 'CL2')
    and Amount > 0

And I want to run the python code like following:

import pyodbc

server = 'my_server_name'
database = 'my_database_name'

connection = pyodbc.connect(Trusted_Connection = "yes", DRIVER = "{SQL Server}", SERVER = server, DATABASE = database)
cursor = connection.cursor()
query = open('Pathway_for_SQL_Query.sql').read()
data = pd.read_sql(query, connection)
connection.close()

I need to declare the @pdate in SQL query every time, I want to ask if I can update the @pdate using Python?

1

1 Answer 1

2

Instead of parsing and replacing an SQL script, you could use bind variables and have Python control the value (note the "?" in the query):

pdate = "some value"

# query could be read from file, given here for simplicity
query = """
select
  cast(L.Date as datetime) as Date
, Amount
, AccountNumber
, Property
, County
, ZipCode
, Price
, Owner

from Account.Detail L

inner join Owner.Detail M
    on L.Date = M.Date
    and L.Number = M.Number

inner join Purchase.Detail P
    on L.Date = P.Date
    and L.Purchase.Number = P.Purchase.Number

where L.Date = ?
    and Purchase.Number not in ('CL1', 'CL2')
    and Amount > 0
"""

data = pd.read_sql(query, connection, params=(pdate,))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your help. I didn't realize that we can directly pass parameters in read_sql function

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.