【问题标题】:cannot find column or the user-defined function or aggregate, or the name is ambigous找不到列或用户定义的函数或聚合,或者名称不明确
【发布时间】:2018-03-02 18:49:34
【问题描述】:

我在尝试 INNER JOIN 2 个表时遇到此错误。

“找不到列“TE”或用户定义的函数或聚合“TE.UserID”,或者名称不明确”

有什么想法吗?

我尝试将表名添加到 Select 语句中,如下所示。这实际上是在 SQL Server 中运行查询。但它对 Python ODBC 没有任何作用。

"Select TP.UserID, Phone "

但这无济于事。

userid = 'dd88'

try:
    connection = pypyodbc.connect('Driver={SQL Server};Server=MyServerName;Database=MyDatabaseName;Trusted_Connection=yes;')
except pypyodbc.Error as ex:
    sqlstate = ex.args[0]
    if sqlstate == '28000':
        print("You do not have access.") 
cursor = connection.cursor() 
SQLCommand = ("SELECT UserID, Phone "
    "FROM dbo.SEC_UserProfile as TP INNER JOIN dbo.SEC_User as TE "
    "ON TP.UserID = TE.UserID "
    "(nolock)"
    "WHERE UserID LIKE ?")
Values = ['%' + userid + '%']
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
if results:
    print(connections + " " + str(results[0]) + " " + str(results[1])) # enters results in entry
    connection.close()
else:
    print(connections + " - NO")
    connection.close()

UserID 在两个表中。

【问题讨论】:

  • 尝试在任何地方添加表名......例如,在 where 子句中也是如此。
  • 我仍然遇到同样的错误。
  • 请小心使用NOLOCK。它有很多大多数人不知道的有趣的东西。 blogs.sentryone.com/aaronbertrand/bad-habits-nolock-everywhere 如果您坚持使用至少使用正确的语法。在查询提示中不推荐使用 WITH 关键字。

标签: python sql sql-server pyodbc


【解决方案1】:

一个问题是你在错误的地方有(nolock)。它应该紧跟一个表别名,而不是连接条件:

在构建此 SQLCommand 字符串时,您是否还不需要添加连接运算符?我从未使用过 Python,但如果这是 .net 代码,它甚至都无法编译。

SQLCommand = ("SELECT TP.UserID, Phone " +
    "FROM dbo.SEC_UserProfile as TP (nolock) INNER JOIN dbo.SEC_User as TE (nolock)" +
    "ON TP.UserID = TE.UserID " +
    "WHERE TP.UserID LIKE ?")

【讨论】:

  • 我确实必须在 SELECT 语句中添加 TP.UserID,但调整 nolock 有效。谢谢!
【解决方案2】:

您需要通过在 select 和 where 子句中定义您需要 UserID 的表来更改您的 sql 语句,例如:

SQLCommand = ("SELECT TP.UserID, Phone "
    "FROM dbo.SEC_UserProfile as TP (nolock) INNER JOIN dbo.SEC_User as TE "
    "ON TP.UserID = TE.UserID "
    "WHERE TP.UserID LIKE ?")

@TabAlleman 是对的,(nolock) 的位置不正确。更新了我的答案。

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 2015-05-26
    • 2020-12-07
    • 2014-01-06
    • 2019-08-01
    • 2011-01-06
    • 2019-02-09
    • 1970-01-01
    • 2022-08-11
    相关资源
    最近更新 更多