1

I'm attempting to call a user defined function (table function) using SQLAlchemy. Here is my code:

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker

db = create_engine('mssql+pymssql://User:Password@Server/Database')

metadata = MetaData(db)
Session = sessionmaker(bind=db)
session = Session()

results = session.query(func.MyFunctionName('Value')).all()

When this executes I get the following error:

sqlalchemy.exc.OperationalError: (OperationalError) (195, "'MyFunctionName' is not a recognized built-in function name.DB-Lib error message 195, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n") 'SELECT MyFunctionName(%(MyFunctionName_2)s) AS [MyFunctionName_1]' {'MyFunctionName_2': 'Value'}

When I look at SQL Profiler, I get the following:

SELECT MyFunctionName('Value') AS [MyFunctionName_1]

Which tells me that it is not adding the SELECT * FROM MyFunctionName in the query.

What do I need to do to get my session.query to add the * FROM in the query for execution?

If you need more information, please leave a comment.

1 Answer 1

2

a table based function you need to turn into a select() object first, using the pattern described at http://docs.sqlalchemy.org/en/latest/core/tutorial.html#functions

myfunc = select([column('x'), column('y')]).select_from(func.myfunction())
session.execute(myfunc).fetchall()
Sign up to request clarification or add additional context in comments.

3 Comments

This worked with tweaking. I had to change session.query to session.execute(myfunc).fetchall(). I edited your response with the updated code.
passing the select() to query() should work as well, it will wrap it in an extra SELECT but you'll still get the same result. what was your output/version of SQLAlchemy ?
It appears I need an alias for my wrapped sub select. So "select column from (select column from myfunc()) as A

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.