2013-03-17 203 views
3

我正试图创建一个存储过程,该存储过程在执行时具有日期参数。我希望能够搜索特定日期之间发货的订单。我有这样的:带日期参数的存储过程

create procedure sp_orders_by_dates 
     @startdate smalldatetime, 
     @enddate smalldatetime 
as 
select OrderID, 
     o.CustomerID, 

     c.CompanyName as CustomerCompany, 
     s.ShipperID, 
     s.CompanyName as ShipperCompany, 
     ShippedDate 

from Orders o join Customers c 
on  o.CustomerID = c.CustomerID join Shippers s 
on  s.ShipperID = o.ShipperID 
where @startdate = ShippedDate, 
     @enddate = ShippedDate 
order by ShippedDate 

和执行,我一定要做到这样:

EXEC sp_orders_by_dates '1991-07-01', '1991-08-31' 

我知道这部分是出了什么问题,但我只是无法弄清楚如何使“ “在这里的讲话之间:

where @startdate = ShippedDate, 
     @enddate = ShippedDate 
+0

备注:您应该**不要**为存储过程使用'sp_'前缀。微软已经保留了这个前缀以供自己使用(参见*命名存储过程*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),以及你将来有可能冒着名字冲突的风险。 [这对你的存储过程性能也不好](http://sqlserverpedia.com/blog/sql-server-bloggers/stored-procedure-performance-using-%E2%80%9Csp_%E2%80%9D-prefix- %E2%80%93-神话或-事实/)。最好只是简单地避免使用'sp_'并将其他内容用作前缀 - 或者根本没有前缀! – 2013-03-17 08:51:25

回答

8
where ShippedDate BETWEEN @startdate and @enddate 
+0

很容易:-S – user2104163 2013-03-17 07:00:10

3

下面是在C#中抢:

DataTable t = new DataTable(); 
//set up your connectionString beforhand 
using(SqlConnection cn = new SqlConnection(conn)) 
     { 
      //and isolating the work from everything else 
      try 
      { 
       //configure the query apparatus, using the stored procedure 
       SqlCommand cmd = new SqlCommand(); 
       cmd.Connection = cn; 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.CommandText = "<StoredProcName>"; 

       //set up the parameters 
       SqlParameter prmFrom = cmd.CreateParameter(); 
       prmFrom.Direction = ParameterDirection.Input; 
       prmFrom.ParameterName = "@FromDate"; 
       prmFrom.IsNullable = true; 
       SqlParameter prmTo = cmd.CreateParameter(); 
       prmTo.Direction = ParameterDirection.Input; 
       prmTo.ParameterName = "@ToDate"; 
       prmTo.IsNullable = true; 

       prmFrom.DbType = DbType.DateTime; 
       prmFrom.SqlValue = from; 

       prmTo.DbType = DbType.DateTime; 
       prmTo.SqlValue = to; 

       //make sure the command and the params go together from the app 
       cmd.Parameters.Add(prmFrom); 
       cmd.Parameters.Add(prmTo); 
       SqlDataAdapter da = new SqlDataAdapter(cmd); 

       //finally, fill the table so you can pass it back to the app 
       da.Fill(t); 
      } 
      catch(Exception ex) 
      { 
       //error handling goes here 
      } 
     }