如何使用SQL从C#中的两个表中检索多个列?

时间:2012-02-23 16:52:54

标签: c# sql

我有两个表,需要根据ProductID的公共密钥从两个表中检索一些列。我尝试了以下操作,但收到错误“关键字'JOIN'附近的语法不正确”

string selectProductStatement = 
"SELECT Products.Code, Products.Description,"+
"Products.Category, Products.Price, BookProducts.Author"+
"FROM Products"+
"INNER JOIN BookProducts ON (Products.@ProductID = BookProducts.ProductID)";

SqlCommand comm = new SqlCommand(selectProductStatement, connection);
comm.Parameters.AddWithValue("@productID", productID);

表格是:

产品

  ProductID
  Code
  Description
  Category
  Price

BookProducts

  BookID PK
  ProductID FK
  Author

7 个答案:

答案 0 :(得分:4)

您在SQL中缺少空格:

string selectProductStatement = 
    "SELECT Products.Code, Products.Description,"+
    "Products.Category, Products.Price, BookProducts.Author"+
    " FROM Products"+
    " INNER JOIN BookProducts ON (Products.@ProductID = BookProducts.ProductID)";

答案 1 :(得分:3)

Products和INNER之间没有空格。在查询的第3行上的FROM产品之前和之后添加一个空格,你会没事的: - )

答案 2 :(得分:3)

我个人喜欢使用SQL命令的文字字符串来消除所有连接。节省时间和头痛!

在定义字符串之前记下@符号。将命令包装在'using'括号中意味着你不能忘记处理它。

 string selectProductStatement = @"           SELECT 
                                              Products.Code, 
                                              Products.Description,
                                              Products.Category, 
                                              Products.Price, 
                                              BookProducts.Author
                                              FROM Products
                                              INNER JOIN BookProducts 
                                              ON (Products.@ProductID = BookProducts.ProductID) ";
            string connectionString = string.Empty;

            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();

                using (SqlCommand sqlCommand = new SqlCommand(selectProductStatement, sqlConnection))
                {
                    sqlCommand.Parameters.AddWithValue("@productID", productID);

                    //Etc
                }
            }

答案 3 :(得分:2)

估计你需要在"产品"之间留出空间。和" INNER"有伙伴,即

"FROM Products "+
"INNER JOIN BookProducts ON (Products.@ProductID = BookProducts.ProductID)";

答案 4 :(得分:2)

尝试以下

string selectProductStatement = 
"SELECT Products.Code, Products.Description,"+
"Products.Category, Products.Price, BookProducts.Author"+
" FROM Products "+
"INNER JOIN BookProducts ON (Products.ProductID = BookProducts.ProductID) WHERE Products.ProductId = @productID";

答案 5 :(得分:2)

将字符串定义为字符串文字有助于错误的间距:

string selectProductStatement = 
 @"SELECT Products.Code, Products.Description, 
Products.Category, Products.Price,
 BookProducts.Author FROM Products 
INNER JOIN BookProducts ON (Products.@ProductID =
BookProducts.ProductID)";

它省略了多个字符串片段的需要和相关问题/可读性

答案 6 :(得分:0)

SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name;

以上是内连接查询的一般语法。请相应地遵循。 :)