我在尝试 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 在两个表中。
请您参考如下方法:
一个问题是你在错误的地方设置了(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 ?")
