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

问题描述 投票:1回答:2

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

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

有任何想法吗?

我已经尝试将表名添加到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在两个表中。

python sql sql-server pyodbc
2个回答
4
投票

一个问题是你在错误的地方有(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 ?")

3
投票

您需要通过在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)的地方不正确。更新了我的回答。

© www.soinside.com 2019 - 2024. All rights reserved.