public static DataTable LoadGrid(string SelectedItem,string yearSelected)
{
DataTable tbl;
string a = SelectedItem;
string b = yearSelected;
string query =" SELECT top 10 SalesOrderID, RevisionNumber, OrderDate,DueDate,
"ShipDate, Status,OnlineOrderFlag,SalesOrderNumber,PurchaseOrderNumber,AccountNumber, CustomerID, SalesPersonID, st.Name AS TerritoryName,BillToAddressID, ShipToAddressID,ShipMethodID, CreditCardID, CreditCardApprovalCode,CurrencyRateID, SubTotal, TaxAmt, Freight,TotalDue,Comment, soh.rowguid, soh.ModifiedDate FROM Sales.SalesOrderHeader soh INNER JOIN Sales.SalesTerritory st ON soh.TerritoryID = st.TerritoryID"+
WHERE st.Name = "+a+"AND Datepart(year,OrderDate) = "+b;
tbl=DataAccess.cmd(query);
return (tbl);
}
传递给a
的数据是一个区域,而b是b
是从2个不同的下拉列表开始的年份,但是查询给出的错误是无效的列名加拿大(假设我从中选择加拿大下拉列表)和加拿大是名称列
答案 0 :(得分:0)
错误的原因是因为缺少引号。该查询是当前的
WHERE st.Name = Candada
虽然它应该是
WHERE st.Name = 'Canada'
代替。
请考虑使用存储过程,而不是使用内联SQL查询。
答案 1 :(得分:0)
更具体地说,您应该使用以下语法
string query = string.Format(
"SELECT top 10 SalesOrderID, RevisionNumber, OrderDate,"
+" DueDate,ShipDate, Status,OnlineOrderFlag,SalesOrderNumber,"
+"PurchaseOrderNumber,AccountNumber, CustomerID,SalesPersonID, st.Name AS TerritoryName,"
+"BillToAddressID, ShipToAddressID,ShipMethodID,CreditCardID,"
+"CreditCardApprovalCode,CurrencyRateID, SubTotal, TaxAmt, Freight,TotalDue,Comment,"
+"soh.rowguid, soh.ModifiedDate FROM Sales.SalesOrderHeader soh "
+"INNER JOIN Sales.SalesTerritory st ON soh.TerritoryID = st.TerritoryID "
+" WHERE st.Name='{0}' AND Datepart(year,OrderDate) = '{1}'",a,b);
但在这些工作中使用sp ......:)
答案 2 :(得分:0)
public static DataTable LoadGrid(string selectedItem,string yearSelected)
{
DataTable tbl;
string query = string.Format( @" SELECT top 10 SalesOrderID, RevisionNumber, OrderDate,DueDate,ShipDate, Status,OnlineOrderFlag,SalesOrderNumber,PurchaseOrderNumber,AccountNumber, CustomerID, SalesPersonID, st.Name AS TerritoryName,BillToAddressID, ShipToAddressID,ShipMethodID, CreditCardID, CreditCardApprovalCode,CurrencyRateID, SubTotal, TaxAmt, Freight,TotalDue,Comment, soh.rowguid, soh.ModifiedDate
FROM Sales.SalesOrderHeader as soh
INNER JOIN Sales.SalesTerritory as st
ON soh.TerritoryID = st.TerritoryID
WHERE st.Name = '{0}' AND Datepart(year,OrderDate) = '{1}'", selectedItem, yearSelected);
tbl=DataAccess.cmd(query);
return (tbl);
}
这可以提高代码可读性,从而使编写查询更具可读性,并且不易出现语法错误。
答案 3 :(得分:-1)
SELECT top 10 SalesOrderID, RevisionNumber, OrderDate,DueDate,
"ShipDate, Status,OnlineOrderFlag,SalesOrderNumber,PurchaseOrderNumber,AccountNumber, CustomerID, SalesPersonID, st.Name AS TerritoryName,BillToAddressID, ShipToAddressID,ShipMethodID, CreditCardID, CreditCardApprovalCode,CurrencyRateID, SubTotal, TaxAmt, Freight,TotalDue,Comment, soh.rowguid, soh.ModifiedDate FROM Sales.SalesOrderHeader soh INNER JOIN Sales.SalesTerritory st ON soh.TerritoryID = st.TerritoryID"+
WHERE st.Name = "+a+"AND Datepart(year,OrderDate) = "+b;
为什么使用+运算符一次又一次地组合字符串,效率非常低且难以阅读,为什么不使用"{0}".format()?