Search code examples
c#sqlsql-serversqldatareadersqlclient

SqlException The multi-part identifier "A.Column" could not be bound


I'm using SqlDataReader and SqlCommand to pass the following query to my DB

query = "SELECT A.Codigo, A.Descripcion, A.Precio, " +
                    "A.Cantidad, B.Codigo AS [Código de Categoría], B.Descripcion AS [Descripción de Categoría]" +
                    " FROM BuenPrecio.DBO.Producto A" +
                    "INNER JOIN BuenPrecio.DBO.Categoria B " +
                    "ON A.CodigoCategoria = B.Codigo " +
                    "ORDER BY A.CodigoCategoria";

SqlDataReader reader;

conn = new SqlConnection(conexionString);

comando.CommandType = CommandType.Text;
comando.CommandText = query;
comando.Connection = conn;

conn.Open();
reader = comando.ExecuteReader();

(The initial declarations for conn, comando and conexionString were declared before, I'm just not including them in here.)

The query can be successfully executed in SQL Server Management Studio, and it produces the expected results.

But in my C# program, upon attempting to execute it, an SqlException is thrown by the line reader = comando.ExecuteReader():

The multi-part identifier "A.Codigo" could not be bound

(for every A column in the select, not just Codigo)

I've been reading in other similarly titled questions about the issue and most of them say it's a problem with the JOIN lacking a reference to the tables, but as you can see, both of the tables used in the JOIN are correctly referenced and aliased. Furthermore, like I said, the query executes successfully in the DBMS.


Solution

  • You missing spaces between the concatenation in your query, try this :

    "SELECT A.Codigo, A.Descripcion, A.Precio," +
    " A.Cantidad, B.Codigo AS [Código de Categoría], B.Descripcion AS [Descripción de Categoría]" +
    " FROM BuenPrecio.DBO.Producto A" +
    " INNER JOIN BuenPrecio.DBO.Categoria B" +
    " ON A.CodigoCategoria = B.Codigo " +
    " ORDER BY A.CodigoCategoria"