简体   繁体   中英

SqlException was unhandled

Please give me advice, I have code, during its execution is displayed this exception:

SqlException was unhandled The multi-part identifier "T.TerritoryDescription" could not be bound.
The multi-part identifier "T.TerritoryID" could not be bound.
The multi-part identifier "T.TerritoryDescription" could not be bound.

When I run the SQL query in Management Studio I get some result. When I run code with this script in Visual Studio I get exception on this line of code

reader = command.ExecuteReader();

Here is my code:

public void databaseQuestion()
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    SqlCommand command = 
       new SqlCommand((@"select T.TerritoryID,T.TerritoryDescription,avg(O.Freight)
                         from Employees E
                         inner join EmployeeTerritories ET on E.EmployeeID = ET.EmployeeID
                         inner join Orders O on E.EmployeeID = O.EmployeeID
                         where T.TerritoryDescription ='Bedford'
                         group by T.TerritoryID,T.TerritoryDescription,O.Freight") ,con);
    dbFile = filePath + @"\sqlFile.txt";

    SqlDataReader reader;

    con.Open();
    reader = command.ExecuteReader();

    using (StreamWriter file = new StreamWriter(dbFile, false))
    {
        while (reader.Read())
        {
            file.WriteLine(reader["T.TerritoryID"] + "\t" + reader["T.TerritoryDescription"]+ "\t" +reader["O.Freight"]);
        }
    }

    reader.Close();
    con.Close();
}     

error with The multi-part identifier XXXX could not be bound. says that If XXXX is consists of alias name for table, you should check if this alias is already defined for a table in same query. In your scenario you are using an alias with name "T" which has been never defined for any table in your query(you have alias E for Employee, O for Orders and ET for EmployeeTerritories.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM