2013-07-11 42 views
1

我尝试使用SQLAlchemy的调用用户定义函数(表函数)。这里是我的代码:SQLAlchemy的用户定义函数的错误

from sqlalchemy import * 
from sqlalchemy.orm import sessionmaker 

db = create_engine('mssql+pymssql://User:[email protected]/Database') 

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

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

当这个执行我收到以下错误:

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'}

当我看到SQL事件探查器,我得到如下:

SELECT MyFunctionName('Value') AS [MyFunctionName_1]

还告诉我,它不是在查询中添加SELECT * FROM MyFunctionName

什么我需要做的就是我的session.query在查询执行添加* FROM?

如果您需要了解更多信息,请发表评论。

回答

2

需要变成一个select()对象首先,使用所描述的图案在http://docs.sqlalchemy.org/en/latest/core/tutorial.html#functions

myfunc = select([column('x'), column('y')]).select_from(func.myfunction()) 
session.execute(myfunc).fetchall() 
+0

这曾与的调整基于表的功能。我不得不将session.query更改为session.execute(myfunc).fetchall()。我使用更新后的代码编辑了您的回复。 – CodeLikeBeaker

+0

通过选择()查询()应该工作为好,它会包装在一个额外的选择,但你仍然会得到相同的结果。你的SQLAlchemy的输出/版本是什么? – zzzeek

+0

它看起来我需要一个别名为我包裹的子选择。所以“从myfunc()中选择列作为A – CodeLikeBeaker