如何在c#代码后面的文件中实现连接查询,并在gridview中显示结果 [英] How to achieve the join query in c# code behind file and display the result in gridview
问题描述
尊敬的先生/女士。
Dear Sir/Madam.
如何在c#代码后面的文件中实现连接查询在gridview中显示结果..
How to achieve the join query in c# code behind file and display the result in gridview..
假设有两个表:产品和销售
产品:
产品ID |名称|制造商|率|日期
----------------------------------------- --------------
1 Scooty TVS 35000 10/10/2012
2 Splendor Hero Honda 50000 5/6/2012 < br $> b $ b
销售:
SaleID |客户ID | ProductID |数量| SoldDate
----------------------------------------- -------------
1 1 2 1 12/12/2012
在这里,我想加入这两个表。它将返回两个表中的匹配记录。
SELECT S.SaleID,P.ProductID,P.ProductName,P.Manfacturer,S.CustomerID,S.SoldDate ,S.Qty,P.Rate,(s.Qty * P.Rate)AS [Total] FROM Products P INNER JOIN Sales S ON s.ProductID = P.ProductID
以上查询返回结果集
SaleID | ProductID |产品名称|制造商|客户ID | SoldDate |数量|率|总计
----------------------------------------- -------------------------------------------------- --------------
1 2 Splendor Hero Honda 1 12/12/2010 1 50000 50000.00
Assume that there are two tables: Products and Sales
Products:
ProductID | Name | Manfacturer | Rate | Date
-------------------------------------------------------
1 Scooty TVS 35000 10/10/2012
2 Splendor Hero Honda 50000 5/6/2012
Sales:
SaleID | CustomerID | ProductID | Qty | SoldDate
------------------------------------------------------
1 1 2 1 12/12/2012
Here i want to join these two tables. It will return the matching records in both tables.
SELECT S.SaleID, P.ProductID, P.ProductName, P.Manfacturer, S.CustomerID, S.SoldDate, S.Qty,P.Rate, (s.Qty * P.Rate) AS [Total] FROM Products P INNER JOIN Sales S ON s.ProductID = P.ProductID
The above query returns the result set as
SaleID | ProductID | ProductName | Manfacturer | CustomerID | SoldDate | Qty | Rate | Total
---------------------------------------------------------------------------------------------------------
1 2 Splendor Hero Honda 1 12/12/2010 1 50000 50000.00
推荐答案
示例代码
sample code
string sql = "SELECT S.SaleID, P.ProductID, P.ProductName, P.Manfacturer, S.CustomerID, S.SoldDate, S.Qty,P.Rate, (s.Qty * P.Rate) AS [Total] FROM Products P INNER JOIN Sales S ON s.ProductID = P.ProductID";
using (SqlConnection con = new SqlConnection("connectionString"))
using (SqlDataAdapter sadp = new SqlDataAdapter(sql, con))
{
DataSet ds = new DataSet();
sadp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
这篇关于如何在c#代码后面的文件中实现连接查询,并在gridview中显示结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!