通过传递两个日期参数来查询Dispatch表

时间:2014-03-25 20:33:00

标签: asp.net sql sql-server

我需要通过说明来查看订单明细;通过传递两个日期参数的每周,每月订单。我尝试了几个,但它返回null。

这是我到目前为止的代码:

SELECT A.Dispatch_ID,   
A.Dispatched_Date, 
A.Product_ID, 
A.Product_Code, 
A.Product_Loaded, 
A.Meter_Ticket_ID, 
A.Marketer_ID, 
A.Dispatched_Truck, 
A.Loaded_Quantity, 
A.Loading_Depot, 
A.Over_Loaded, 
A.Under_Loaded,
A.User_Name, 
A.Employee_ID, 
B.Dispatched_Date AS Dispatched_Date1 
FROM ((SELECT Dispatch_ID, Format(Dispatched_Date, 'dd/mm/yyyy') AS Dispatched_Date, Product_ID, Product_Code, Product_Loaded, Meter_Ticket_ID, Marketer_ID, Dispatched_Truck, Loaded_Quantity, Loading_Depot, Over_Loaded, Under_Loaded, User_Name, Employee_ID FROM Dispatched_Entry) A 
INNER JOIN (SELECT Dispatch_ID, Format(Dispatched_Date, 'dd/mm/yyyy') AS Dispatched_Date, Product_ID, Product_Code, Product_Loaded, Meter_Ticket_ID, Marketer_ID, Dispatched_Truck, Loaded_Quantity, Loading_Depot, Over_Loaded, Under_Loaded, User_Name, Employee_ID FROM Dispatched_Entry Dispatched_Entry_1)B ON A.Product_ID = B.Product_ID)
WHERE A.Dispatched_Date =? AND B.Dispatched_Date =?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果要通过SqlCommand实例将参数传递给SQL查询,请使用命名参数。这是C#中的粗略示例:

var query = @"SELECT A.Dispatch_ID, 
              ...
              WHERE A.Dispatched_Date = @dateA AND B.Dispatched_Date = @dateB";
var connection = new SqlConnection(connectionString);
var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@dateA", someDateA);
command.Parameters.AddWithValue("@dateB", someDateB);

MSDN还有其他例子。


直接在ASP.NET中配置SqlDataSource,如下所示:

<asp:dropdownlist
   id="DropDownListA"
   runat="server"
   autopostback="True">
   ...
</asp:dropdownlist>

<asp:dropdownlist
   id="DropDownListB"
   runat="server"
   autopostback="True">
   ...
</asp:dropdownlist>

<asp:sqldatasource
    id="SqlDataSource1"
    runat="server"
    connectionstring="<%$ ConnectionStrings:MyConnectionString %>"
    selectcommand="SELECT A.Dispatch_ID, 
                   ...
                   WHERE A.Dispatched_Date = @dateA AND B.Dispatched_Date = @dateB">
    <selectparameters>
      <asp:controlparameter name="dateA" controlid="DropDownListA" propertyname="SelectedValue"/>
      <asp:controlparameter name="dateB" controlid="DropDownListB" propertyname="SelectedValue"/>
    </selectparameters>
</asp:sqldatasource>

可以在MSDN找到更多信息。