指定字段 'ID' 可以引用多个 table
The specified field 'ID' could refer to more than one table
当我尝试通过 ID 查找时,我总是收到此错误:
system.data.oledb.oledbexception the speciefied field 'ID' could refer
to more than one table listed in the FROM clause of your SQL Statement
这是我的代码:
public static Invoice GetInvoice(string id)
{
OleDbConnection conn = GetConnection();
Invoice invoice = null;
if (conn == null)
{
return null;
}
string sqlString = "SELECT * FROM Person INNER JOIN Employee ON " +
"Person.ID=Employee.ID WHERE ID = @ID";
OleDbCommand comm = new OleDbCommand(sqlString, conn);
comm.Parameters.AddWithValue("@ID", id);
OleDbDataReader dr = null;
try
{
conn.Open();
dr = comm.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
invoice = new Invoice();
invoice.PersonID = (string)dr["ID"];
invoice.FirstName = (string)dr["FirstName"];
invoice.LastName = (string)dr["LastName"];
invoice.Age = (int)dr["Age"];
}
}
catch (Exception ex)
{
invoice = null;
MessageBox.Show(ex.ToString());
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return invoice;
}
您需要更改查询,目前您选择的是通配符“*”,这意味着它将同时提取人员 ID 和员工 ID,但不会有唯一的引用。更改您的通配符以提取准确的表 ID,如下所示:
SELECT Person.ID, FirstName, LastName FROM...
您还需要将 WHERE 语句更改为:
WHERE Person.ID = @ID
因为 where 语句不知道要过滤哪些表 ID(我知道它们是相同的值,但 SQL 不关心那个)
当我尝试通过 ID 查找时,我总是收到此错误:
system.data.oledb.oledbexception the speciefied field 'ID' could refer to more than one table listed in the FROM clause of your SQL Statement
这是我的代码:
public static Invoice GetInvoice(string id)
{
OleDbConnection conn = GetConnection();
Invoice invoice = null;
if (conn == null)
{
return null;
}
string sqlString = "SELECT * FROM Person INNER JOIN Employee ON " +
"Person.ID=Employee.ID WHERE ID = @ID";
OleDbCommand comm = new OleDbCommand(sqlString, conn);
comm.Parameters.AddWithValue("@ID", id);
OleDbDataReader dr = null;
try
{
conn.Open();
dr = comm.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
invoice = new Invoice();
invoice.PersonID = (string)dr["ID"];
invoice.FirstName = (string)dr["FirstName"];
invoice.LastName = (string)dr["LastName"];
invoice.Age = (int)dr["Age"];
}
}
catch (Exception ex)
{
invoice = null;
MessageBox.Show(ex.ToString());
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return invoice;
}
您需要更改查询,目前您选择的是通配符“*”,这意味着它将同时提取人员 ID 和员工 ID,但不会有唯一的引用。更改您的通配符以提取准确的表 ID,如下所示:
SELECT Person.ID, FirstName, LastName FROM...
您还需要将 WHERE 语句更改为:
WHERE Person.ID = @ID
因为 where 语句不知道要过滤哪些表 ID(我知道它们是相同的值,但 SQL 不关心那个)